content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
//----------------------------------------------------------------------- // <copyright file="CommonAssemblyInfo.cs" company="ALM | DevOps Ranger Contributors"> // © ALM | DevOps Ranger Contributors // MIT License // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. // </copyright> //----------------------------------------------------------------------- using System.Reflection; using System.Resources; using System.Runtime.InteropServices; [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")] [assembly: AssemblyInformationalVersion("1.0.0.0")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyCopyright("Copyright � Microsoft 2012")] [assembly: AssemblyTrademark("")] [assembly: NeutralResourcesLanguage("")] [assembly: AssemblyCulture("")] [assembly: AssemblyProduct("Coded UI Word Add-in")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)]
49.883721
87
0.695571
[ "MIT" ]
ALM-Rangers/Sample-Code
src/Coded-UI/samples/DevelopmentDev10/Source Code/Common/CommonAssemblyInfo.cs
2,148
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace OpenDebugAD7 { /// <summary> /// Class to hold configuration for a single debug session, such as Just My Code or Require Exact Source settings /// </summary> internal class SessionConfiguration { public bool RequireExactSource { get; set; } = true; public bool JustMyCode { get; set; } = true; public bool StopAtEntrypoint { get; set; } = false; public bool EnableStepFiltering { get; set; } = true; } }
36.647059
117
0.672552
[ "MIT" ]
Bhaskers-Blu-Org2/MIEngine
src/OpenDebugAD7/SessionConfiguration.cs
625
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace GuessFont.Properties { /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if ((resourceMan == null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("GuessFont.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } } }
38.541667
175
0.602523
[ "Apache-2.0" ]
ponchikDnika/GuessFontGame
GuessFont/Properties/Resources.Designer.cs
2,777
C#
using Microsoft.EntityFrameworkCore; using System.Linq; using tcs_service.Models; using tcs_service.Repos.Base; using tcs_service.Repos.Interfaces; namespace tcs_service.Repos { public class SessionClassRepo : BaseRepo<SessionClass>, ISessionClassRepo { public SessionClassRepo(DbContextOptions options) : base(options) { } protected override IQueryable<SessionClass> Include(DbSet<SessionClass> set) => set; } }
27.6875
92
0.767494
[ "MIT" ]
a2937/wvup-tcs
backend/tcs-service/Repos/SessionClassRepo.cs
443
C#
// Copyright (c) Andrew Arnott. All rights reserved. // Licensed under the Microsoft Public License (Ms-PL) license. See LICENSE file in the project root for full license information. namespace PCLCrypto { using System; using System.Collections.Generic; using System.Text; #if !PCL using PCLCrypto.Formatters; #endif using Validation; /// <summary>Extension methods that add functionality to the WinRT crypto API.</summary> public static class WinRTExtensions { /// <summary>Creates a cryptographic key based on the specified RSA parameters.</summary> /// <param name="provider">The asymmetric algorithm provider.</param> /// <param name="parameters">The RSA parameters from which to initialize the key.</param> /// <returns>The cryptographic key.</returns> public static ICryptographicKey ImportParameters(this IAsymmetricKeyAlgorithmProvider provider, RSAParameters parameters) { #if PCL throw new NotImplementedException("Not implemented in reference assembly."); #else Requires.NotNull(provider, "provider"); byte[] keyBlob = KeyFormatter.Pkcs1.Write(parameters); return KeyFormatter.HasPrivateKey(parameters) ? provider.ImportKeyPair(keyBlob, CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey) : provider.ImportPublicKey(keyBlob, CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey); #endif } /// <summary>Exports the RSA parameters of a cryptographic key.</summary> /// <param name="key">The cryptographic key.</param> /// <param name="includePrivateParameters"><c>true</c> to include the private key in the exported parameters; <c>false</c> to only include the public key.</param> /// <returns>The RSA parameters for the key.</returns> public static RSAParameters ExportParameters(this ICryptographicKey key, bool includePrivateParameters) { #if PCL throw new NotImplementedException("Not implemented in reference assembly."); #else Requires.NotNull(key, "key"); byte[] keyBlob = includePrivateParameters ? key.Export(CryptographicPrivateKeyBlobType.Pkcs1RsaPrivateKey) : key.ExportPublicKey(CryptographicPublicKeyBlobType.Pkcs1RsaPublicKey); RSAParameters parameters = KeyFormatter.Pkcs1.Read(keyBlob); return parameters; #endif } /// <summary>Returns a crypto key management for a specified algorithm.</summary> /// <param name="factory">The factory.</param> /// <param name="algorithm">The algorithm.</param> /// <returns>An instance of <see cref="ISymmetricKeyAlgorithmProvider"/>.</returns> public static ISymmetricKeyAlgorithmProvider OpenAlgorithm(this ISymmetricKeyAlgorithmProviderFactory factory, SymmetricAlgorithm algorithm) { Requires.NotNull(factory, nameof(factory)); return factory.OpenAlgorithm(algorithm.GetName(), algorithm.GetMode(), algorithm.GetPadding()); } } }
46.939394
170
0.693673
[ "Apache-2.0" ]
cuteant/IdentityModel
src/PCLCrypto.Shared.Common/WinRTExtensions.cs
3,100
C#
// <copyright file="IIxStdProviderConfig.cs" company="ClrCoder project"> // Copyright (c) ClrCoder project. All rights reserved. // Licensed under the Apache 2.0 license. See LICENSE file in the project root for full license information. // </copyright> namespace ClrCoder.ComponentModel.IndirectX { using JetBrains.Annotations; /// <summary> /// Standard provider node config. /// </summary> public interface IIxStdProviderConfig : IIxProviderNodeConfig { /// <summary> /// Scope binding strategy config (registration, transient, etc.). /// </summary> [CanBeNull] IIxScopeBindingConfig ScopeBinding { get; } /// <summary> /// Multiplicity config. (Singleton, pool, factory etc.). /// </summary> [CanBeNull] IIxMultiplicityConfig Multiplicity { get; } /// <summary> /// Instance builder config. (Class constructor, existing instance, etc.). /// </summary> [CanBeNull] IIxInstanceBuilderConfig InstanceBuilder { get; } /// <summary> /// Enables auto dispose when no more external locks exists. /// </summary> bool AutoDisposeEnabled { get; } /// <summary> /// Overrides dispose operation. /// </summary> [CanBeNull] IxDisposeHandlerDelegate DisposeHandler { get; } } }
30.977778
108
0.61693
[ "MIT" ]
ClrCoder/ClrCoderFX
src/ClrCoder/ComponentModel/IndirectX/Config/IIxStdProviderConfig.cs
1,394
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading; using Grace.Data.Immutable; using Grace.DependencyInjection.Exceptions; using Grace.DependencyInjection.Impl.KnownTypeStrategies; using Grace.DependencyInjection.Impl.Wrappers; using Grace.Diagnostics; namespace Grace.DependencyInjection.Impl { /// <summary> /// Root injection scope that is inherited by the Dependency injection container /// </summary> [DebuggerDisplay("{" + nameof(DebugDisplayString) + ",nq}")] [DebuggerTypeProxy(typeof(InjectionScopeDebuggerView))] public class InjectionScope : BaseExportLocatorScope, IInjectionScope { #region Fields /// <summary> /// Internal field storage /// </summary> protected InternalFieldStorageClass InternalFieldStorage = new InternalFieldStorageClass(); /// <summary> /// string constant that is used to locate a lock for adding strategies to the container /// Note: Do not use this unless you are working on container internals /// </summary> public const string ActivationStrategyAddLockName = "ActivationStrategyAddLock"; #endregion #region Constructors /// <summary> /// Constructor that takes configuration action /// </summary> /// <param name="configuration">configuration action</param> public InjectionScope(Action<InjectionScopeConfiguration> configuration) : this(CreateConfiguration(configuration), null, "RootScope") { } /// <summary> /// Constructor takes a configuration object /// </summary> /// <param name="configuration"></param> public InjectionScope(IInjectionScopeConfiguration configuration) : this(configuration, null, "RootScope") { } /// <summary> /// Configuration object constructor /// </summary> /// <param name="configuration"></param> /// <param name="parent"></param> /// <param name="name"></param> public InjectionScope(IInjectionScopeConfiguration configuration, IInjectionScope parent, string name) : base(parent, name, new ActivationStrategyDelegateCache()) { configuration.SetInjectionScope(this); InternalFieldStorage.ScopeConfiguration = configuration; InternalFieldStorage.InjectionContextCreator = configuration.Implementation.Locate<IInjectionContextCreator>(); InternalFieldStorage.CanLocateTypeService = configuration.Implementation.Locate<ICanLocateTypeService>(); InternalFieldStorage.ActivationStrategyCompiler = configuration.Implementation.Locate<IActivationStrategyCompiler>(); InternalFieldStorage.StrategyCollectionContainer = AddDisposable(configuration.Implementation.Locate<IActivationStrategyCollectionContainer<ICompiledExportStrategy>>()); InternalFieldStorage.DecoratorCollectionContainer = AddDisposable(configuration.Implementation.Locate<IActivationStrategyCollectionContainer<ICompiledDecoratorStrategy>>()); if (configuration.AutoRegisterUnknown && Parent == null) { InternalFieldStorage.MissingExportStrategyProviders = InternalFieldStorage.MissingExportStrategyProviders.Add( configuration.Implementation.Locate<IMissingExportStrategyProvider>()); } if (configuration.SupportFuncType) { StrategyCollectionContainer.AddStrategy(new FuncTypeStrategy(this)); } } #endregion #region Public members /// <summary> /// Scope configuration /// </summary> public IInjectionScopeConfiguration ScopeConfiguration => InternalFieldStorage.ScopeConfiguration; /// <summary> /// Compiler that produces Activation Strategy Delegates /// </summary> IActivationStrategyCompiler IInjectionScope.StrategyCompiler => InternalFieldStorage.ActivationStrategyCompiler; /// <summary> /// Can Locator type /// </summary> /// <param name="type">type to locate</param> /// <param name="consider"></param> /// <param name="key">key to use while locating</param> /// <returns></returns> public override bool CanLocate(Type type, ActivationStrategyFilter consider = null, object key = null) { return InternalFieldStorage.CanLocateTypeService.CanLocate(this, type, consider, key); } /// <summary> /// Locate specific type using extra data or key /// </summary> /// <param name="type">type to locate</param> /// <param name="extraData">extra data to be used during construction</param> /// <param name="consider">filter out exports you don't want to consider</param> /// <param name="withKey">key to use for locating type</param> /// <param name="isDynamic">skip cache and look through exports</param> /// <returns>located instance</returns> // ReSharper disable once MethodOverloadWithOptionalParameter public override object Locate(Type type, object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false) { IInjectionContext context = extraData == null ? null : CreateInjectionContextFromExtraData(type, extraData); if (withKey == null && consider == null && !isDynamic) { return DelegateCache.ExecuteActivationStrategyDelegateWithContext(type, this, false, context); } return InternalLocate(this, this, type, consider, withKey, context, false, isDynamic); } /// <summary> /// Locate specific type using extra data or key /// </summary> /// <typeparam name="T">type to locate</typeparam> /// <param name="extraData">extra data</param> /// <param name="consider">filter out exports you don't want to consider</param> /// <param name="withKey">key to use during construction</param> /// <param name="isDynamic">skip cache and look at all strategies</param> /// <returns>located instance</returns> // ReSharper disable once MethodOverloadWithOptionalParameter public override T Locate<T>(object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false) { return (T)Locate(typeof(T), extraData, consider, withKey, isDynamic); } /// <summary> /// Locate all instances of a type /// </summary> /// <param name="type">type to locate</param> /// <param name="extraData">extra data </param> /// <param name="consider">provide method to filter out exports</param> /// <param name="comparer">comparer to use for sorting</param> /// <returns>list of all type</returns> public override List<object> LocateAll(Type type, object extraData = null, ActivationStrategyFilter consider = null, IComparer<object> comparer = null) { return ((IInjectionScope)this).InternalLocateAll(this, this, type, extraData, consider, comparer); } /// <summary> /// Locate all of a specific type /// </summary> /// <typeparam name="T">type to locate</typeparam> /// <param name="type">type to locate</param> /// <param name="extraData">extra data to use during construction</param> /// <param name="consider">provide method to filter out exports</param> /// <param name="comparer">comparer to use for sorting</param> /// <returns>list of all located</returns> public override List<T> LocateAll<T>(Type type = null, object extraData = null, ActivationStrategyFilter consider = null, IComparer<T> comparer = null) { return ((IInjectionScope)this).InternalLocateAll(this, this, type ?? typeof(T), extraData, consider, comparer); } /// <summary> /// Try to locate a specific type /// </summary> /// <typeparam name="T"></typeparam> /// <param name="value">located value</param> /// <param name="extraData">extra data to be used during construction</param> /// <param name="consider">filter out exports you don't want</param> /// <param name="withKey">key to use while locating</param> /// <param name="isDynamic">skip cache and look at all exports</param> /// <returns></returns> public override bool TryLocate<T>(out T value, object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false) { var context = CreateInjectionContextFromExtraData(typeof(T), extraData); var newValue = InternalLocate(this, this, typeof(T), consider, withKey, context, true, isDynamic); var returnValue = false; if (newValue != null) { returnValue = true; value = (T)newValue; } else { value = default(T); } return returnValue; } /// <summary> /// Try to locate an export by type /// </summary> /// <param name="type">locate type</param> /// <param name="value">out value</param> /// <param name="extraData">extra data to use during locate</param> /// <param name="consider">filter out exports you don't want</param> /// <param name="withKey">key to use during locate</param> /// <param name="isDynamic">skip cache and look at all exports</param> /// <returns>returns tue if export found</returns> public override bool TryLocate(Type type, out object value, object extraData = null, ActivationStrategyFilter consider = null, object withKey = null, bool isDynamic = false) { var context = CreateInjectionContextFromExtraData(type, extraData); value = InternalLocate(this, this, type, consider, withKey, context, true, isDynamic); return value != null; } /// <summary> /// Locate by name /// </summary> /// <param name="name"></param> /// <param name="extraData"></param> /// <param name="consider"></param> /// <returns></returns> public override object LocateByName(string name, object extraData = null, ActivationStrategyFilter consider = null) { return ((IInjectionScope)this).LocateByNameFromChildScope(this, this, name, extraData, consider, false); } /// <summary> /// Locate all by specific name /// </summary> /// <param name="name"></param> /// <param name="extraData"></param> /// <param name="consider"></param> /// <returns></returns> public override List<object> LocateAllByName(string name, object extraData = null, ActivationStrategyFilter consider = null) { return ((IInjectionScope)this).InternalLocateAllByName(this, this, name, extraData, consider); } /// <summary> /// Try to locate by name /// </summary> /// <param name="name"></param> /// <param name="value"></param> /// <param name="extraData"></param> /// <param name="consider"></param> /// <returns></returns> public override bool TryLocateByName(string name, out object value, object extraData = null, ActivationStrategyFilter consider = null) { value = ((IInjectionScope)this).LocateByNameFromChildScope(this, this, name, extraData, consider, true); return value != null; } /// <summary> /// Being lifetime scope /// </summary> /// <param name="scopeName"></param> /// <returns></returns> public override IExportLocatorScope BeginLifetimeScope(string scopeName = "") { return new LifetimeScope(this, this, scopeName, DelegateCache); } /// <summary> /// Create injection context /// </summary> /// <param name="extraData">extra data</param> /// <returns></returns> public override IInjectionContext CreateContext(object extraData = null) { return InternalFieldStorage.InjectionContextCreator.CreateContext(extraData); } /// <summary> /// Configure the injection scope /// </summary> /// <param name="registrationBlock"></param> public void Configure(Action<IExportRegistrationBlock> registrationBlock) { lock (GetLockObject(ActivationStrategyAddLockName)) { var provider = ScopeConfiguration.Implementation.Locate<IExportRegistrationBlockValueProvider>(); registrationBlock(provider); foreach (var inspector in provider.GetInspectors()) { StrategyCollectionContainer.AddInspector(inspector); WrapperCollectionContainer.AddInspector(inspector); DecoratorCollectionContainer.AddInspector(inspector); } foreach (var missingExportStrategyProvider in provider.GetMissingExportStrategyProviders()) { InternalFieldStorage.MissingExportStrategyProviders = InternalFieldStorage.MissingExportStrategyProviders.Add(missingExportStrategyProvider); } foreach (var expressionProvider in provider.GetMissingDependencyExpressionProviders()) { InternalFieldStorage.MissingDependencyExpressionProviders = InternalFieldStorage.MissingDependencyExpressionProviders.Add(expressionProvider); } foreach (var injectionValueProvider in provider.GetValueProviders()) { InternalFieldStorage.ValueProviders = InternalFieldStorage.ValueProviders.Add(injectionValueProvider); } foreach (var compiledWrapperStrategy in provider.GetWrapperStrategies()) { WrapperCollectionContainer.AddStrategy(compiledWrapperStrategy); } foreach (var decorator in provider.GetDecoratorStrategies()) { DecoratorCollectionContainer.AddStrategy(decorator); } foreach (var strategy in provider.GetExportStrategies()) { StrategyCollectionContainer.AddStrategy(strategy); foreach (var secondaryStrategy in strategy.SecondaryStrategies()) { StrategyCollectionContainer.AddStrategy(secondaryStrategy); } } foreach (var selector in provider.GetMemberInjectionSelectors()) { InternalFieldStorage.MemberInjectionSelectors = InternalFieldStorage.MemberInjectionSelectors.Add(selector); } } } /// <summary> /// Configure with module /// </summary> /// <param name="module">configuration module</param> public void Configure(IConfigurationModule module) { if (module == null) throw new ArgumentNullException(nameof(module)); Configure(module.Configure); } /// <summary> /// Strategies associated with this scope /// </summary> public IActivationStrategyCollectionContainer<ICompiledExportStrategy> StrategyCollectionContainer => InternalFieldStorage.StrategyCollectionContainer; /// <summary> /// Wrappers associated with this scope /// </summary> public IActivationStrategyCollectionContainer<ICompiledWrapperStrategy> WrapperCollectionContainer => InternalFieldStorage.Wrappers ?? GetWrappers(); /// <summary> /// Decorators associated with this scope /// </summary> public IActivationStrategyCollectionContainer<ICompiledDecoratorStrategy> DecoratorCollectionContainer => InternalFieldStorage.DecoratorCollectionContainer; /// <summary> /// Member /// </summary> public IEnumerable<IMemberInjectionSelector> MemberInjectionSelectors => InternalFieldStorage.MemberInjectionSelectors; /// <summary> /// List of missing export strategy providers /// </summary> public IEnumerable<IMissingExportStrategyProvider> MissingExportStrategyProviders => InternalFieldStorage.MissingExportStrategyProviders; /// <summary> /// List of missing dependency expression providers /// </summary> public IEnumerable<IMissingDependencyExpressionProvider> MissingDependencyExpressionProviders => InternalFieldStorage.MissingDependencyExpressionProviders; /// <summary> /// List of value providers that can be used during construction of linq expression /// </summary> public IEnumerable<IInjectionValueProvider> InjectionValueProviders => InternalFieldStorage.ValueProviders; /// <summary> /// Locate an export from a child scope /// </summary> /// <param name="childScope">scope where the locate originated</param> /// <param name="disposalScope"></param> /// <param name="type">type to locate</param> /// <param name="extraData"></param> /// <param name="consider"></param> /// <param name="key"></param> /// <param name="allowNull"></param> /// <param name="isDynamic"></param> /// <returns>configuration object</returns> object IInjectionScope.LocateFromChildScope(IExportLocatorScope childScope, IDisposalScope disposalScope, Type type, object extraData, ActivationStrategyFilter consider, object key, bool allowNull, bool isDynamic) { return InternalLocate(childScope, disposalScope, type, consider, key, CreateInjectionContextFromExtraData(type, extraData), allowNull, isDynamic); } /// <summary> /// /// </summary> /// <param name="childScope"></param> /// <param name="disposalScope"></param> /// <param name="name"></param> /// <param name="extraData"></param> /// <param name="consider"></param> /// <param name="allowNull"></param> /// <returns></returns> object IInjectionScope.LocateByNameFromChildScope(IExportLocatorScope childScope, IDisposalScope disposalScope, string name, object extraData, ActivationStrategyFilter consider, bool allowNull) { var collection = StrategyCollectionContainer.GetActivationStrategyCollectionByName(name); ICompiledExportStrategy strategy = null; if (collection != null) { if (consider != null) { var context = new StaticInjectionContext(typeof(object)); strategy = collection.GetStrategies() .FirstOrDefault( s => (!s.HasConditions || s.Conditions.All(con => con.MeetsCondition(s, context))) && consider(s)); } else { strategy = collection.GetPrimary(); if (strategy == null) { var context = new StaticInjectionContext(typeof(object)); strategy = collection.GetStrategies() .FirstOrDefault( s => !s.HasConditions || s.Conditions.All(con => con.MeetsCondition(s, context))); } } } if (strategy != null) { var strategyDelegate = strategy.GetActivationStrategyDelegate(this, InternalFieldStorage.ActivationStrategyCompiler, typeof(object)); return strategyDelegate(childScope, disposalScope, CreateContext(extraData)); } if (Parent != null) { return ((IInjectionScope)Parent).LocateByNameFromChildScope(childScope, disposalScope, name, extraData, consider, allowNull); } if (!allowNull) { throw new LocateException(new StaticInjectionContext(typeof(object))); } return null; } /// <summary> /// Internal locate all method /// </summary> /// <typeparam name="T"></typeparam> /// <param name="scope"></param> /// <param name="disposalScope"></param> /// <param name="type"></param> /// <param name="extraData"></param> /// <param name="consider"></param> /// <param name="comparer"></param> /// <returns></returns> List<T> IInjectionScope.InternalLocateAll<T>(IExportLocatorScope scope, IDisposalScope disposalScope, Type type, object extraData, ActivationStrategyFilter consider, IComparer<T> comparer) { var returnList = new List<T>(); var context = CreateInjectionContextFromExtraData(typeof(T), extraData); var collection = StrategyCollectionContainer.GetActivationStrategyCollection(type); if (collection != null) { LocateEnumerablesFromStrategyCollection(collection, scope, disposalScope, type, context, consider, returnList); } if (type.IsConstructedGenericType) { var genericType = type.GetGenericTypeDefinition(); collection = StrategyCollectionContainer.GetActivationStrategyCollection(genericType); if (collection != null) { LocateEnumerablesFromStrategyCollection(collection, scope, disposalScope, type, context, consider, returnList); } } var injectionParent = Parent as IInjectionScope; if (injectionParent != null) { returnList.AddRange(injectionParent.InternalLocateAll<T>(scope, disposalScope, type, context, consider, null)); } if (comparer != null) { returnList.Sort(comparer); } return returnList; } /// <summary> /// /// </summary> /// <param name="scope"></param> /// <param name="disposalScope"></param> /// <param name="exportName"></param> /// <param name="extraData"></param> /// <param name="consider"></param> /// <returns></returns> List<object> IInjectionScope.InternalLocateAllByName(IExportLocatorScope scope, IDisposalScope disposalScope, string exportName, object extraData, ActivationStrategyFilter consider) { var context = CreateContext(extraData); var returnList = new List<object>(); var collection = StrategyCollectionContainer.GetActivationStrategyCollectionByName(exportName); foreach (var strategy in collection.GetStrategies()) { if (consider == null || consider(strategy)) { var activation = strategy.GetActivationStrategyDelegate(this, InternalFieldStorage.ActivationStrategyCompiler, typeof(object)); returnList.Add(activation(scope, disposalScope, context.Clone())); } } var injectionScopeParent = Parent as IInjectionScope; if (injectionScopeParent != null) { returnList.AddRange(injectionScopeParent.InternalLocateAllByName(scope, disposalScope, exportName, context, consider)); } return returnList; } /// <summary> /// Creates a new child scope /// This is best used for long term usage, not per request scenario /// </summary> /// <param name="configure">configure scope</param> /// <param name="scopeName">scope name </param> /// <returns></returns> public IInjectionScope CreateChildScope(Action<IExportRegistrationBlock> configure = null, string scopeName = "") { var newScope = new InjectionScope(ScopeConfiguration.Clone(), this, scopeName); if (configure != null) { newScope.Configure(configure); } return newScope; } #endregion #region Non public members /// <summary> /// Creates a new configuration object /// </summary> /// <param name="configuration"></param> /// <returns></returns> protected static IInjectionScopeConfiguration CreateConfiguration(Action<InjectionScopeConfiguration> configuration) { var configurationObject = new InjectionScopeConfiguration(); configuration?.Invoke(configurationObject); return configurationObject; } /// <summary> /// Create an injection context from extra data /// </summary> /// <param name="type"></param> /// <param name="extraData"></param> /// <returns></returns> protected virtual IInjectionContext CreateInjectionContextFromExtraData(Type type, object extraData) { return CreateContext(extraData); } private object InternalLocate(IExportLocatorScope scope, IDisposalScope disposalScope, Type type, ActivationStrategyFilter consider, object key, IInjectionContext injectionContext, bool allowNull, bool isDynamic) { if (type == typeof(ILocatorService) || type == typeof(IExportLocatorScope)) { return scope; } if (isDynamic) { if (type.IsArray) { return DynamicArray(scope, disposalScope, type, consider, injectionContext); } if (type.IsConstructedGenericType && type.GetGenericTypeDefinition() == typeof(IEnumerable<>)) { return DynamicIEnumerable(scope, disposalScope, type, consider, injectionContext); } } var compiledDelegate = InternalFieldStorage.ActivationStrategyCompiler.FindDelegate(this, type, consider, key, injectionContext, InternalFieldStorage.MissingExportStrategyProviders != ImmutableLinkedList<IMissingExportStrategyProvider>.Empty); if (compiledDelegate != null) { if (key == null && consider == null) { compiledDelegate = AddObjectFactory(type, compiledDelegate); } return compiledDelegate(scope, disposalScope ?? scope, injectionContext); } if (Parent != null) { var injectionScopeParent = (IInjectionScope)Parent; return injectionScopeParent.LocateFromChildScope(scope, disposalScope, type, injectionContext, consider, key, allowNull, isDynamic); } if (type == typeof(IInjectionScope) && ScopeConfiguration.Behaviors.AllowInjectionScopeLocation) { return scope; } var value = ScopeConfiguration.Implementation.Locate<IInjectionContextValueProvider>() .GetValueFromInjectionContext(scope, type, null, injectionContext, !allowNull); if (value != null) { return value; } if (!allowNull) { throw new LocateException(new StaticInjectionContext(type)); } return null; } private object DynamicIEnumerable(IExportLocatorScope scope, IDisposalScope disposalScope, Type type, ActivationStrategyFilter consider, IInjectionContext injectionContext) { if (InternalFieldStorage.DynamicIEnumerableLocator == null) { Interlocked.CompareExchange(ref InternalFieldStorage.DynamicIEnumerableLocator, ScopeConfiguration.Implementation.Locate<IDynamicIEnumerableLocator>(), null); } return InternalFieldStorage.DynamicIEnumerableLocator.Locate(this, scope, disposalScope, type, consider, injectionContext); } private object DynamicArray(IExportLocatorScope scope, IDisposalScope disposalScope, Type type, ActivationStrategyFilter consider, IInjectionContext injectionContext) { if (InternalFieldStorage.DynamicArrayLocator == null) { Interlocked.CompareExchange(ref InternalFieldStorage.DynamicArrayLocator, ScopeConfiguration.Implementation.Locate<IDynamicArrayLocator>(), null); } return InternalFieldStorage.DynamicArrayLocator.Locate(this, scope, disposalScope, type, consider, injectionContext); } private ActivationStrategyDelegate AddObjectFactory(Type type, ActivationStrategyDelegate activationStrategyDelegate) { DelegateCache.AddDelegate(type, activationStrategyDelegate); return activationStrategyDelegate; } private IActivationStrategyCollectionContainer<ICompiledWrapperStrategy> GetWrappers() { if (InternalFieldStorage.Wrappers != null) { return InternalFieldStorage.Wrappers; } var wrapperCollectionProvider = ScopeConfiguration.Implementation.Locate<IDefaultWrapperCollectionProvider>(); if (Interlocked.CompareExchange(ref InternalFieldStorage.Wrappers, wrapperCollectionProvider.ProvideCollection(this), null) == null) { AddDisposable(InternalFieldStorage.Wrappers); } return InternalFieldStorage.Wrappers; } private void LocateEnumerablesFromStrategyCollection<TStrategy, TValue>(IActivationStrategyCollection<TStrategy> collection, IExportLocatorScope scope, IDisposalScope disposalScope, Type type, IInjectionContext context, ActivationStrategyFilter filter, List<TValue> returnList) where TStrategy : IWrapperOrExportActivationStrategy { foreach (var strategy in collection.GetStrategies()) { ProcessStrategyForCollection(scope, disposalScope, type, context, filter, returnList, strategy); } if (InternalFieldStorage.ScopeConfiguration.ReturnKeyedInEnumerable) { foreach (var keyValuePair in collection.GetKeyedStrategies()) { ProcessStrategyForCollection(scope, disposalScope, type, context, filter, returnList, keyValuePair.Value); } } } private void ProcessStrategyForCollection<TStrategy, TValue>(IExportLocatorScope scope, IDisposalScope disposalScope, Type type, IInjectionContext context, ActivationStrategyFilter filter, List<TValue> returnList, TStrategy strategy) where TStrategy : IWrapperOrExportActivationStrategy { if (strategy.HasConditions) { var pass = true; foreach (var condition in strategy.Conditions) { if (!condition.MeetsCondition(strategy, new StaticInjectionContext(type))) { pass = false; break; } } if (!pass) { return; } } if (filter != null && !filter(strategy)) { return; } var activationDelegate = strategy.GetActivationStrategyDelegate(this, InternalFieldStorage.ActivationStrategyCompiler, type); if (activationDelegate != null) { returnList.Add( (TValue)activationDelegate(scope, disposalScope, context?.Clone())); } } private string DebugDisplayString => "Exports: " + StrategyCollectionContainer.GetAllStrategies().Count(); #endregion #region Internal storage class /// <summary> /// Class for storing fields for injection scope, /// Fields that are not on the fast path are put in this class to keep the injection scope as light as possible /// </summary> protected class InternalFieldStorageClass { /// <summary> /// List of member injection selectors /// </summary> public ImmutableLinkedList<IMemberInjectionSelector> MemberInjectionSelectors = ImmutableLinkedList<IMemberInjectionSelector>.Empty; /// <summary> /// List of missing dependency expression providers /// </summary> public ImmutableLinkedList<IMissingDependencyExpressionProvider> MissingDependencyExpressionProviders = ImmutableLinkedList<IMissingDependencyExpressionProvider>.Empty; /// <summary> /// Dynamic array locator /// </summary> public IDynamicArrayLocator DynamicArrayLocator; /// <summary> /// dynamic ienumerable locator /// </summary> public IDynamicIEnumerableLocator DynamicIEnumerableLocator; /// <summary> /// Wrappers for scope /// </summary> public IActivationStrategyCollectionContainer<ICompiledWrapperStrategy> Wrappers; /// <summary> /// Value providers /// </summary> public ImmutableLinkedList<IInjectionValueProvider> ValueProviders = ImmutableLinkedList<IInjectionValueProvider>.Empty; /// <summary> /// Missing export strategy providers /// </summary> public ImmutableLinkedList<IMissingExportStrategyProvider> MissingExportStrategyProviders = ImmutableLinkedList<IMissingExportStrategyProvider>.Empty; /// <summary> /// activation strategy compiler /// </summary> public IActivationStrategyCompiler ActivationStrategyCompiler; /// <summary> /// Strategy collection /// </summary> public IActivationStrategyCollectionContainer<ICompiledExportStrategy> StrategyCollectionContainer; /// <summary> /// Decorators /// </summary> public IActivationStrategyCollectionContainer<ICompiledDecoratorStrategy> DecoratorCollectionContainer; /// <summary> /// Scope configuration /// </summary> public IInjectionScopeConfiguration ScopeConfiguration; /// <summary> /// Creates injection context when needed /// </summary> public IInjectionContextCreator InjectionContextCreator; /// <summary> /// Implementation to tell if a type can be located /// </summary> public ICanLocateTypeService CanLocateTypeService; } #endregion } }
40.974943
338
0.607238
[ "MIT" ]
Lex45x/Grace
src/Grace/DependencyInjection/Impl/InjectionScope.cs
35,976
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _02.Pets { class Pets { static void Main(string[] args) { int days = int.Parse(Console.ReadLine()); int food = int.Parse(Console.ReadLine()); // kg double dogFood = double.Parse(Console.ReadLine()); //kg for day double catFood = double.Parse(Console.ReadLine()); //kg for day double turtleFood = double.Parse(Console.ReadLine()); //g for day double dogNeed = days * dogFood; double catNeed = days * catFood; double turtleNeed = (days * turtleFood) / 1000; double allTheFood = dogNeed + catNeed + turtleNeed; if(food >= allTheFood) { Console.WriteLine("{0} kilos of food left.",Math.Floor(food - allTheFood)); } else { Console.WriteLine("{0} more kilos of food are needed.", Math.Ceiling(allTheFood - food)); } } } }
28.868421
105
0.557885
[ "MIT" ]
1ooIL40/FundamentalsRepo
new project 04.03/Programming Basics Exam - 20 November 2016 - Morning/02. Pets/Pets.cs
1,099
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using StarkPlatform.CodeAnalysis; using System.Diagnostics; namespace StarkPlatform.VisualStudio.LanguageServices.Implementation { internal sealed class AnalyzerDependencyConflict { public AnalyzerDependencyConflict(AssemblyIdentity identity, string analyzerFilePath1, string analyzerFilePath2) { Debug.Assert(identity != null); Debug.Assert(analyzerFilePath1 != null); Debug.Assert(analyzerFilePath2 != null); Identity = identity; AnalyzerFilePath1 = analyzerFilePath1; AnalyzerFilePath2 = analyzerFilePath2; } public string AnalyzerFilePath1 { get; } public string AnalyzerFilePath2 { get; } public AssemblyIdentity Identity { get; } } }
36.076923
161
0.698294
[ "Apache-2.0" ]
stark-lang/stark-roslyn
src/VisualStudio/Core/Def/Implementation/AnalyzerDependency/AnalyzerDependencyConflict.cs
940
C#
using DCL.Interface; using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using static HotScenesController; public interface IPlacesAPIController { /// <summary> /// Request all places from the server. /// </summary> /// <param name="OnCompleted">It will be triggered when the operation has finished successfully.</param> void GetAllPlaces(Action<List<HotSceneInfo>> OnCompleted); } [ExcludeFromCodeCoverage] public class PlacesAPIController : IPlacesAPIController { internal Action<List<HotSceneInfo>> OnGetOperationCompleted; public void GetAllPlaces(Action<List<HotSceneInfo>> OnCompleted) { OnGetOperationCompleted = OnCompleted; WebInterface.FetchHotScenes(); HotScenesController.i.OnHotSceneListFinishUpdating -= OnFetchHotScenes; HotScenesController.i.OnHotSceneListFinishUpdating += OnFetchHotScenes; } internal void OnFetchHotScenes() { HotScenesController.i.OnHotSceneListFinishUpdating -= OnFetchHotScenes; OnGetOperationCompleted?.Invoke(HotScenesController.i.hotScenesList); } }
31.305556
108
0.755989
[ "Apache-2.0" ]
CarlosPolygonalMind/unity-renderer
unity-renderer/Assets/Scripts/MainScripts/DCL/Controllers/ExploreV2/Scripts/Sections/PlacesAndEventsSection/SubSections/PlacesSubSection/PlacesSubSectionMenu/PlacesAPIController.cs
1,127
C#
using System.Windows.Input; namespace tweetz5.Commands { internal static class UpdateLayoutCommand { public static readonly RoutedCommand Command = new RoutedUICommand(); } }
22.666667
78
0.70098
[ "MIT" ]
mike-ward/tweetz-desktop
tweetz/tweetz5/Commands/UpdateLayoutCommand.cs
206
C#
#region MigraDoc - Creating Documents on the Fly // // Authors: // Klaus Potzesny (mailto:Klaus.Potzesny@pdfsharp.com) // // Copyright (c) 2001-2009 empira Software GmbH, Cologne (Germany) // // http://www.pdfsharp.com // http://www.migradoc.com // http://sourceforge.net/projects/pdfsharp // // Permission is hereby granted, free of charge, to any person obtaining a // copy of this software and associated documentation files (the "Software"), // to deal in the Software without restriction, including without limitation // the rights to use, copy, modify, merge, publish, distribute, sublicense, // and/or sell copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included // in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL // THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER // DEALINGS IN THE SOFTWARE. #endregion using System; using System.Collections; namespace MigraDoc.Rendering { /// <summary> /// Represents a class that provides a series of Areas to render into. /// </summary> internal interface IAreaProvider { /// <summary> /// Gets the next area to render into. /// </summary> Area GetNextArea(); /// <summary> /// Probes the next area to render into like GetNextArea, but doesn't change the provider state. /// </summary> /// <returns>The area for the next rendering act.</returns> Area ProbeNextArea(); FieldInfos AreaFieldInfos { get; } /// <summary> /// Determines whether the element requires an area break before. /// </summary> bool IsAreaBreakBefore(LayoutInfo layoutInfo); /// <summary> /// Positions the element vertically relatively to the current area. /// </summary> /// <param name="layoutInfo">The layout info of the element.</param> /// <returns>True, if the element was moved by the function.</returns> bool PositionVertically(LayoutInfo layoutInfo); /// <summary> /// Positions the element horizontally relatively to the current area. /// </summary> /// <param name="layoutInfo">The layout info of the element.</param> /// <returns>True, if the element was moved by the function.</returns> bool PositionHorizontally(LayoutInfo layoutInfo); /// <summary> /// Stores the RenderInfos of elements on the current area. /// </summary> /// <param name="renderInfos"></param> void StoreRenderInfos(ArrayList renderInfos); } }
35.795181
101
0.703803
[ "MIT" ]
HiraokaHyperTools/PDFsharp
MigraDoc/code/MigraDoc.Rendering/MigraDoc.Rendering/IAreaProvider.cs
2,971
C#
using System.Collections.Generic; using System.Runtime.Serialization; namespace Nest { public class GetTransformResponse : ResponseBase { /// <summary> /// The count of transforms. /// </summary> [DataMember(Name = "count")] public long Count { get; internal set; } /// <summary> /// An array of transform resources /// </summary> [DataMember(Name = "transforms")] public IReadOnlyCollection<Transform> Transforms { get; internal set; } = EmptyReadOnly<Transform>.Collection; } }
24.047619
112
0.69901
[ "Apache-2.0" ]
RPM1984/elasticsearch-net
src/Nest/XPack/Transform/GetTransform/GetTransformResponse.cs
505
C#
/* feedseekclr: test program for mpg123clr, showing how to use fuzzy seeking in feeder mode copyright 2009 by the mpg123 project - free software under the terms of the LGPL 2.1 see COPYING and AUTHORS files in distribution or http://mpg123.org based on feedseek.c example for libmpg123. Comment (Malcolm Boczek) this CLR example has been written to allow easy comparison to the original feedseek.c example and uses some constructs that would not normally be used in a C# environment, eg: byte[]/ASCII text, Marshal.Copy, static fields, lots of casts etc. */ /* 1.9.0.0 24-Sep-09 Function names harmonized with libmpg123 (mb) */ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.IO; using System.Runtime.InteropServices; using mpg123clr; namespace feedseekclr { class Program { const int WAVE_FORMAT_PCM = 0x0001; const int WAVE_FORMAT_IEEE_FLOAT = 0x0003; static BinaryWriter _out; static long totaloffset, dataoffset; static int rate; static mpg123clr.mpg.channelcount channels; static mpg123clr.mpg.enc enc; static short bitspersample, wavformat; // write wav header static void initwav() { uint tmp32 = 0; ushort tmp16 = 0; byte[] rifftxt = new byte[] { (byte)'R', (byte)'I', (byte)'F', (byte)'F' }; byte[] wavetxt = new byte[] { (byte)'W', (byte)'A', (byte)'V', (byte)'E' }; byte[] fmttxt = new byte[] { (byte)'f', (byte)'m', (byte)'t', (byte)' ' }; byte[] datatxt = new byte[] { (byte)'d', (byte)'a', (byte)'t', (byte)'a' }; _out.Write(rifftxt); totaloffset = _out.BaseStream.Position; _out.Write(tmp32); // total size _out.Write(wavetxt); _out.Write(fmttxt); tmp32 = 16; _out.Write(tmp32); // format length tmp16 = (ushort)wavformat; _out.Write(tmp16); // format tmp16 = (ushort)channels; _out.Write(tmp16); // channels tmp32 = (uint)rate; _out.Write(tmp32); // sample rate tmp32 = (uint) (rate * bitspersample / 8 * (int)channels); _out.Write(tmp32); // bytes / second tmp16 = (ushort)(bitspersample / 8 * (int)channels); // float 16 or signed int 16 _out.Write(tmp16); // block align tmp16 = (ushort)bitspersample; _out.Write(tmp16); // bits per sample _out.Write(datatxt); tmp32 = 0; dataoffset = _out.BaseStream.Position; _out.Write(tmp32); // data length } // rewrite wav header with final length infos static void closewav() { uint tmp32 = 0; // ushort tmp16 = 0; int total = (int)_out.BaseStream.Position; _out.Seek((int)totaloffset, SeekOrigin.Begin); tmp32 = (uint)(total - (totaloffset + 4)); _out.Write(tmp32); _out.Seek((int)dataoffset, SeekOrigin.Begin); tmp32 = (uint)(total - (dataoffset + 4)); _out.Write(tmp32); } // determine correct wav format and bits per sample // from mpg123 enc value static void initwavformat() { if ((enc & mpg123clr.mpg.enc.enc_float_64) != 0) { bitspersample = 64; wavformat = WAVE_FORMAT_IEEE_FLOAT; } else if ((enc & mpg123clr.mpg.enc.enc_float_32) != 0) { bitspersample = 32; wavformat = WAVE_FORMAT_IEEE_FLOAT; } else if ((enc & mpg123clr.mpg.enc.enc_16) != 0) { bitspersample = 16; wavformat = WAVE_FORMAT_PCM; } else { bitspersample = 8; wavformat = WAVE_FORMAT_PCM; } } static void Main(string[] args) { const long INBUFF = 16384 * 2 * 2; int ret; mpg123clr.mpg.ErrorCode state; long inoffset,inc = 0; long outc = 0; byte[] buf = new byte[INBUFF]; if (args.Length < 2) { Console.WriteLine("Please supply in and out filenames\n"); Console.WriteLine("Press any key to exit:"); while (Console.Read() == 0) ; return; } mpg123clr.mpg.ErrorCode err; err = mpg123.mpg123_init(); mpg123 mp = new mpg123(); err = mp.mpg123_new(); if (err != mpg123clr.mpg.ErrorCode.ok) { Console.WriteLine("Unable to create mpg123 handle: " + mpg123error.mpg123_plain_strerror(err)); Console.WriteLine("Press any key to exit:"); while (Console.Read() == 0) ; return; } mp.mpg123_param(mpg123clr.mpg.parms.verbose, 4, 0); err = mp.mpg123_param(mpg123clr.mpg.parms.flags, (int) (mpg123clr.mpg.param_flags.fuzzy | mpg123clr.mpg.param_flags.seekbuffer | mpg123clr.mpg.param_flags.gapless), 0); if (err != mpg123clr.mpg.ErrorCode.ok) { Console.WriteLine("Unable to set library options: " + mp.mpg123_strerror()); Console.WriteLine("Press any key to exit:"); while (Console.Read() == 0) ; return; } // Let the seek index auto-grow and contain an entry for every frame err = mp.mpg123_param(mpg123clr.mpg.parms.index_size, -1, 0); if (err != mpg123clr.mpg.ErrorCode.ok) { Console.WriteLine("Unable to set index size: " + mp.mpg123_strerror()); Console.WriteLine("Press any key to exit:"); while (Console.Read() == 0) ; return; } // Use float output formats only err = mp.mpg123_format_none(); if (err != mpg123clr.mpg.ErrorCode.ok) { Console.WriteLine("Unable to disable all output formats: " + mp.mpg123_strerror()); Console.WriteLine("Press any key to exit:"); while (Console.Read() == 0) ; return; } int[] rates = mp.mpg123_rates(); foreach (int rate in rates) { err = mp.mpg123_format(rate, mpg123clr.mpg.channelcount.both, mpg123clr.mpg.enc.enc_float_32); if (err != mpg123clr.mpg.ErrorCode.ok) { Console.WriteLine("Unable to set float output formats: " + mp.mpg123_strerror()); Console.WriteLine("Press any key to exit:"); while (Console.Read() == 0) ; return; } } err = mp.mpg123_open_feed(); if (err != mpg123clr.mpg.ErrorCode.ok) { Console.WriteLine("Unable to open feed: " + mp.mpg123_strerror()); Console.WriteLine("Press any key to exit:"); while (Console.Read() == 0) ; return; } string filename = args[0]; BinaryReader _in = new BinaryReader(File.Open(filename, FileMode.Open)); _out = new BinaryWriter(File.Open(args[1], FileMode.Create)); while ((ret = (int)(mp.mpg123_feedseek(95000, SeekOrigin.Begin, out inoffset))) == (int)mpg123clr.mpg.ErrorCode.need_more) // equiv to mpg123_feedseek { buf = _in.ReadBytes((int)INBUFF); if (buf.Length <= 0) break; inc += buf.Length; state = mp.mpg123_feed(buf, (uint)buf.Length); if (state == mpg123clr.mpg.ErrorCode.err) { Console.WriteLine("Feed error: " + mp.mpg123_strerror()); Console.WriteLine("Press any key to exit:"); while (Console.Read() == 0) ; return; } } _in.BaseStream.Seek(inoffset, SeekOrigin.Begin); while (true) { buf = _in.ReadBytes((int)INBUFF); if (buf.Length <= 0) break; inc += buf.Length; err = mp.mpg123_feed(buf, (uint)buf.Length); int num; uint bytes; IntPtr audio; while (err != mpg123clr.mpg.ErrorCode.err && err != mpg123clr.mpg.ErrorCode.need_more) { err = mp.mpg123_decode_frame(out num, out audio, out bytes); if (err == mpg123clr.mpg.ErrorCode.new_format) { mp.mpg123_getformat(out rate, out channels, out enc); initwavformat(); initwav(); } // (Surprisingly?) even though it does a Marshal.Copy it's as efficient as the pointer example below!!! if (bytes > 0) { byte[] outbuf = new byte[bytes]; Marshal.Copy(audio, outbuf, 0, (int)bytes); _out.Write(outbuf, 0, (int)bytes); } // Alternative example of direct usage of audio data via pointers - note it needs "unsafe" // and I'm fairly sure pointers should be "fixed" first // if (bytes > 0) // unsafe{ // byte* p = (byte*)audio; // for (int ii = 0; ii < bytes; ii++) // _out.Write(*p++); // } outc += bytes; } if (err == mpg123clr.mpg.ErrorCode.err) { Console.WriteLine("Error: " + mp.mpg123_strerror()); break; } } Console.WriteLine("Finished"); closewav(); _out.Close(); _in.Close(); mp.mpg123_delete(); mp.Dispose(); mpg123.mpg123_exit(); } } }
31.671687
162
0.493581
[ "MIT" ]
AbdullahTrees/pk2
external/test_abd/SDL2_mixer-2.0.4/external/mpg123-1.25.6/ports/MSVC++/2008clr/examples/feedseekclr/Program.cs
10,517
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System.Composition.Hosting; using Microsoft.Internal; namespace System.Composition.Hosting.Util { // Extremely performance-sensitive. // Always safe for reading, even under concurrent writes, // only one writer at a time allowed. internal class SmallSparseInitonlyArray { private class Element { public int Index; public object Value; } private const int ElementsCapacity = 128; private const int ElementIndexMask = 127; private const int LocalOffsetMax = 3; private Element[] _elements = null; private SmallSparseInitonlyArray _overflow; public void Add(int index, object value) { if (_elements == null) _elements = new Element[ElementsCapacity]; var newElement = new Element { Index = index, Value = value }; var elementIndex = index & ElementIndexMask; var e = _elements[elementIndex]; if (e == null) { _elements[elementIndex] = newElement; return; } // This overload of IsTrue doesn't call String.Format unless required. // Do, not switch to other version as it affects performance. Assumes.IsTrue(e.Index != index, "An item with the key '{0}' has already been added.", index); for (int offset = 1; offset <= LocalOffsetMax; ++offset) { var nextIndex = (index + offset) & ElementIndexMask; e = _elements[nextIndex]; if (e == null) { _elements[nextIndex] = newElement; return; } Assumes.IsTrue(e.Index != index, "An item with the key '{0}' has already been added.", index); } if (_overflow == null) _overflow = new SmallSparseInitonlyArray(); _overflow.Add(index, value); } public bool TryGetValue(int index, out object value) { if (_elements == null) { value = null; return false; } var elementIndex = index & ElementIndexMask; var e = _elements[elementIndex]; if (e != null && e.Index == index) { value = e.Value; return true; } for (int offset = 1; offset <= LocalOffsetMax; ++offset) { e = _elements[(index + offset) & ElementIndexMask]; if (e == null) { value = null; return false; } if (e.Index == index) { value = e.Value; return true; } } if (_overflow != null) return _overflow.TryGetValue(index, out value); value = null; return false; } } }
31.291262
110
0.515048
[ "MIT" ]
er0dr1guez/corefx
src/System.Composition.Hosting/src/System/Composition/Hosting/Util/SmallSparseInitonlyArray.cs
3,223
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Formats.Red.Records.Enums; namespace GameEstate.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class CBTTaskIfTargetHasEffectDef : IBehTreeTaskDefinition { [Ordinal(1)] [RED("effect")] public CEnum<EEffectType> Effect { get; set;} [Ordinal(2)] [RED("useCombatTarget")] public CBool UseCombatTarget { get; set;} public CBTTaskIfTargetHasEffectDef(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CBTTaskIfTargetHasEffectDef(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
34.37037
139
0.738147
[ "MIT" ]
smorey2/GameEstate
src/GameEstate.Formats.Red/Formats/Red/W3/RTTIConvert/CBTTaskIfTargetHasEffectDef.cs
928
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Diagnostics.CodeAnalysis; using System.Globalization; using System.Numerics; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Runtime.Versioning; namespace System { [Serializable] [CLSCompliant(false)] [StructLayout(LayoutKind.Sequential)] [TypeForwardedFrom("mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089")] public readonly struct UInt16 : IComparable, IConvertible, ISpanFormattable, IComparable<ushort>, IEquatable<ushort> #if FEATURE_GENERIC_MATH #pragma warning disable SA1001 , IBinaryInteger<ushort>, IMinMaxValue<ushort>, IUnsignedNumber<ushort> #pragma warning restore SA1001 #endif // FEATURE_GENERIC_MATH { private readonly ushort m_value; // Do not rename (binary serialization) public const ushort MaxValue = (ushort)0xFFFF; public const ushort MinValue = 0; // Compares this object to another object, returning an integer that // indicates the relationship. // Returns a value less than zero if this object // null is considered to be less than any instance. // If object is not of type UInt16, this method throws an ArgumentException. // public int CompareTo(object? value) { if (value == null) { return 1; } if (value is ushort) { return (int)m_value - (int)(((ushort)value).m_value); } throw new ArgumentException(SR.Arg_MustBeUInt16); } public int CompareTo(ushort value) { return (int)m_value - (int)value; } public override bool Equals([NotNullWhen(true)] object? obj) { if (!(obj is ushort)) { return false; } return m_value == ((ushort)obj).m_value; } [NonVersionable] public bool Equals(ushort obj) { return m_value == obj; } // Returns a HashCode for the UInt16 public override int GetHashCode() { return (int)m_value; } // Converts the current value to a String in base-10 with no extra padding. public override string ToString() { return Number.UInt32ToDecStr(m_value); } public string ToString(IFormatProvider? provider) { return Number.UInt32ToDecStr(m_value); } public string ToString(string? format) { return Number.FormatUInt32(m_value, format, null); } public string ToString(string? format, IFormatProvider? provider) { return Number.FormatUInt32(m_value, format, provider); } public bool TryFormat(Span<char> destination, out int charsWritten, ReadOnlySpan<char> format = default, IFormatProvider? provider = null) { return Number.TryFormatUInt32(m_value, format, provider, destination, out charsWritten); } public static ushort Parse(string s) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo); } public static ushort Parse(string s, NumberStyles style) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.CurrentInfo); } public static ushort Parse(string s, IFormatProvider? provider) { if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.GetInstance(provider)); } public static ushort Parse(string s, NumberStyles style, IFormatProvider? provider) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) ThrowHelper.ThrowArgumentNullException(ExceptionArgument.s); return Parse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider)); } public static ushort Parse(ReadOnlySpan<char> s, NumberStyles style = NumberStyles.Integer, IFormatProvider? provider = null) { NumberFormatInfo.ValidateParseStyleInteger(style); return Parse(s, style, NumberFormatInfo.GetInstance(provider)); } private static ushort Parse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info) { Number.ParsingStatus status = Number.TryParseUInt32(s, style, info, out uint i); if (status != Number.ParsingStatus.OK) { Number.ThrowOverflowOrFormatException(status, TypeCode.UInt16); } if (i > MaxValue) Number.ThrowOverflowException(TypeCode.UInt16); return (ushort)i; } public static bool TryParse([NotNullWhen(true)] string? s, out ushort result) { if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse(ReadOnlySpan<char> s, out ushort result) { return TryParse(s, NumberStyles.Integer, NumberFormatInfo.CurrentInfo, out result); } public static bool TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out ushort result) { NumberFormatInfo.ValidateParseStyleInteger(style); if (s == null) { result = 0; return false; } return TryParse((ReadOnlySpan<char>)s, style, NumberFormatInfo.GetInstance(provider), out result); } public static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out ushort result) { NumberFormatInfo.ValidateParseStyleInteger(style); return TryParse(s, style, NumberFormatInfo.GetInstance(provider), out result); } private static bool TryParse(ReadOnlySpan<char> s, NumberStyles style, NumberFormatInfo info, out ushort result) { if (Number.TryParseUInt32(s, style, info, out uint i) != Number.ParsingStatus.OK || i > MaxValue) { result = 0; return false; } result = (ushort)i; return true; } // // IConvertible implementation // public TypeCode GetTypeCode() { return TypeCode.UInt16; } bool IConvertible.ToBoolean(IFormatProvider? provider) { return Convert.ToBoolean(m_value); } char IConvertible.ToChar(IFormatProvider? provider) { return Convert.ToChar(m_value); } sbyte IConvertible.ToSByte(IFormatProvider? provider) { return Convert.ToSByte(m_value); } byte IConvertible.ToByte(IFormatProvider? provider) { return Convert.ToByte(m_value); } short IConvertible.ToInt16(IFormatProvider? provider) { return Convert.ToInt16(m_value); } ushort IConvertible.ToUInt16(IFormatProvider? provider) { return m_value; } int IConvertible.ToInt32(IFormatProvider? provider) { return Convert.ToInt32(m_value); } uint IConvertible.ToUInt32(IFormatProvider? provider) { return Convert.ToUInt32(m_value); } long IConvertible.ToInt64(IFormatProvider? provider) { return Convert.ToInt64(m_value); } ulong IConvertible.ToUInt64(IFormatProvider? provider) { return Convert.ToUInt64(m_value); } float IConvertible.ToSingle(IFormatProvider? provider) { return Convert.ToSingle(m_value); } double IConvertible.ToDouble(IFormatProvider? provider) { return Convert.ToDouble(m_value); } decimal IConvertible.ToDecimal(IFormatProvider? provider) { return Convert.ToDecimal(m_value); } DateTime IConvertible.ToDateTime(IFormatProvider? provider) { throw new InvalidCastException(SR.Format(SR.InvalidCast_FromTo, "UInt16", "DateTime")); } object IConvertible.ToType(Type type, IFormatProvider? provider) { return Convert.DefaultToType((IConvertible)this, type, provider); } #if FEATURE_GENERIC_MATH // // IAdditionOperators // [RequiresPreviewFeatures] static ushort IAdditionOperators<ushort, ushort, ushort>.operator +(ushort left, ushort right) => (ushort)(left + right); // [RequiresPreviewFeatures] // static checked ushort IAdditionOperators<ushort, ushort, ushort>.operator +(ushort left, ushort right) // => checked((ushort)(left + right)); // // IAdditiveIdentity // [RequiresPreviewFeatures] static ushort IAdditiveIdentity<ushort, ushort>.AdditiveIdentity => 0; // // IBinaryInteger // [RequiresPreviewFeatures] static ushort IBinaryInteger<ushort>.LeadingZeroCount(ushort value) => (ushort)(BitOperations.LeadingZeroCount(value) - 16); [RequiresPreviewFeatures] static ushort IBinaryInteger<ushort>.PopCount(ushort value) => (ushort)BitOperations.PopCount(value); [RequiresPreviewFeatures] static ushort IBinaryInteger<ushort>.RotateLeft(ushort value, int rotateAmount) => (ushort)((value << (rotateAmount & 15)) | (value >> ((16 - rotateAmount) & 15))); [RequiresPreviewFeatures] static ushort IBinaryInteger<ushort>.RotateRight(ushort value, int rotateAmount) => (ushort)((value >> (rotateAmount & 15)) | (value << ((16 - rotateAmount) & 15))); [RequiresPreviewFeatures] static ushort IBinaryInteger<ushort>.TrailingZeroCount(ushort value) => (ushort)(BitOperations.TrailingZeroCount(value << 16) - 16); // // IBinaryNumber // [RequiresPreviewFeatures] static bool IBinaryNumber<ushort>.IsPow2(ushort value) => BitOperations.IsPow2((uint)value); [RequiresPreviewFeatures] static ushort IBinaryNumber<ushort>.Log2(ushort value) => (ushort)BitOperations.Log2(value); // // IBitwiseOperators // [RequiresPreviewFeatures] static ushort IBitwiseOperators<ushort, ushort, ushort>.operator &(ushort left, ushort right) => (ushort)(left & right); [RequiresPreviewFeatures] static ushort IBitwiseOperators<ushort, ushort, ushort>.operator |(ushort left, ushort right) => (ushort)(left | right); [RequiresPreviewFeatures] static ushort IBitwiseOperators<ushort, ushort, ushort>.operator ^(ushort left, ushort right) => (ushort)(left ^ right); [RequiresPreviewFeatures] static ushort IBitwiseOperators<ushort, ushort, ushort>.operator ~(ushort value) => (ushort)(~value); // // IComparisonOperators // [RequiresPreviewFeatures] static bool IComparisonOperators<ushort, ushort>.operator <(ushort left, ushort right) => left < right; [RequiresPreviewFeatures] static bool IComparisonOperators<ushort, ushort>.operator <=(ushort left, ushort right) => left <= right; [RequiresPreviewFeatures] static bool IComparisonOperators<ushort, ushort>.operator >(ushort left, ushort right) => left > right; [RequiresPreviewFeatures] static bool IComparisonOperators<ushort, ushort>.operator >=(ushort left, ushort right) => left >= right; // // IDecrementOperators // [RequiresPreviewFeatures] static ushort IDecrementOperators<ushort>.operator --(ushort value) => --value; // [RequiresPreviewFeatures] // static checked ushort IDecrementOperators<ushort>.operator --(ushort value) // => checked(--value); // // IDivisionOperators // [RequiresPreviewFeatures] static ushort IDivisionOperators<ushort, ushort, ushort>.operator /(ushort left, ushort right) => (ushort)(left / right); // [RequiresPreviewFeatures] // static checked ushort IDivisionOperators<ushort, ushort, ushort>.operator /(ushort left, ushort right) // => checked((ushort)(left / right)); // // IEqualityOperators // [RequiresPreviewFeatures] static bool IEqualityOperators<ushort, ushort>.operator ==(ushort left, ushort right) => left == right; [RequiresPreviewFeatures] static bool IEqualityOperators<ushort, ushort>.operator !=(ushort left, ushort right) => left != right; // // IIncrementOperators // [RequiresPreviewFeatures] static ushort IIncrementOperators<ushort>.operator ++(ushort value) => ++value; // [RequiresPreviewFeatures] // static checked ushort IIncrementOperators<ushort>.operator ++(ushort value) // => checked(++value); // // IMinMaxValue // [RequiresPreviewFeatures] static ushort IMinMaxValue<ushort>.MinValue => MinValue; [RequiresPreviewFeatures] static ushort IMinMaxValue<ushort>.MaxValue => MaxValue; // // IModulusOperators // [RequiresPreviewFeatures] static ushort IModulusOperators<ushort, ushort, ushort>.operator %(ushort left, ushort right) => (ushort)(left % right); // [RequiresPreviewFeatures] // static checked ushort IModulusOperators<ushort, ushort, ushort>.operator %(ushort left, ushort right) // => checked((ushort)(left % right)); // // IMultiplicativeIdentity // [RequiresPreviewFeatures] static ushort IMultiplicativeIdentity<ushort, ushort>.MultiplicativeIdentity => 1; // // IMultiplyOperators // [RequiresPreviewFeatures] static ushort IMultiplyOperators<ushort, ushort, ushort>.operator *(ushort left, ushort right) => (ushort)(left * right); // [RequiresPreviewFeatures] // static checked ushort IMultiplyOperators<ushort, ushort, ushort>.operator *(ushort left, ushort right) // => checked((ushort)(left * right)); // // INumber // [RequiresPreviewFeatures] static ushort INumber<ushort>.One => 1; [RequiresPreviewFeatures] static ushort INumber<ushort>.Zero => 0; [RequiresPreviewFeatures] static ushort INumber<ushort>.Abs(ushort value) => value; [RequiresPreviewFeatures] static ushort INumber<ushort>.Clamp(ushort value, ushort min, ushort max) => Math.Clamp(value, min, max); [RequiresPreviewFeatures] [MethodImpl(MethodImplOptions.AggressiveInlining)] static ushort INumber<ushort>.Create<TOther>(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } else if (typeof(TOther) == typeof(char)) { return (char)(object)value; } else if (typeof(TOther) == typeof(decimal)) { return checked((ushort)(decimal)(object)value); } else if (typeof(TOther) == typeof(double)) { return checked((ushort)(double)(object)value); } else if (typeof(TOther) == typeof(short)) { return checked((ushort)(short)(object)value); } else if (typeof(TOther) == typeof(int)) { return checked((ushort)(int)(object)value); } else if (typeof(TOther) == typeof(long)) { return checked((ushort)(long)(object)value); } else if (typeof(TOther) == typeof(nint)) { return checked((ushort)(nint)(object)value); } else if (typeof(TOther) == typeof(sbyte)) { return checked((ushort)(sbyte)(object)value); } else if (typeof(TOther) == typeof(float)) { return checked((ushort)(float)(object)value); } else if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } else if (typeof(TOther) == typeof(uint)) { return checked((ushort)(uint)(object)value); } else if (typeof(TOther) == typeof(ulong)) { return checked((ushort)(ulong)(object)value); } else if (typeof(TOther) == typeof(nuint)) { return checked((ushort)(nuint)(object)value); } else { ThrowHelper.ThrowNotSupportedException(); return default; } } [RequiresPreviewFeatures] [MethodImpl(MethodImplOptions.AggressiveInlining)] static ushort INumber<ushort>.CreateSaturating<TOther>(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } else if (typeof(TOther) == typeof(char)) { return (char)(object)value; } else if (typeof(TOther) == typeof(decimal)) { var actualValue = (decimal)(object)value; return (actualValue > MaxValue) ? MaxValue : (actualValue < 0) ? MinValue : (ushort)actualValue; } else if (typeof(TOther) == typeof(double)) { var actualValue = (double)(object)value; return (actualValue > MaxValue) ? MaxValue : (actualValue < 0) ? MinValue : (ushort)actualValue; } else if (typeof(TOther) == typeof(short)) { var actualValue = (short)(object)value; return (actualValue < 0) ? MinValue : (ushort)actualValue; } else if (typeof(TOther) == typeof(int)) { var actualValue = (int)(object)value; return (actualValue > MaxValue) ? MaxValue : (actualValue < 0) ? MinValue : (ushort)actualValue; } else if (typeof(TOther) == typeof(long)) { var actualValue = (long)(object)value; return (actualValue > MaxValue) ? MaxValue : (actualValue < 0) ? MinValue : (ushort)actualValue; } else if (typeof(TOther) == typeof(nint)) { var actualValue = (nint)(object)value; return (actualValue > MaxValue) ? MaxValue : (actualValue < 0) ? MinValue : (ushort)actualValue; } else if (typeof(TOther) == typeof(sbyte)) { var actualValue = (sbyte)(object)value; return (actualValue < 0) ? MinValue : (ushort)actualValue; } else if (typeof(TOther) == typeof(float)) { var actualValue = (float)(object)value; return (actualValue > MaxValue) ? MaxValue : (actualValue < 0) ? MinValue : (ushort)actualValue; } else if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } else if (typeof(TOther) == typeof(uint)) { var actualValue = (uint)(object)value; return (actualValue > MaxValue) ? MaxValue : (ushort)actualValue; } else if (typeof(TOther) == typeof(ulong)) { var actualValue = (ulong)(object)value; return (actualValue > MaxValue) ? MaxValue : (ushort)actualValue; } else if (typeof(TOther) == typeof(nuint)) { var actualValue = (nuint)(object)value; return (actualValue > MaxValue) ? MaxValue : (ushort)actualValue; } else { ThrowHelper.ThrowNotSupportedException(); return default; } } [RequiresPreviewFeatures] [MethodImpl(MethodImplOptions.AggressiveInlining)] static ushort INumber<ushort>.CreateTruncating<TOther>(TOther value) { if (typeof(TOther) == typeof(byte)) { return (byte)(object)value; } else if (typeof(TOther) == typeof(char)) { return (char)(object)value; } else if (typeof(TOther) == typeof(decimal)) { return (ushort)(decimal)(object)value; } else if (typeof(TOther) == typeof(double)) { return (ushort)(double)(object)value; } else if (typeof(TOther) == typeof(short)) { return (ushort)(short)(object)value; } else if (typeof(TOther) == typeof(int)) { return (ushort)(int)(object)value; } else if (typeof(TOther) == typeof(long)) { return (ushort)(long)(object)value; } else if (typeof(TOther) == typeof(nint)) { return (ushort)(nint)(object)value; } else if (typeof(TOther) == typeof(sbyte)) { return (ushort)(sbyte)(object)value; } else if (typeof(TOther) == typeof(float)) { return (ushort)(float)(object)value; } else if (typeof(TOther) == typeof(ushort)) { return (ushort)(object)value; } else if (typeof(TOther) == typeof(uint)) { return (ushort)(uint)(object)value; } else if (typeof(TOther) == typeof(ulong)) { return (ushort)(ulong)(object)value; } else if (typeof(TOther) == typeof(nuint)) { return (ushort)(nuint)(object)value; } else { ThrowHelper.ThrowNotSupportedException(); return default; } } [RequiresPreviewFeatures] static (ushort Quotient, ushort Remainder) INumber<ushort>.DivRem(ushort left, ushort right) => Math.DivRem(left, right); [RequiresPreviewFeatures] static ushort INumber<ushort>.Max(ushort x, ushort y) => Math.Max(x, y); [RequiresPreviewFeatures] static ushort INumber<ushort>.Min(ushort x, ushort y) => Math.Min(x, y); [RequiresPreviewFeatures] static ushort INumber<ushort>.Parse(string s, NumberStyles style, IFormatProvider? provider) => Parse(s, style, provider); [RequiresPreviewFeatures] static ushort INumber<ushort>.Parse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider) => Parse(s, style, provider); [RequiresPreviewFeatures] static ushort INumber<ushort>.Sign(ushort value) => (ushort)((value == 0) ? 0 : 1); [RequiresPreviewFeatures] [MethodImpl(MethodImplOptions.AggressiveInlining)] static bool INumber<ushort>.TryCreate<TOther>(TOther value, out ushort result) { if (typeof(TOther) == typeof(byte)) { result = (byte)(object)value; return true; } else if (typeof(TOther) == typeof(char)) { result = (char)(object)value; return true; } else if (typeof(TOther) == typeof(decimal)) { var actualValue = (decimal)(object)value; if ((actualValue < 0) || (actualValue > MaxValue)) { result = default; return false; } result = (ushort)actualValue; return true; } else if (typeof(TOther) == typeof(double)) { var actualValue = (double)(object)value; if ((actualValue < 0) || (actualValue > MaxValue)) { result = default; return false; } result = (ushort)actualValue; return true; } else if (typeof(TOther) == typeof(short)) { var actualValue = (short)(object)value; if (actualValue < 0) { result = default; return false; } result = (ushort)actualValue; return true; } else if (typeof(TOther) == typeof(int)) { var actualValue = (int)(object)value; if ((actualValue < 0) || (actualValue > MaxValue)) { result = default; return false; } result = (ushort)actualValue; return true; } else if (typeof(TOther) == typeof(long)) { var actualValue = (long)(object)value; if ((actualValue < 0) || (actualValue > MaxValue)) { result = default; return false; } result = (ushort)actualValue; return true; } else if (typeof(TOther) == typeof(nint)) { var actualValue = (nint)(object)value; if ((actualValue < 0) || (actualValue > MaxValue)) { result = default; return false; } result = (ushort)actualValue; return true; } else if (typeof(TOther) == typeof(sbyte)) { var actualValue = (sbyte)(object)value; if (actualValue < 0) { result = default; return false; } result = (ushort)actualValue; return true; } else if (typeof(TOther) == typeof(float)) { var actualValue = (float)(object)value; if ((actualValue < 0) || (actualValue > MaxValue)) { result = default; return false; } result = (ushort)actualValue; return true; } else if (typeof(TOther) == typeof(ushort)) { result = (ushort)(object)value; return true; } else if (typeof(TOther) == typeof(uint)) { var actualValue = (uint)(object)value; if (actualValue > MaxValue) { result = default; return false; } result = (ushort)actualValue; return true; } else if (typeof(TOther) == typeof(ulong)) { var actualValue = (ulong)(object)value; if (actualValue > MaxValue) { result = default; return false; } result = (ushort)actualValue; return true; } else if (typeof(TOther) == typeof(nuint)) { var actualValue = (nuint)(object)value; if (actualValue > MaxValue) { result = default; return false; } result = (ushort)actualValue; return true; } else { ThrowHelper.ThrowNotSupportedException(); result = default; return false; } } [RequiresPreviewFeatures] static bool INumber<ushort>.TryParse([NotNullWhen(true)] string? s, NumberStyles style, IFormatProvider? provider, out ushort result) => TryParse(s, style, provider, out result); [RequiresPreviewFeatures] static bool INumber<ushort>.TryParse(ReadOnlySpan<char> s, NumberStyles style, IFormatProvider? provider, out ushort result) => TryParse(s, style, provider, out result); // // IParseable // [RequiresPreviewFeatures] static ushort IParseable<ushort>.Parse(string s, IFormatProvider? provider) => Parse(s, provider); [RequiresPreviewFeatures] static bool IParseable<ushort>.TryParse([NotNullWhen(true)] string? s, IFormatProvider? provider, out ushort result) => TryParse(s, NumberStyles.Integer, provider, out result); // // IShiftOperators // [RequiresPreviewFeatures] static ushort IShiftOperators<ushort, ushort>.operator <<(ushort value, int shiftAmount) => (ushort)(value << shiftAmount); [RequiresPreviewFeatures] static ushort IShiftOperators<ushort, ushort>.operator >>(ushort value, int shiftAmount) => (ushort)(value >> shiftAmount); // [RequiresPreviewFeatures] // static ushort IShiftOperators<ushort, ushort>.operator >>>(ushort value, int shiftAmount) // => (ushort)(value >> shiftAmount); // // ISpanParseable // [RequiresPreviewFeatures] static ushort ISpanParseable<ushort>.Parse(ReadOnlySpan<char> s, IFormatProvider? provider) => Parse(s, NumberStyles.Integer, provider); [RequiresPreviewFeatures] static bool ISpanParseable<ushort>.TryParse(ReadOnlySpan<char> s, IFormatProvider? provider, out ushort result) => TryParse(s, NumberStyles.Integer, provider, out result); // // ISubtractionOperators // [RequiresPreviewFeatures] static ushort ISubtractionOperators<ushort, ushort, ushort>.operator -(ushort left, ushort right) => (ushort)(left - right); // [RequiresPreviewFeatures] // static checked ushort ISubtractionOperators<ushort, ushort, ushort>.operator -(ushort left, ushort right) // => checked((ushort)(left - right)); // // IUnaryNegationOperators // [RequiresPreviewFeatures] static ushort IUnaryNegationOperators<ushort, ushort>.operator -(ushort value) => (ushort)(-value); // [RequiresPreviewFeatures] // static checked ushort IUnaryNegationOperators<ushort, ushort>.operator -(ushort value) // => checked((ushort)(-value)); // // IUnaryPlusOperators // [RequiresPreviewFeatures] static ushort IUnaryPlusOperators<ushort, ushort>.operator +(ushort value) => (ushort)(+value); // [RequiresPreviewFeatures] // static checked ushort IUnaryPlusOperators<ushort, ushort>.operator +(ushort value) // => checked((ushort)(+value)); #endif // FEATURE_GENERIC_MATH } }
33.562372
146
0.541159
[ "MIT" ]
74971030177/runtime
src/libraries/System.Private.CoreLib/src/System/UInt16.cs
32,824
C#
#region License // Copyright (c) 2010-2019, Mark Final // All rights reserved. // // Redistribution and use in source and binary forms, with or without // modification, are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, this // list of conditions and the following disclaimer. // // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // // * Neither the name of BuildAMation nor the names of its // contributors may be used to endorse or promote products derived from // this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" // AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE // OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion // License namespace GccCommon { /// <summary> /// Abstract class representing the common Gcc C++ compiler settings /// </summary> abstract class CommonCxxCompilerSettings : CommonCompilerSettings, C.ICxxOnlyCompilerSettings { protected override void ModifyDefaults() { base.ModifyDefaults(); (this as C.ICommonPreprocessorSettings).TargetLanguage = C.ETargetLanguage.Cxx; } [CommandLineProcessor.Enum(C.Cxx.EExceptionHandler.Disabled, "-fno-exceptions")] [CommandLineProcessor.Enum(C.Cxx.EExceptionHandler.Asynchronous, "-fexceptions")] [CommandLineProcessor.Enum(C.Cxx.EExceptionHandler.Synchronous, "-fexceptions")] [CommandLineProcessor.Enum(C.Cxx.EExceptionHandler.SyncWithCExternFunctions, "-fexceptions")] C.Cxx.EExceptionHandler? C.ICxxOnlyCompilerSettings.ExceptionHandler { get; set; } [CommandLineProcessor.Bool("-frtti", "-fno-rtti")] bool? C.ICxxOnlyCompilerSettings.EnableRunTimeTypeInfo { get; set; } [CommandLineProcessor.Enum(C.Cxx.ELanguageStandard.NotSet, "")] [CommandLineProcessor.Enum(C.Cxx.ELanguageStandard.Cxx98, "-std=c++98")] [CommandLineProcessor.Enum(C.Cxx.ELanguageStandard.GnuCxx98, "-std=gnu++98")] [CommandLineProcessor.Enum(C.Cxx.ELanguageStandard.Cxx03, "-std=c++03")] [CommandLineProcessor.Enum(C.Cxx.ELanguageStandard.GnuCxx03, "-std=gnu++03")] [CommandLineProcessor.Enum(C.Cxx.ELanguageStandard.Cxx11, "-std=c++11")] [CommandLineProcessor.Enum(C.Cxx.ELanguageStandard.GnuCxx11, "-std=gnu++11")] [CommandLineProcessor.Enum(C.Cxx.ELanguageStandard.Cxx14, "-std=c++14")] [CommandLineProcessor.Enum(C.Cxx.ELanguageStandard.GnuCxx14, "-std=gnu++14")] [CommandLineProcessor.Enum(C.Cxx.ELanguageStandard.Cxx17, "-std=c++17")] [CommandLineProcessor.Enum(C.Cxx.ELanguageStandard.GnuCxx17, "-std=gnu++17")] C.Cxx.ELanguageStandard? C.ICxxOnlyCompilerSettings.LanguageStandard { get; set; } [CommandLineProcessor.Enum(C.Cxx.EStandardLibrary.NotSet, "")] [CommandLineProcessor.Enum(C.Cxx.EStandardLibrary.libstdcxx, "")] [CommandLineProcessor.Enum(C.Cxx.EStandardLibrary.libcxx, "")] C.Cxx.EStandardLibrary? C.ICxxOnlyCompilerSettings.StandardLibrary { get; set; } } }
52.906667
101
0.728075
[ "BSD-3-Clause" ]
markfinal/BuildAMation
packages/GccCommon/bam/Scripts/CommonCxxCompilerSettings.cs
3,968
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Text.Json; using System.Threading; using System.Threading.Tasks; using Azure; using Azure.Core; using Azure.Core.Pipeline; using Azure.ResourceManager.Network.Models; namespace Azure.ResourceManager.Network { /// <summary> Creates or updates a peering in the specified virtual network. </summary> public partial class VirtualNetworkPeeringsCreateOrUpdateOperation : Operation<VirtualNetworkPeering>, IOperationSource<VirtualNetworkPeering> { private readonly ArmOperationHelpers<VirtualNetworkPeering> _operation; /// <summary> Initializes a new instance of VirtualNetworkPeeringsCreateOrUpdateOperation for mocking. </summary> protected VirtualNetworkPeeringsCreateOrUpdateOperation() { } internal VirtualNetworkPeeringsCreateOrUpdateOperation(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, Request request, Response response) { _operation = new ArmOperationHelpers<VirtualNetworkPeering>(this, clientDiagnostics, pipeline, request, response, OperationFinalStateVia.AzureAsyncOperation, "VirtualNetworkPeeringsCreateOrUpdateOperation"); } /// <inheritdoc /> public override string Id => _operation.Id; /// <inheritdoc /> public override VirtualNetworkPeering Value => _operation.Value; /// <inheritdoc /> public override bool HasCompleted => _operation.HasCompleted; /// <inheritdoc /> public override bool HasValue => _operation.HasValue; /// <inheritdoc /> public override Response GetRawResponse() => _operation.GetRawResponse(); /// <inheritdoc /> public override Response UpdateStatus(CancellationToken cancellationToken = default) => _operation.UpdateStatus(cancellationToken); /// <inheritdoc /> public override ValueTask<Response> UpdateStatusAsync(CancellationToken cancellationToken = default) => _operation.UpdateStatusAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<VirtualNetworkPeering>> WaitForCompletionAsync(CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(cancellationToken); /// <inheritdoc /> public override ValueTask<Response<VirtualNetworkPeering>> WaitForCompletionAsync(TimeSpan pollingInterval, CancellationToken cancellationToken = default) => _operation.WaitForCompletionAsync(pollingInterval, cancellationToken); VirtualNetworkPeering IOperationSource<VirtualNetworkPeering>.CreateResult(Response response, CancellationToken cancellationToken) { using var document = JsonDocument.Parse(response.ContentStream); return VirtualNetworkPeering.DeserializeVirtualNetworkPeering(document.RootElement); } async ValueTask<VirtualNetworkPeering> IOperationSource<VirtualNetworkPeering>.CreateResultAsync(Response response, CancellationToken cancellationToken) { using var document = await JsonDocument.ParseAsync(response.ContentStream, default, cancellationToken).ConfigureAwait(false); return VirtualNetworkPeering.DeserializeVirtualNetworkPeering(document.RootElement); } } }
46.438356
236
0.751917
[ "MIT" ]
AME-Redmond/azure-sdk-for-net
sdk/network/Azure.ResourceManager.Network/src/Generated/VirtualNetworkPeeringsCreateOrUpdateOperation.cs
3,390
C#
using Microsoft.UI.Xaml; using Microsoft.UI.Xaml.Controls; using Microsoft.UI.Xaml.Controls.Primitives; using Microsoft.UI.Xaml.Data; using Microsoft.UI.Xaml.Input; using Microsoft.UI.Xaml.Media; using Microsoft.UI.Xaml.Navigation; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using System.Threading.Tasks; using Windows.Foundation; using Windows.Foundation.Collections; // To learn more about WinUI, the WinUI project structure, // and more about our project templates, see: http://aka.ms/winui-project-info. namespace Loaf { public sealed partial class Windows11UpdateView { private bool _disposed = false; public Windows11UpdateView() { this.InitializeComponent(); Loaded += Windows11UpdateView_Loaded; Unloaded += Windows11UpdateView_Unloaded; this.KeyDown += Windows11UpdateView_KeyDown; this.PointerReleased += Windows11UpdateView_PointerReleased; } private void Windows11UpdateView_PointerReleased(object sender, PointerRoutedEventArgs e) { this.Focus(FocusState.Keyboard); } private void Windows11UpdateView_PointerPressed(object sender, PointerRoutedEventArgs e) { } private void Windows11UpdateView_KeyDown(object sender, KeyRoutedEventArgs e) { } private void Windows11UpdateView_Unloaded(object sender, RoutedEventArgs e) { _disposed = true; } private async void Windows11UpdateView_Loaded(object sender, RoutedEventArgs e) { int index = 0; while (_disposed == false) { UpdatingElement.Text = String.Format(ResourceExtensions.GetLocalized("UpdatingText"), (index++) % 100); await Task.Delay(TimeSpan.FromSeconds(10)); } } } }
29.402985
119
0.674619
[ "MIT" ]
Richasy/Loaf
Loaf/Windows11UpdateView.xaml.cs
1,972
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using Zenject; using Conekton.ARMultiplayer.SpatialAnchor.Domain; namespace Conekton.ARMultiplayer.SpatialAnchor.Infrastructure { public class SpatialAnchorRepository : ISpatialAnchorRepository { [Inject] private Presentation.SpatialAnchor.SpatialAnchorFactory _anchorFactory = null; private Dictionary<SpatialAnchorID, ISpatialAnchor> _database = new Dictionary<SpatialAnchorID, ISpatialAnchor>(); ISpatialAnchor ISpatialAnchorRepository.Create(SpatialAnchorID anchorID) => Create(anchorID); ISpatialAnchor ISpatialAnchorRepository.Find(SpatialAnchorID anchorID) => Find(anchorID); private ISpatialAnchor Create(SpatialAnchorID anchorID) { ISpatialAnchor anchor = _anchorFactory.Create(anchorID); AddAnchor(anchorID, anchor); return anchor; } private ISpatialAnchor Find(SpatialAnchorID anchorID) { if (_database.ContainsKey(anchorID)) { return _database[anchorID]; } return null; } private void AddAnchor(SpatialAnchorID anchorID, ISpatialAnchor anchor) { if (Find(anchorID) != null) { Debug.LogWarning($"{anchorID} is already exist in the database. The anchor won't be added this time."); return; } _database.Add(anchorID, anchor); } } }
30.403846
123
0.635674
[ "Apache-2.0" ]
miyatakoji/magic-leap-distance-checker
Assets/Conekton/Multiplayer/Scripts/UseCase/SpatialAnchor/Infrastructure/SpatialAnchorRepository.cs
1,583
C#
using System; using System.Collections.Generic; using System.Linq; using Microsoft.EntityFrameworkCore; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Stl.CommandR; using Stl.CommandR.Configuration; using Stl.Fusion; using Stl.Fusion.EntityFramework; using Stl.IO; using Stl.RegisterAttributes; using Stl.Testing; using Stl.Testing.Output; using Stl.Tests.CommandR.Services; using Xunit.Abstractions; using Xunit.DependencyInjection.Logging; namespace Stl.Tests.CommandR { public class CommandRTestBase : TestBase { protected bool UseDbContext { get; set; } protected Func<CommandHandler, Type, bool>? CommandHandlerFilter { get; set; } public CommandRTestBase(ITestOutputHelper @out) : base(@out) { } protected virtual IServiceProvider CreateServices() { var serviceCollection = new ServiceCollection(); ConfigureServices(serviceCollection); var services = serviceCollection.BuildServiceProvider(); if (UseDbContext) { var dbContextFactory = services.GetRequiredService<IDbContextFactory<TestDbContext>>(); using var dbContext = dbContextFactory.CreateDbContext(); dbContext.Database.EnsureDeleted(); dbContext.Database.EnsureCreated(); } return services; } private void ConfigureServices(ServiceCollection services) { services.AddLogging(logging => { var debugCategories = new List<string> { "Stl.CommandR", "Stl.Tests.CommandR", }; bool LogFilter(string category, LogLevel level) => debugCategories.Any(category.StartsWith) && level >= LogLevel.Debug; logging.ClearProviders(); logging.SetMinimumLevel(LogLevel.Debug); logging.AddDebug(); // XUnit logging requires weird setup b/c otherwise it filters out // everything below LogLevel.Information logging.AddProvider(new XunitTestOutputLoggerProvider( new TestOutputHelperAccessor(Out), LogFilter)); }); var commander = services.AddCommander(); if (CommandHandlerFilter != null) commander.AddHandlerFilter(CommandHandlerFilter); var fusion = services.AddFusion(); if (UseDbContext) { var testType = GetType(); var appTempDir = FilePath.GetApplicationTempDirectory("", true); var dbPath = appTempDir & FilePath.GetHashedName($"{testType.Name}_{testType.Namespace}.db"); services.AddPooledDbContextFactory<TestDbContext>(builder => { builder.UseSqlite($"Data Source={dbPath}", sqlite => { }); }, 256); services.AddDbContextServices<TestDbContext>(dbServices => { dbServices.AddOperations(); dbServices.AddEntityResolver<string, User>(); }); } services.UseRegisterAttributeScanner() .WithTypeFilter(GetType().Namespace!) .RegisterFrom(GetType().Assembly); } } }
37.595506
109
0.612074
[ "MIT" ]
MessiDaGod/Stl.Fusion
tests/Stl.Tests/CommandR/CommandRTestBase.cs
3,346
C#
using System; using System.Linq; using System.Runtime.CompilerServices; using System.ServiceModel; namespace Unity.Wcf.Tests.TestSupport { internal class TestHost<TContract, TService> where TService : class, TContract { private readonly ServiceHost _host; private ChannelFactory<TContract> _factory; public TestHost(IUnityContainer container = null, [CallerMemberName] string name = "") { BaseAddress = new Uri($"net.tcp://localhost/{TargetType.FullName}.{name}"); Container = container ?? new UnityContainer(); Container.RegisterType<TContract, TService>(); _host = new UnityServiceHost(Container, TargetType, BaseAddress); } public Uri BaseAddress { get; } public IUnityContainer Container { get; } public Type TargetType => typeof(TService); public TContract GetProxy() => _factory.CreateChannel(); public void Start() { _host.Open(); var se = _host.Description.Endpoints.First(); _factory = new ChannelFactory<TContract>(se.Binding, se.Address); } public void Stop() { _host.Close(); _factory = null; } } }
29.27907
94
0.619539
[ "Apache-2.0" ]
unitycontainer/wcf
tests/TestSupport/TestHost.cs
1,259
C#
#region BSD License /* Copyright (c) 2013-2018, Doxense SAS All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * Neither the name of Doxense nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ #endregion namespace FoundationDB.Layers.Experimental.Indexing.Tests { using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.IO; using System.Linq; using System.Text; using Doxense.Collections.Tuples; using FoundationDB.Client.Tests; using MathNet.Numerics.Distributions; using NUnit.Framework; [TestFixture] [Category("LongRunning")] public class CompressedBitmapsFacts : FdbTest { [Test] public void Test_EmptyBitmap() { // the empty bitmap shouldn't have any words var empty = CompressedBitmap.Empty; Assert.That(empty, Is.Not.Null.And.Count.EqualTo(0)); //REVIEW: what should the bounds be for an empty bitmap? Assert.That(empty.Bounds.Lowest, Is.EqualTo(0), "empty.Bounds.Lowest"); Assert.That(empty.Bounds.Highest, Is.EqualTo(-1), "empty.Bounds.Highest"); Assert.That(empty.Bounds.IsEmpty, Is.True, "empty.Bounds.IsEmpty"); // all bits should be unset Assert.That(empty.Test(0), Is.False); Assert.That(empty.Test(31), Is.False); Assert.That(empty.Test(32), Is.False); Assert.That(empty.Test(1234), Is.False); // binary representation should be 0 bytes var packed = empty.ToSlice(); Assert.That(packed, Is.EqualTo(Slice.Empty)); } private static void Verify(CompressedBitmapBuilder builder, SuperSlowUncompressedBitmap witness) { var bmpBuilder = builder.ToBitmap(); var bmpWitness = witness.ToBitmap(); Log($"> B: {bmpBuilder.Bounds,12} ({bmpBuilder.CountBits(),3}) {bmpBuilder.ToSlice().ToHexaString()}"); Log($"> W: {bmpWitness.Bounds,12} ({bmpWitness.CountBits(),3}) {bmpWitness.ToSlice().ToHexaString()}"); var rawBuilder = builder.ToBooleanArray(); var rawWitness = witness.ToBooleanArray(); Log("> B: " + bmpBuilder.Dump()); Log("> W: " + bmpWitness.Dump()); var a = SuperSlowUncompressedBitmap.Dump(rawBuilder).ToString().Split('\n'); var b = SuperSlowUncompressedBitmap.Dump(rawWitness).ToString().Split('\n'); Log(String.Join("\n", a.Zip(b, (x, y) => (x == y ? "= " : "##") + x + "\n " + y))); Assert.That(rawBuilder, Is.EqualTo(rawWitness), "Uncompressed bitmap does not match"); } private static bool SetBitAndVerify(CompressedBitmapBuilder builder, SuperSlowUncompressedBitmap witness, int offset) { Log(); Log($"Set({offset}):"); bool actual = builder.Set(offset); bool expected = witness.Set(offset); Assert.That(actual, Is.EqualTo(expected), "Set({0})", offset); Verify(builder, witness); return actual; } private static bool ClearBitAndVerify(CompressedBitmapBuilder builder, SuperSlowUncompressedBitmap witness, int offset) { Log(); Log($"Clear({offset}):"); bool actual = builder.Clear(offset); bool expected = witness.Clear(offset); Assert.That(actual, Is.EqualTo(expected), "Clear({0})", offset); Verify(builder, witness); return actual; } [Test] public void Test_CompressedBitmapBuilder_Set_Bits() { // start with an empty bitmap var builder = CompressedBitmap.Empty.ToBuilder(); Assert.That(builder, Is.Not.Null.And.Count.EqualTo(0)); var witness = new SuperSlowUncompressedBitmap(); Assert.That(SetBitAndVerify(builder, witness, 0), Is.True); Assert.That(SetBitAndVerify(builder, witness, 17), Is.True); Assert.That(SetBitAndVerify(builder, witness, 17), Is.False); Assert.That(SetBitAndVerify(builder, witness, 31), Is.True); Assert.That(SetBitAndVerify(builder, witness, 1234), Is.True); Assert.That(SetBitAndVerify(builder, witness, 777), Is.True); Assert.That(SetBitAndVerify(builder, witness, 62), Is.True); Assert.That(SetBitAndVerify(builder, witness, 774), Is.True); Assert.That(SetBitAndVerify(builder, witness, 124), Is.True); Assert.That(SetBitAndVerify(builder, witness, 93), Is.True); } [Test] public void Test_CompressedBitmapBuilder_Clear_Bits() { var builder = CompressedBitmap.Empty.ToBuilder(); Assert.That(builder, Is.Not.Null.And.Count.EqualTo(0)); var witness = new SuperSlowUncompressedBitmap(); // clearing anything in the empty bitmap is a no-op Assert.That(ClearBitAndVerify(builder, witness, 0), Is.False); Assert.That(ClearBitAndVerify(builder, witness, 42), Is.False); Assert.That(ClearBitAndVerify(builder, witness, int.MaxValue), Is.False); Assert.That(SetBitAndVerify(builder, witness, 42), Is.True); Assert.That(ClearBitAndVerify(builder, witness, 42), Is.True, "Clear just after set"); Assert.That(ClearBitAndVerify(builder, witness, 42), Is.False, "Clear just after clear"); } [Test] public void Test_CompressedBitmapBuilder_Linear_Sets() { // for each bit, from 0 to N-1, set it with proability P // => this test linear insertion, that always need to patch or append at the end of the bitmap var builder = CompressedBitmap.Empty.ToBuilder(); var witness = new SuperSlowUncompressedBitmap(); int N = 5 * 1000; int P = 100; var rnd = new Random(12345678); for (int i = 0; i < N; i++) { if (rnd.Next(P) == 42) { SetBitAndVerify(builder, witness, rnd.Next(N)); } } } [Test] public void Test_CompressedBitmapBuilder_Random_Sets() { // randomly set K bits in a set of N possible bits (with possible overlap) // => this test random insertions that need to modifiy the inside of a bitmap var builder = CompressedBitmap.Empty.ToBuilder(); var witness = new SuperSlowUncompressedBitmap(); int N = 5 * 1000; int K = 100; var rnd = new Random(12345678); for (int i = 0; i < K; i++) { SetBitAndVerify(builder, witness, rnd.Next(N)); } } [Test] public void Test_CompressedBitmapBuilder_Random_Sets_And_Clears() { // randomly alternate between setting and clearing random bits int K = 20; int S = 100; int C = 100; int N = 5 * 1000; var bmp = CompressedBitmap.Empty; var witness = new SuperSlowUncompressedBitmap(); var rnd = new Random(12345678); for (int k = 0; k < K; k++) { Log("### Generation " + k); // convert to builder var builder = bmp.ToBuilder(); Verify(builder, witness); // set S bits for (int i = 0; i < S; i++) { int p = rnd.Next(N); builder.Set(p); witness.Set(p); //SetBitAndVerify(builder, witness, p); } // clear C bits for (int i = 0; i < C; i++) { int p = rnd.Next(N); //ClearBitAndVerify(builder, witness, p); builder.Clear(p); witness.Clear(p); } // pack back to bitmap bmp = builder.ToBitmap(); Log(); Log($"> Result of gen #{k}: {bmp.Dump()}"); Log($"> {bmp.ToSlice().ToHexaString()}"); Log(); } } [Test] public void TestFoo() { var rnd = new Random(); void Compress(Slice input) { Log($"IN [{input.Count}] => {input}"); var writer = new CompressedBitmapWriter(); int r = WordAlignHybridEncoder.CompressTo(input, writer); var compressed = writer.GetBuffer(); Log($"OUT [{compressed.Count}] => {compressed} [r={r}]"); var sb = new StringBuilder(); Log(WordAlignHybridEncoder.DumpCompressed(compressed).ToString()); Log(); } Compress(Slice.FromString("This is a test of the emergency broadcast system")); // all zeroes (multiple of 31 bits) Compress(Slice.Repeat(0, 62)); // all zeroes (with padding) Compress(Slice.Repeat(0, 42)); // all ones (multiple of 31 bits) Compress(Slice.Repeat(255, 62)); // all ones (with padding) Compress(Slice.Repeat(255, 42)); // random stuff (multiple of 31 bits) Compress(Slice.Random(rnd, 42)); // random stuff (with padding) Compress(Slice.Random(rnd, 42)); // mostly zeroes void SetBit(byte[] b, int p) { b[p >> 3] |= (byte) (1 << (p & 7)); } byte[] MostlyZeroes(int count) { var buf = new byte[1024]; for (int i = 0; i < count; i++) { SetBit(buf, rnd.Next(buf.Length * 8)); } Log("Mostly zeroes: " + count); return buf; } Compress(MostlyZeroes(1).AsSlice()); Compress(MostlyZeroes(10).AsSlice()); Compress(MostlyZeroes(42).AsSlice()); Compress(MostlyZeroes(100).AsSlice()); // mostly ones void ClearBit(byte[] b, int p) { b[p >> 3] &= (byte) ~(1 << (p & 7)); } byte[] MostlyOnes(int count) { var buf = new byte[1024]; for (int i = 0; i < buf.Length; i++) buf[i] = 0xFF; for (int i = 0; i < 10; i++) { ClearBit(buf, rnd.Next(buf.Length * 8)); } Log("Mostly ones: " + count); return buf; } Compress(MostlyOnes(1).AsSlice()); Compress(MostlyOnes(10).AsSlice()); Compress(MostlyOnes(42).AsSlice()); Compress(MostlyOnes(100).AsSlice()); // progressive bool TestBit(byte[] b, int p) => (b[p >> 3] & (1 << (p & 7))) != 0; const int VALUES = 8192; var buffer = new byte[VALUES / 8]; var output = new CompressedBitmapWriter(); WordAlignHybridEncoder.CompressTo(buffer.AsSlice(), output); Log($"{0}\t{output.Length}\t1024"); for (int i = 0; i < VALUES / 8; i++) { int p; do { p = rnd.Next(VALUES); } while (TestBit(buffer, p)); SetBit(buffer, p); output.Reset(); WordAlignHybridEncoder.CompressTo(buffer.AsSlice(), output); Log($"{1.0d * (i + 1) / VALUES}\t{output.Length}\t1024"); } } private class Character { public int Id { get; set; } public string Name { get; set; } // will mostly be used for sorting public string Gender { get; set; } // poor man's enum with 49%/49%/1% distribution public string Job { get; set; } // regular enum with random distribution public DateTime? Born { get; set; } // accurate to the day, usually used in range queries public bool Dead { get; set; } // zomg, spoilers ahead! probably used as an exclusion flag (like IsDeleted) } public class MemoryIndex<TKey> { public readonly Dictionary<TKey, CompressedBitmap> Values; public readonly Dictionary<TKey, int> Statistics; public MemoryIndex(IEqualityComparer<TKey> comparer = null) { comparer = comparer ?? EqualityComparer<TKey>.Default; this.Values = new Dictionary<TKey, CompressedBitmap>(comparer); this.Statistics = new Dictionary<TKey, int>(comparer); } public CompressedBitmap Lookup(TKey value) { return this.Values.TryGetValue(value, out CompressedBitmap bmp) ? bmp : null; } public int Count(TKey value) { return this.Statistics.TryGetValue(value, out int cnt) ? cnt : 0; } public double Frequency(TKey value) { return (double)Count(value) / this.Statistics.Values.Sum(); } } private static Action<TDoc> MakeInserter<TDoc, TKey>(MemoryIndex<TKey> index, Func<TDoc, int> idFunc, Func<TDoc, TKey> keyFunc) { return (TDoc doc) => { int docId = idFunc(doc); TKey indexedValue = keyFunc(doc); int count; if (!index.Values.TryGetValue(indexedValue, out CompressedBitmap bmp)) { bmp = CompressedBitmap.Empty; count = 0; } else { count = index.Statistics[indexedValue]; } var builder = bmp.ToBuilder(); builder.Set(docId); index.Values[indexedValue] = builder.ToBitmap(); index.Statistics[indexedValue] = count + 1; }; } private static string MakeHeatMap(int[] map) { int max = map.Max(); const string SCALE = "`.:;+=xX$&#"; double r = (double)(SCALE.Length - 1) / max; var chars = new char[map.Length]; for (int i = 0; i < map.Length; i++) { if (map[i] == 0) chars[i] = '\xA0'; else chars[i] = SCALE[(int)Math.Round(r * map[i], MidpointRounding.AwayFromZero)]; } return new string(chars); } private static void DumpIndex<TKey, TVal>(string label, MemoryIndex<TKey> index, Func<TKey, int, TVal> orderBy, IComparer<TVal> comparer = null, bool heatMaps = false) { comparer = comparer ?? Comparer<TVal>.Default; int total = index.Statistics.Values.Sum(); long totalLegacy = 0; int[] map = new int[100]; double r = (double)(map.Length - 1) / total; Log($"__{label}__"); Log("| Indexed Value | Count | Total % | Words | Lit% | 1-Bits | Word% | Bitmap | ratio % | Legacy | ratio % |" + (heatMaps ? " HeatMap |" : "")); Log("|:------------------------|-------:|--------:|------:|-------:|-------:|-------:|---------:|--------:|----------:|--------:|" + (heatMaps ? ":-----------------------------------------------------------------------|" : "")); foreach (var kv in index.Values.OrderBy((kv) => orderBy(kv.Key, index.Count(kv.Key)), comparer)) { var t = STuple.Create(kv.Key); var tk = TuPack.Pack(t); kv.Value.GetStatistics(out int bits, out int words, out int literals, out int _, out double ratio); long legacyIndexSize = 0; // size estimate of a regular FDB index (..., "Value", GUID) = "" Array.Clear(map, 0, map.Length); foreach(var p in kv.Value.GetView()) { map[(int)(r * p)]++; legacyIndexSize += 3 + tk.Count + 17; } totalLegacy += legacyIndexSize; int bytes = kv.Value.ToSlice().Count; Log(string.Format( CultureInfo.InvariantCulture, "| {0,-24}| {1,6:N0} | {2,6:N2}% | {3,5:N0} | {4,5:N1}% | {5,6:N0} | {6,6:N2} | {7,8:N0} | {8,6:N2}% | {9,9:N0} | {10,6:N2}% |" + (heatMaps ? " `{11}` |" : ""), /*0*/ t, /*1*/ index.Count(kv.Key), /*2*/ 100.0 * index.Frequency(kv.Key), /*3*/ words, /*4*/ (100.0 * literals) / words, /*5*/ bits, /*6*/ 1.0 * bits / words, /*7*/ bytes, /*8*/ 100.0 * ratio, /*9*/ legacyIndexSize, /*A*/ (100.0 * bytes) / legacyIndexSize, /*B*/ heatMaps ? MakeHeatMap(map) : "" )); } Log(string.Format( CultureInfo.InvariantCulture, "> {0:N0} distinct value(s), {1:N0} document(s), {2:N0} bitmap bytes, {3:N0} legacy bytes", index.Values.Count, total, index.Values.Values.Sum(x => x.ToSlice().Count), totalLegacy )); } private static List<Character> DumpIndexQueryResult(Dictionary<int, Character> characters, CompressedBitmap bitmap) { var results = new List<Character>(); foreach (var docId in bitmap.GetView()) { Assert.That(characters.TryGetValue(docId, out Character character), Is.True); results.Add(character); Log($"- {docId}: {character.Name} {(character.Gender == "Male" ? "\u2642" : character.Gender == "Female" ? "\u2640" : character.Gender)}{(character.Dead ? " (\u271D)" : "")}"); } return results; } [Test] public void Test_Merging_Multiple_Bitmaps() { var dataSet = new List<Character>() { new Character { Id = 1, Name = "Spike Spiegel", Gender = "Male", Job="Bounty_Hunter", Born = new DateTime(2044, 6, 26), Dead = true /* bang! */ }, new Character { Id = 2, Name = "Jet Black", Gender = "Male", Job="Bounty_Hunter", Born = new DateTime(2035, 12, 13) }, new Character { Id = 3, Name = "Faye Valentine", Gender = "Female", Job="Bounty_Hunter", Born = new DateTime(1994, 8, 14) }, new Character { Id = 4, Name = "Edward Wong Hau Pepelu Tivruski IV", Gender = "Female", Job="Hacker", Born = new DateTime(2058, 1, 1) }, new Character { Id = 5, Name = "Ein", Gender = "Male", Job="Dog" }, new Character { Id = 6, Name = "Vicious", Gender = "Male", Job = "Vilain", Dead = true }, new Character { Id = 7, Name = "Julia", Gender = "Female", Job = "Damsel_In_Distress", Dead = true /* It's all a dream */ }, new Character { Id = 8, Name = "Victoria Tepsichore", Gender = "Female", Job = "Space_Trucker" }, new Character { Id = 9, Name = "Punch", Gender = "Male", Job = "TV_Host" }, new Character { Id = 10, Name = "Judy", Gender = "Female", Job = "TV_Host" }, }; // poor man's in memory database var database = new Dictionary<int, Character>(); var indexByGender = new MemoryIndex<string>(StringComparer.OrdinalIgnoreCase); var indexByJob = new MemoryIndex<string>(StringComparer.OrdinalIgnoreCase); var indexOfTheDead = new MemoryIndex<bool>(); // simulate building the indexes one document at a time var indexers = new[] { MakeInserter<Character, string>(indexByGender, (doc) => doc.Id, (doc) => doc.Gender), MakeInserter<Character, string>(indexByJob, (doc) => doc.Id, (doc) => doc.Job), MakeInserter<Character, bool>(indexOfTheDead, (doc) => doc.Id, (doc) => doc.Dead), }; Log("Inserting into database..."); foreach (var character in dataSet) { database[character.Id] = character; foreach (var indexer in indexers) { indexer(character); } } // dump the indexes Log(); DumpIndex("Genders", indexByGender, (s, _) => s); Log(); DumpIndex("Jobs", indexByJob, (s, _) => s); Log(); DumpIndex("DeadOrAlive", indexOfTheDead, (s, _) => s); // Où sont les femmes ? Log(); Log("indexByGender.Lookup('Female')"); CompressedBitmap females = indexByGender.Lookup("Female"); Assert.That(females, Is.Not.Null); Log($"=> {females.Dump()}"); DumpIndexQueryResult(database, females); // R.I.P Log(); Log("indexOfTheDead.Lookup(dead: true)"); CompressedBitmap deadPeople = indexOfTheDead.Lookup(true); Assert.That(deadPeople, Is.Not.Null); Log($"=> {deadPeople.Dump()}"); DumpIndexQueryResult(database, deadPeople); // combination of both Log(); Log("indexByGender.Lookup('Female') AND indexOfTheDead.Lookup(dead: true)"); var julia = WordAlignHybridEncoder.And(females, deadPeople); Log($"=> {julia.Dump()}"); DumpIndexQueryResult(database, julia); // the crew Log(); Log("indexByJob.Lookup('Bounty_Hunter' OR 'Hacker' OR 'Dog')"); var bmps = new[] { "Bounty_Hunter", "Hacker", "Dog" }.Select(job => indexByJob.Lookup(job)).ToList(); CompressedBitmap crew = null; foreach (var bmp in bmps) { if (crew == null) crew = bmp; else crew = WordAlignHybridEncoder.Or(crew, bmp); } crew = crew ?? CompressedBitmap.Empty; Log($"=> {crew.Dump()}"); DumpIndexQueryResult(database, crew); } [Test] public void Test_Logical_Binary_Operations() { var a = SuperSlowUncompressedBitmap.FromBitString("0101").ToBitmap(); var b = SuperSlowUncompressedBitmap.FromBitString("0011").ToBitmap(); var and = a.And(b); Assert.That(and, Is.Not.Null); Assert.That(new SuperSlowUncompressedBitmap(and).ToBitString(), Is.EqualTo("0001000000000000000000000000000"), "a AND b"); var or = a.Or(b); Assert.That(or, Is.Not.Null); Assert.That(new SuperSlowUncompressedBitmap(or).ToBitString(), Is.EqualTo("0111000000000000000000000000000"), "a OR b"); var xor = a.Xor(b); Assert.That(xor, Is.Not.Null); Assert.That(new SuperSlowUncompressedBitmap(xor).ToBitString(), Is.EqualTo("0110000000000000000000000000000"), "a XOR b"); var andNot = a.AndNot(b); Assert.That(andNot, Is.Not.Null); Assert.That(new SuperSlowUncompressedBitmap(andNot).ToBitString(), Is.EqualTo("0100000000000000000000000000000"), "a AND NOT b"); var orNot = a.OrNot(b); Assert.That(orNot, Is.Not.Null); Assert.That(new SuperSlowUncompressedBitmap(orNot).ToBitString(), Is.EqualTo("1101111111111111111111111111111"), "a OR NOT b"); var xorNot = a.XorNot(b); Assert.That(xorNot, Is.Not.Null); Assert.That(new SuperSlowUncompressedBitmap(xorNot).ToBitString(), Is.EqualTo("1001111111111111111111111111111")); } #region Coin Toss... public sealed class CoinToss { public const int HEAD = 1; // 49.5% public const int TAIL = 2; // 49.5% public const int EDGE = 0; // 1.0% /// <summary>Toss unique id (random guid)</summary> public Guid Id { get; set; } /// <summary>False if the toss was discarded as invalid</summary> public bool Valid { get; set; } // 99.9% true, 0.1% false /// <summary>True for head, False for tails, null for edge</summary> public int Result { get; set; } /// <summary>Number of completed 360° flips</summary> public int Flips { get; set; } /// <summary>Coin elevation (in cm)</summary> public double Elevation { get; set; } /// <summary>true for daytime, false for nighttime</summary> public bool Daytime { get; set; } /// <summary>Name of location where the toss was performed</summary> public string Location { get; set; } } [Test] public void Test_Randomized_Data() { #region Data Generators... Random rnd = null; // initialized later var dfFlips = new Cauchy(10, 4, rnd); Func<int> makeFlips = () => { int x = 0; while (x <= 0 || x >= 30) { x = (int)Math.Floor(dfFlips.Sample()); } return x; }; var dfElev = new Cauchy(10, 1, rnd); Func<double> makeElevation = () => { double x = 0; while (x <= 0.0 || x >= 30) { x = dfElev.Sample(); } return x; }; bool flipFlop = false; Func<bool> makeFlipFlop = () => { if (rnd.NextDouble() < 0.01) flipFlop = !flipFlop; return flipFlop; }; var cities = new[] { "Paris", "Marseilles", "Lyon", "Toulouse", "Nice", "Nantes", "Strasbourg", "Montpellier", "Bordeaux", "Lille", "Rennes", "Reims", "Le Havre", "Saint-Étienne", "Toulon", "Grenoble", "Dijon", "Angers", "Saint-Denis", "Villeurbanne", "Nîmes", "Le Mans", "Clermont-Ferrand", "Aix-en-Provence", "Brest" }; var dfLoc = new Cauchy(0, 1.25, rnd); Func<string> makeLocation = () => { int x = cities.Length; while (x >= cities.Length) { x = (int)Math.Floor(Math.Abs(dfLoc.Sample())); } return cities[x]; }; Func<int> makeHeadsOrTails = () => rnd.NextDouble() < 0.01 ? CoinToss.EDGE : rnd.NextDouble() <= 0.5 ? CoinToss.HEAD : CoinToss.TAIL; // biased! Func<bool> makeValid = () => rnd.Next(1000) != 666; #endregion //foreach (var N in new[] { 1000, 2000, 5000, 10 * 1000, 20 * 1000, 50 * 1000, 100 * 1000 }) const int N = 10 * 1000; { Log("================================================================================================================================================================================================================================="); Log($"N = {N:N0}"); Log("================================================================================================================================================================================================================================="); rnd = new Random(123456); var dataSet = Enumerable .Range(0, N) .Select(i => new KeyValuePair<int, CoinToss>(i, new CoinToss { Id = Guid.NewGuid(), Valid = makeValid(), Result = makeHeadsOrTails(), Flips = makeFlips(), Elevation = makeElevation(), Location = makeLocation(), Daytime = makeFlipFlop(), })) .ToList(); var indexLoc = new MemoryIndex<string>(StringComparer.Ordinal); var indexValid = new MemoryIndex<bool>(); var indexResult = new MemoryIndex<int>(); var indexFlips = new MemoryIndex<int>(); var indexElevation = new MemoryIndex<double>(); // quantized! var indexFlipFlop = new MemoryIndex<bool>(); var inserters = new [] { MakeInserter<KeyValuePair<int, CoinToss>, int>(indexResult, (kv) => kv.Key, (kv) => kv.Value.Result), MakeInserter<KeyValuePair<int, CoinToss>, bool>(indexValid, (kv) => kv.Key, (kv) => kv.Value.Valid), MakeInserter<KeyValuePair<int, CoinToss>, bool>(indexFlipFlop, (kv) => kv.Key, (kv) => kv.Value.Daytime), MakeInserter<KeyValuePair<int, CoinToss>, int>(indexFlips, (kv) => kv.Key, (kv) => kv.Value.Flips), MakeInserter<KeyValuePair<int, CoinToss>, double>(indexElevation, (kv) => kv.Key, (kv) => Math.Round(kv.Value.Elevation, 1, MidpointRounding.AwayFromZero)), MakeInserter<KeyValuePair<int, CoinToss>, string>(indexLoc, (kv) => kv.Key, (kv) => kv.Value.Location), }; var database = new Dictionary<int, CoinToss>(); //Log("Inserting data: ..."); foreach (var data in dataSet) { //if (database.Count % 1000 == 0) Log("\rInserting data: {0} / {1}", database.Count, N); database[data.Key] = data.Value; foreach (var inserter in inserters) inserter(data); } //Log("\rInserting data: {0} / {1}", database.Count, N); Log(); DumpIndex("Result", indexResult, (s, _) => s, heatMaps: true); Log(); DumpIndex("Valid", indexValid, (s, _) => s, heatMaps: true); Log(); DumpIndex("FlipFlops", indexFlipFlop, (s, _) => s, heatMaps: true); Log(); DumpIndex("Flips", indexFlips, (s, _) => s, heatMaps: true); Log(); DumpIndex("Location", indexLoc, (_, n) => -n, heatMaps: true); Log(); DumpIndex("Elevation", indexElevation, (s, _) => s, heatMaps: true); //Log(indexValid.Values[true].Dump()); //Log(indexValid.Values[true].ToSlice().ToHexaString()); Log(); Log(); } } #endregion [Test] public void Test_BigBadIndexOfTheDead() { // simulate a dataset where 50,000 users create a stream of 10,000,000 events, with a non uniform distribution, ie: few users making the bulk, and a long tail of mostly inactive users const int N = 10 * 1000 * 1000; const int K = 50 * 1000; var rnd = new Random(123456); #region create a non uniform random distribution for the users // step1: create a semi random distribution for the values Log($"Creating Probability Distribution Function for {K:N0} users..."); var pk = new double[K]; // step1: each gets a random score for (int i = 0; i < pk.Length; i++) { pk[i] = Math.Pow(rnd.NextDouble(), 10); } // then sort + reverse Array.Sort(pk); Array.Reverse(pk); // step2: spread double sum = 0; for(int i = 0; i < pk.Length;i++) { var s = pk[i]; pk[i] = sum; sum += s; } // step3: normalize double r = (N - 1) / sum; for (int i = 0; i < pk.Length; i++) { pk[i] = Math.Floor(pk[i] * r); } sum = N; // step4: fudge the tail r = pk[pk.Length - 1]; double delta = 1; for (int i = pk.Length - 2; i >= 0; i--) { if (pk[i] < r) break; r -= delta; delta *= 1.0001; pk[i] = r; } //for (int i = 0; i < pk.Length; i += 500) //{ // Log(pk[i].ToString("R", CultureInfo.InvariantCulture)); //} int p25 = Array.BinarySearch(pk, 0.25 * sum); p25 = p25 < 0 ? ~p25 : p25; int p50 = Array.BinarySearch(pk, 0.50 * sum); p50 = p50 < 0 ? ~p50 : p50; int p75 = Array.BinarySearch(pk, 0.75 * sum); p75 = p75 < 0 ? ~p75 : p75; int p95 = Array.BinarySearch(pk, 0.95 * sum); p95 = p95 < 0 ? ~p95 : p95; Log($"> PDF: P25={100.0 * p25 / K:G2} %, P50={100.0 * p50 / K:G2} %, P75={100.0 * p75 / K:G2} %, P95={100.0 * p95 / K:G2} %"); #endregion #region Create the random event dataset... // a user will be selected randomly, and will be able to produce a random number of consecutive events, until we reach the desired amount of events Log($"Creating dataset for {N:N0} documents..."); var dataSet = new int[N]; //int j = 0; //for (int i = 0; i < N; i++) //{ // if (pk[j + 1] <= i) j++; // dataSet[i] = j; //} //// scramble dataset //for (int i = 0; i < N;i++) //{ // var p = rnd.Next(i); // var tmp = dataSet[i]; // dataSet[i] = dataSet[p]; // dataSet[p] = tmp; //} int user = 0; int j = 0; while (j < N) { if (rnd.NextDouble() * sum * 1.005 >= pk[user]) { int n = 1 + (int)(Math.Pow(rnd.NextDouble(), 2) * 10); while (n-- > 0 && j < N) { dataSet[j++] = user; } } ++user; if (user == K) user = 0; } Log("Computing control statistics..."); // compute the control value for the counts per value var controlStats = dataSet .GroupBy(x => x).Select(g => new { Value = g.Key, Count = g.Count() }) .OrderByDescending(x => x.Count) .ToList(); Log($"> Found {controlStats.Count:N0} unique values"); #endregion // create pseudo-index Log($"Indexing {N:N0} documents..."); var sw = Stopwatch.StartNew(); var index = new Dictionary<int, CompressedBitmapBuilder>(K); for (int id = 0; id < dataSet.Length; id++) { int value = dataSet[id]; CompressedBitmapBuilder builder; if (!index.TryGetValue(value, out builder)) { builder = new CompressedBitmapBuilder(CompressedBitmap.Empty); index[value] = builder; } builder.Set(id); } sw.Stop(); Log($"> Found {index.Count:N0} unique values in {sw.Elapsed.TotalSeconds:N1} sec"); // verify the counts Log("Verifying index results..."); var log = new StringWriter(CultureInfo.InvariantCulture); long totalBitmapSize = 0; j = 0; foreach (var kv in controlStats) { Assert.That(index.TryGetValue(kv.Value, out CompressedBitmapBuilder builder), Is.True, "{0} is missing from index", kv.Value); var bmp = builder.ToBitmap(); bmp.GetStatistics(out int bits, out int words, out int a, out int b, out _); Assert.That(bits, Is.EqualTo(kv.Count), "{0} has invalid count", kv.Value); int sz = bmp.ToSlice().Count; log.WriteLine("{0,8} : {1,5} bits, {2} words ({3} lit. / {4} fil.), {5:N0} bytes, {6:N3} bytes/doc, {7:N2}% compression", kv.Value, bits, words, a, b, sz, 1.0 * sz / bits, 100.0 * (4 + 17 + sz) / (17 + (4 + 17) * bits)); totalBitmapSize += sz; //if (j % 500 == 0) Log((100.0 * b / words)); //if (j % 500 == 0) Log(bmp.Dump()); j++; } Assert.That(index.Count, Is.EqualTo(controlStats.Count), "Some values have not been indexed properly"); Log("> success!"); Log($"Total index size for {N:N0} documents and {K:N0} values is {totalBitmapSize:N0} bytes"); Log(); Log("Dumping results:"); Log(log.ToString()); } } }
33.194444
237
0.619601
[ "BSD-3-Clause" ]
Doxense/foundationdb-dotnet-client
FoundationDB.Layers.Experimental.Tests/Indexing/CompressedBitmapsFacts.cs
31,076
C#
using System.Windows; using System.Windows.Controls; using System.Windows.Input; namespace PixiEditor.Views.Dialogs { public partial class DialogTitleBar : UserControl { public static readonly DependencyProperty TitleTextProperty = DependencyProperty.Register(nameof(TitleText), typeof(string), typeof(DialogTitleBar), new PropertyMetadata("")); public static readonly DependencyProperty CloseCommandProperty = DependencyProperty.Register(nameof(CloseCommand), typeof(ICommand), typeof(DialogTitleBar), new PropertyMetadata(null)); public ICommand CloseCommand { get { return (ICommand)GetValue(CloseCommandProperty); } set { SetValue(CloseCommandProperty, value); } } public string TitleText { get { return (string)GetValue(TitleTextProperty); } set { SetValue(TitleTextProperty, value); } } public DialogTitleBar() { InitializeComponent(); } } }
31.454545
132
0.66185
[ "MIT" ]
Kosta1994/PixiEditor
PixiEditor/Views/Dialogs/DialogTitleBar.xaml.cs
1,040
C#
// Copyright (c) Tunnel Vision Laboratories, LLC. All Rights Reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. namespace StyleCop.Analyzers.Test.CSharp7.NamingRules { using System.Threading; using System.Threading.Tasks; using Microsoft.CodeAnalysis.Testing; using StyleCop.Analyzers.Test.NamingRules; using TestHelper; using Xunit; using static StyleCop.Analyzers.Test.Verifiers.StyleCopCodeFixVerifier< StyleCop.Analyzers.NamingRules.SA1312VariableNamesMustBeginWithLowerCaseLetter, StyleCop.Analyzers.NamingRules.RenameToLowerCaseCodeFixProvider>; public class SA1312CSharp7UnitTests : SA1312UnitTests { [Fact] public async Task TestThatDiagnosticIsReported_SingleVariableDesignatorAsync() { var testCode = @"public class TypeName { public void MethodName() { int.TryParse(""0"", out var Bar); int.TryParse(""0"", out var car); int.TryParse(""0"", out var Par); } }"; DiagnosticResult[] expected = { Diagnostic().WithArguments("Bar").WithLocation(5, 35), Diagnostic().WithArguments("Par").WithLocation(7, 35), }; var fixedCode = @"public class TypeName { public void MethodName() { int.TryParse(""0"", out var bar); int.TryParse(""0"", out var car); int.TryParse(""0"", out var par); } }"; await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestThatDiagnosticIsReported_MultipleVariableDesignatorsAsync() { var testCode = @"public class TypeName { public void MethodName() { var (Bar, car, Par) = (1, 2, 3); } }"; DiagnosticResult[] expected = { Diagnostic().WithArguments("Bar").WithLocation(5, 14), Diagnostic().WithArguments("Par").WithLocation(5, 24), }; var fixedCode = @"public class TypeName { public void MethodName() { var (bar, car, par) = (1, 2, 3); } }"; await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestVariableDesignatorStartingWithAnUnderscoreAsync() { // Makes sure SA1312 is reported for variables starting with an underscore var testCode = @"public class TypeName { public void MethodName() { int.TryParse(""baz"", out var _bar); } }"; var fixedTestCode = @"public class TypeName { public void MethodName() { int.TryParse(""baz"", out var bar); } }"; DiagnosticResult expected = Diagnostic().WithArguments("_bar").WithLocation(5, 37); await VerifyCSharpFixAsync(testCode, expected, fixedTestCode, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestVariableDesignatorInWhenClauseAsync() { var testCode = @" using System; public class TypeName { public void MethodName() { try { } catch (Exception ex) when (ex is ArgumentException ArgEx) { } } }"; var fixedCode = @" using System; public class TypeName { public void MethodName() { try { } catch (Exception ex) when (ex is ArgumentException argEx) { } } }"; DiagnosticResult expected = Diagnostic().WithArguments("ArgEx").WithLocation(10, 60); await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestPatternInForEachStatementAsync() { var testCode = @"public class TypeName { public void MethodName() { foreach (var (X, y) in new (int, int)[0]) { } } }"; var fixedCode = @"public class TypeName { public void MethodName() { foreach (var (x, y) in new (int, int)[0]) { } } }"; DiagnosticResult expected = Diagnostic().WithArguments("X").WithLocation(5, 23); await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestPatternInSwitchCaseAsync() { var testCode = @"public class TypeName { public void MethodName() { switch (new object()) { case int X: default: break; } } }"; var fixedCode = @"public class TypeName { public void MethodName() { switch (new object()) { case int x: default: break; } } }"; DiagnosticResult expected = Diagnostic().WithArguments("X").WithLocation(7, 18); await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestPatternPlacedInsideNativeMethodsClassAsync() { var testCode = @"public class FooNativeMethods { public void MethodName() { int.TryParse(""baz"", out var Bar); } }"; await VerifyCSharpDiagnosticAsync(testCode, DiagnosticResult.EmptyDiagnosticResults, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestPatternVariableRenameConflictsWithVariableAsync() { var testCode = @"public class TypeName { public void MethodName() { string variable = ""Text""; int.TryParse(variable.ToString(), out var Variable); } }"; DiagnosticResult expected = Diagnostic().WithArguments("Variable").WithLocation(6, 51); var fixedCode = @"public class TypeName { public void MethodName() { string variable = ""Text""; int.TryParse(variable.ToString(), out var variable1); } }"; await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestVariableRenameConflictsWithPatternVariableAsync() { var testCode = @"public class TypeName { public void MethodName() { int.TryParse(""Text"", out var variable); string Variable = variable.ToString(); } }"; DiagnosticResult expected = Diagnostic().WithArguments("Variable").WithLocation(6, 16); var fixedCode = @"public class TypeName { public void MethodName() { int.TryParse(""Text"", out var variable); string variable1 = variable.ToString(); } }"; await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestPatternVariableRenameConflictsWithKeywordAsync() { var testCode = @"public class TypeName { public void MethodName() { int.TryParse(""text"", out var Int); } }"; DiagnosticResult expected = Diagnostic().WithArguments("Int").WithLocation(5, 38); var fixedCode = @"public class TypeName { public void MethodName() { int.TryParse(""text"", out var @int); } }"; await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestPatternVariableRenameConflictsWithParameterAsync() { var testCode = @"public class TypeName { public void MethodName(int parameter) { int.TryParse(parameter.ToString(), out var Parameter); } }"; DiagnosticResult expected = Diagnostic().WithArguments("Parameter").WithLocation(5, 52); var fixedCode = @"public class TypeName { public void MethodName(int parameter) { int.TryParse(parameter.ToString(), out var parameter1); } }"; await VerifyCSharpFixAsync(testCode, expected, fixedCode, CancellationToken.None).ConfigureAwait(false); } [Fact] public async Task TestDiscardsDoNotTriggerCodeFixAsync() { var testCode = @"public class TypeName { public void MethodName(int parameter) { int.TryParse(parameter.ToString(), out var _); int.TryParse(parameter.ToString(), out var _); int.TryParse(parameter.ToString(), out var __); // This one isn't a discard } }"; DiagnosticResult expected = Diagnostic().WithArguments("__").WithLocation(7, 52); await VerifyCSharpFixAsync(testCode, expected, testCode, CancellationToken.None).ConfigureAwait(false); } } }
27.5
143
0.605654
[ "Apache-2.0" ]
Andreyul/StyleCopAnalyzers
StyleCop.Analyzers/StyleCop.Analyzers.Test.CSharp7/NamingRules/SA1312CSharp7UnitTests.cs
9,022
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AwsNative.NetworkFirewall.Inputs { public sealed class FirewallSubnetMappingArgs : Pulumi.ResourceArgs { /// <summary> /// A SubnetId. /// </summary> [Input("subnetId", required: true)] public Input<string> SubnetId { get; set; } = null!; public FirewallSubnetMappingArgs() { } } }
26
81
0.656805
[ "Apache-2.0" ]
AaronFriel/pulumi-aws-native
sdk/dotnet/NetworkFirewall/Inputs/FirewallSubnetMappingArgs.cs
676
C#
using System; using System.Threading.Tasks; using Twilio; using Twilio.Rest.Api.V2010.Account; namespace PharmVerse.Infrastructure.SMS { public class SMS { private string accountSid = Environment.GetEnvironmentVariable(("TWILIO_ACCOUNT_SID")); private string authToken = Environment.GetEnvironmentVariable("TWILIO_AUTH_TOKEN"); private string RecipientNumber { get; set; } public string Body { get; set; } public string From { get; set; } public SMS(string from, string to, string body) { From = from.ToString(); Body = body; RecipientNumber = to.ToString(); } public async void SendSms() { TwilioClient.Init(accountSid, authToken); var message = MessageResource.Create( body: Body, from: new Twilio.Types.PhoneNumber(From), to: new Twilio.Types.PhoneNumber(RecipientNumber) ); Console.WriteLine(message.Status); } } }
24.973684
91
0.671233
[ "MIT" ]
ddynamight/PharmVerse
PharmVerse/PharmVerse.Infrastructure/SMS/SMS.cs
949
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/wingdi.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="LOCALESIGNATURE" /> struct.</summary> public static unsafe class LOCALESIGNATURETests { /// <summary>Validates that the <see cref="LOCALESIGNATURE" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<LOCALESIGNATURE>(), Is.EqualTo(sizeof(LOCALESIGNATURE))); } /// <summary>Validates that the <see cref="LOCALESIGNATURE" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(LOCALESIGNATURE).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="LOCALESIGNATURE" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(LOCALESIGNATURE), Is.EqualTo(32)); } } }
38.055556
145
0.666423
[ "MIT" ]
Ethereal77/terrafx.interop.windows
tests/Interop/Windows/um/wingdi/LOCALESIGNATURETests.cs
1,372
C#
/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System.Collections.Generic; using Aeter.Ratio.Testing.Fakes.Entities; namespace Aeter.Ratio.Testing.Fakes.Graphs { public class CollectionOfComplexGraph { public List<Relation> Value { get; set; } } }
29
70
0.712644
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
jaygumji/Aeter.Ratio
Aeter.Ratio.Test/Fakes/Graphs/CollectionOfComplexGraph.cs
435
C#
using UnityEngine; using UnityEditor; using System; using System.Collections; using System.Reflection; using EasyMobile.Internal; namespace EasyMobile.Editor { [CustomPropertyDrawer(typeof(EnumFlagsAttribute))] public class EnumFlagsDrawer : PropertyDrawer { public override void OnGUI(Rect position, SerializedProperty property, GUIContent label) { EnumFlagsAttribute flagSettings = (EnumFlagsAttribute)attribute; Enum targetEnum = GetBaseProperty<Enum>(property); string propName = flagSettings.enumName; Enum enumNew; EditorGUI.BeginProperty(position, label, property); if (string.IsNullOrEmpty(propName)) { #if UNITY_2017_3_OR_NEWER enumNew = EditorGUI.EnumFlagsField(position, label, targetEnum); #else enumNew = EditorGUI.EnumMaskField(position, label, targetEnum); #endif } else { #if UNITY_2017_3_OR_NEWER enumNew = EditorGUI.EnumFlagsField(position, propName, targetEnum); #else enumNew = EditorGUI.EnumMaskField(position, propName, targetEnum); #endif } property.intValue = (int)Convert.ChangeType(enumNew, targetEnum.GetType()); EditorGUI.EndProperty(); } static T GetBaseProperty<T>(SerializedProperty prop) { string[] separatedPaths = prop.propertyPath.Split('.'); System.Object reflectionTarget = prop.serializedObject.targetObject as object; foreach (var path in separatedPaths) { FieldInfo fieldInfo = reflectionTarget.GetType().GetField(path, BindingFlags.NonPublic | BindingFlags.Public | BindingFlags.Instance); reflectionTarget = fieldInfo.GetValue(reflectionTarget); } return (T)reflectionTarget; } } }
35.964286
150
0.616187
[ "MIT" ]
AndreeBurlamaqui/HyperBeatMIX
Assets/EasyMobile/Editor/Common/PropertyDrawers/EnumFlagsDrawer.cs
2,016
C#
using System; namespace Шофиор_на_тир { class Program { static void Main(string[] args) { string season = Console.ReadLine(); double km = double.Parse(Console.ReadLine()); double kmPrice = 0; if (season == "Spring" || season == "Autumn") { if (km <= 5000) { kmPrice = km * 0.75; } else if (km > 5000 && km <= 10000) { kmPrice = km * 0.95; } else if (km > 10000 && km <= 20000) { kmPrice = km * 1.45; } } if (season == "Summer") { if (km <= 5000) { kmPrice = km * 0.90; } else if (km > 5000 && km <= 10000) { kmPrice = km * 1.10; } else if (km > 10000 && km <= 20000) { kmPrice = km * 1.45; } } if (season == "Winter") { if (km <= 5000) { kmPrice = km * 1.05; } else if (km > 5000 && km <= 10000) { kmPrice = km * 1.25; } else if (km > 10000 && km <= 20000) { kmPrice = km * 1.45; } } double finalKmPrice = (kmPrice * 0.90) * 4; Console.WriteLine($"{finalKmPrice:f2}"); } } }
26.888889
57
0.298701
[ "MIT" ]
Anzzhhela98/CSharp-Basics-Course
Conditional Statements Advanced/Nested Conditional Statements - More Exercises/06. Truck Driver/Program.cs
1,707
C#
using System.Reflection; using System.Runtime.InteropServices; [assembly: AssemblyTitle("WebApiContrib.Formatting.Xlsx sample app")] [assembly: AssemblyDescription("Sample application to demonstrate use of WebApiContrib.Formatting.Xlsx.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("WebApiContrib")] [assembly: AssemblyProduct("WebApiContrib.Formatting.Xlsx.Sample")] [assembly: AssemblyCopyright("2014 Jordan Gray, WebApiContrib team")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] [assembly: ComVisible(false)] [assembly: Guid("7b5cf620-153f-441e-97d2-dcab4d74756c")] [assembly: AssemblyVersion("2.0.*")] [assembly: AssemblyInformationalVersion("2.0.0-pre")]
41.647059
106
0.789548
[ "MIT" ]
ARKlab/WebApiContrib.Formatting.Xlsx
samples/WebApiContrib.Formatting.Xlsx.Sample/Properties/AssemblyInfo.cs
710
C#
namespace Potassium.Examples.MouseDrag { partial class Form1 { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; private System.Windows.Forms.Label label1; private System.Windows.Forms.TextBox x; private System.Windows.Forms.TextBox y; private System.Windows.Forms.Label label2; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.label1 = new System.Windows.Forms.Label(); this.x = new System.Windows.Forms.TextBox(); this.y = new System.Windows.Forms.TextBox(); this.label2 = new System.Windows.Forms.Label(); this.status = new System.Windows.Forms.TextBox(); this.label3 = new System.Windows.Forms.Label(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(12, 25); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(14, 13); this.label1.TabIndex = 0; this.label1.Text = "X"; // // x // this.x.Location = new System.Drawing.Point(94, 21); this.x.Name = "x"; this.x.ReadOnly = true; this.x.Size = new System.Drawing.Size(100, 20); this.x.TabIndex = 1; // // y // this.y.Location = new System.Drawing.Point(94, 61); this.y.Name = "y"; this.y.ReadOnly = true; this.y.Size = new System.Drawing.Size(100, 20); this.y.TabIndex = 3; // // label2 // this.label2.AutoSize = true; this.label2.Location = new System.Drawing.Point(12, 65); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(14, 13); this.label2.TabIndex = 2; this.label2.Text = "Y"; // // status // this.status.Location = new System.Drawing.Point(94, 96); this.status.Name = "status"; this.status.ReadOnly = true; this.status.Size = new System.Drawing.Size(100, 20); this.status.TabIndex = 5; // // label3 // this.label3.AutoSize = true; this.label3.Location = new System.Drawing.Point(12, 100); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(37, 13); this.label3.TabIndex = 4; this.label3.Text = "Status"; // // Form1 // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(710, 397); this.Controls.Add(this.status); this.Controls.Add(this.label3); this.Controls.Add(this.y); this.Controls.Add(this.label2); this.Controls.Add(this.x); this.Controls.Add(this.label1); this.Name = "Form1"; this.Text = "Form1"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.TextBox status; private System.Windows.Forms.Label label3; } }
35.428571
107
0.521347
[ "MIT" ]
jerometerry/potassium
examples/MouseDrag/Form1.Designer.cs
4,218
C#
/***************************************************************************** * Copyright 2016 Aurora Solutions * * http://www.aurorasolutions.io * * Aurora Solutions is an innovative services and product company at * the forefront of the software industry, with processes and practices * involving Domain Driven Design(DDD), Agile methodologies to build * scalable, secure, reliable and high performance products. * * Coin Exchange is a high performance exchange system specialized for * Crypto currency trading. It has different general purpose uses such as * independent deposit and withdrawal channels for Bitcoin and Litecoin, * but can also act as a standalone exchange that can be used with * different asset classes. * Coin Exchange uses state of the art technologies such as ASP.NET REST API, * AngularJS and NUnit. It also uses design patterns for complex event * processing and handling of thousands of transactions per second, such as * Domain Driven Designing, Disruptor Pattern and CQRS With Event Sourcing. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *****************************************************************************/ using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using CoinExchange.Trades.ReadModel.DTO; namespace CoinExchange.Trades.ReadModel.Repositories { public interface IOhlcRepository { OhlcReadModel GetOhlcByDateTime(DateTime dateTime); IList<object> GetOhlcByCurrencyPair(string currencyPair); } }
42.26
80
0.698533
[ "Apache-2.0" ]
3plcoins/coin-exchange-backend
src/Trades/CoinExchange.Trades.ReadModel/Repositories/IOhlcRepository.cs
2,115
C#
using System.IO; using Microsoft.AspNetCore.Hosting; using SDDL.Web.Services.Interface; namespace SDDL.Web.Services { public class SpaService : ISpaService { private readonly IWebHostEnvironment _env; public SpaService(IWebHostEnvironment env) { _env = env; } public string GetIndexFilePath() { return Path.Combine(_env.ContentRootPath, @"wwwroot/dist/static/index.html"); } } }
23
80
0.729469
[ "MIT" ]
Wufe/sddl
Presentation/SDDL.Web/Services/SpaService.cs
414
C#
using Microsoft.Framework.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace WeConnect.Core { public interface IWechat { ITokenManager TokenManager { get; } IServiceProvider ServiceResolver { get; } ILoggerFactory LogFactory { get; } } }
21.3125
49
0.71261
[ "MIT" ]
wechat-cloud/we-connect
src/WeConnect.Core/IWechat.cs
343
C#
using System; namespace _01._Repainting { class Program { static void Main(string[] args) { //Предпазен найлон -1.50 лв.за кв.м. //Боя - 14.50 лв.за литър //Разредител за боя - 5.00 лв.за литър //+ 10 % от количеството боя //+ 2 кв.м.найлон //+ 0.40 лв.за торбички //1 час работа, = 30 % от сбора на всички разходи за материали int naylon = int.Parse(Console.ReadLine()); int paintLTR = int.Parse(Console.ReadLine()); int diluentLTR = int.Parse(Console.ReadLine()); int hours = int.Parse(Console.ReadLine()); double naylonPrice = naylon * 1.5; double paintPrice = paintLTR * 14.5; double diluentPrice = diluentLTR * 5; double naylonTotal = naylonPrice + (2 * 1.5); double paintTotal = paintPrice + (paintPrice * 0.1); double total = naylonTotal + paintTotal + diluentPrice + 0.4; double workersPrice = total * 0.3; double all = workersPrice * hours; double allTotal = all + total; Console.WriteLine($"Total expenses: {allTotal:F2} lv."); } } }
29.619048
74
0.538585
[ "MIT" ]
GeorgiGradev/SoftUni
01. Programming Basics/02.4. EXAM - Simple Operations and Calculations/Repainting/Program.cs
1,384
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.CloudTrail { public static partial class Invokes { /// <summary> /// Use this data source to get the Account ID of the [AWS CloudTrail Service Account](http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-supported-regions.html) /// in a given region for the purpose of allowing CloudTrail to store trail data in S3. /// /// /// /// &gt; This content is derived from https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/d/cloudtrail_service_account.html.markdown. /// </summary> [Obsolete("Use GetServiceAccount.InvokeAsync() instead")] public static Task<GetServiceAccountResult> GetServiceAccount(GetServiceAccountArgs? args = null, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetServiceAccountResult>("aws:cloudtrail/getServiceAccount:getServiceAccount", args ?? InvokeArgs.Empty, options.WithVersion()); } public static class GetServiceAccount { /// <summary> /// Use this data source to get the Account ID of the [AWS CloudTrail Service Account](http://docs.aws.amazon.com/awscloudtrail/latest/userguide/cloudtrail-supported-regions.html) /// in a given region for the purpose of allowing CloudTrail to store trail data in S3. /// /// /// /// &gt; This content is derived from https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/d/cloudtrail_service_account.html.markdown. /// </summary> public static Task<GetServiceAccountResult> InvokeAsync(GetServiceAccountArgs? args = null, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetServiceAccountResult>("aws:cloudtrail/getServiceAccount:getServiceAccount", args ?? InvokeArgs.Empty, options.WithVersion()); } public sealed class GetServiceAccountArgs : Pulumi.InvokeArgs { /// <summary> /// Name of the region whose AWS CloudTrail account ID is desired. /// Defaults to the region from the AWS provider configuration. /// </summary> [Input("region")] public string? Region { get; set; } public GetServiceAccountArgs() { } } [OutputType] public sealed class GetServiceAccountResult { /// <summary> /// The ARN of the AWS CloudTrail service account in the selected region. /// </summary> public readonly string Arn; public readonly string? Region; /// <summary> /// id is the provider-assigned unique ID for this managed resource. /// </summary> public readonly string Id; [OutputConstructor] private GetServiceAccountResult( string arn, string? region, string id) { Arn = arn; Region = region; Id = id; } } }
42.075949
187
0.657641
[ "ECL-2.0", "Apache-2.0" ]
Dominik-K/pulumi-aws
sdk/dotnet/Cloudtrail/GetServiceAccount.cs
3,324
C#
//------------------------------------------------------------------------------ // <auto-generated> // 本文件代码自动生成。用于实现强类型接口,方便应用层使用。 // 版本号:1.6.0 // // 请勿修改,否则在重新生成时,所有修改会丢失。 // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Linq.Expressions; using System.Text; using Rafy; using Rafy.ComponentModel; using Rafy.Data; using Rafy.Domain; using Rafy.Domain.ORM; namespace UT { partial class PBSList { #region 强类型公有接口 /// <summary> /// 获取或设置指定位置的实体。 /// </summary> /// <param name="index"></param> /// <returns></returns> public new PBS this[int index] { get { return base[index] as PBS; } set { base[index] = value; } } /// <summary> /// 获取本实体列表的迭代器。 /// </summary> /// <returns></returns> [DebuggerStepThrough] public new IEnumerator<PBS> GetEnumerator() { return new EntityListEnumerator<PBS>(this); } /// <summary> /// 返回子实体的强类型迭代接口,方便使用 Linq To Object 操作。 /// </summary> /// <returns></returns> [DebuggerStepThrough] public IEnumerable<PBS> Concrete() { return this.Cast<PBS>(); } /// <summary> /// 添加指定的实体到集合中。 /// </summary> [DebuggerStepThrough] public void Add(PBS entity) { base.Add(entity); } /// <summary> /// 判断本集合是否包含指定的实体。 /// </summary> /// <returns></returns> [DebuggerStepThrough] public bool Contains(PBS entity) { return base.Contains(entity); } /// <summary> /// 判断指定的实体在本集合中的索引号。 /// </summary> /// <returns></returns> [DebuggerStepThrough] public int IndexOf(PBS entity) { return base.IndexOf(entity); } /// <summary> /// 在指定的位置插入实体。 /// </summary> /// <returns></returns> [DebuggerStepThrough] public void Insert(int index, PBS entity) { base.Insert(index, entity); } /// <summary> /// 在集合中删除指定的实体。返回是否成功删除。 /// </summary> /// <returns></returns> [DebuggerStepThrough] public bool Remove(PBS entity) { return base.Remove(entity); } #endregion } partial class PBSRepository { #region 私有方法,本类内部使用 /// <summary> /// 创建一个实体类的 Linq 查询器 /// </summary> /// <returns></returns> [DebuggerStepThrough] private IQueryable<PBS> CreateLinqQuery() { return base.CreateLinqQuery<PBS>(); } #endregion #region 强类型公有接口 /// <summary> /// 创建一个新的实体。 /// </summary> /// <returns></returns> [DebuggerStepThrough] public new PBS New() { return base.New() as PBS; } /// <summary> /// 创建一个全新的列表 /// </summary> /// <returns></returns> [DebuggerStepThrough] public new PBSList NewList() { return base.NewList() as PBSList; } /// <summary> /// 优先使用缓存中的数据来通过 Id 获取指定的实体对象 /// /// 如果该实体的缓存没有打开,则本方法会直接调用 GetById 并返回结果。 /// 如果缓存中没有这些数据,则本方法同时会把数据缓存起来。 /// </summary> /// <param name="id"></param> /// <returns></returns> [DebuggerStepThrough] public new PBS CacheById(object id) { return base.CacheById(id) as PBS; } /// <summary> /// 优先使用缓存中的数据来查询所有的实体类 /// /// 如果该实体的缓存没有打开,则本方法会直接调用 GetAll 并返回结果。 /// 如果缓存中没有这些数据,则本方法同时会把数据缓存起来。 /// </summary> /// <returns></returns> [DebuggerStepThrough] public new PBSList CacheAll() { return base.CacheAll() as PBSList; } /// <summary> /// 通过Id在数据层中查询指定的对象 /// </summary> /// <param name="id"></param> /// <param name="loadOptions">数据加载时选项(贪婪加载等)。</param> /// <returns></returns> [DebuggerStepThrough] public new PBS GetById(object id, LoadOptions loadOptions = null) { return base.GetById(id, loadOptions) as PBS; } /// <summary> /// 查询第一个实体类 /// </summary> /// <param name="loadOptions">数据加载时选项(贪婪加载等)。</param> /// <returns></returns> [DebuggerStepThrough] public new PBS GetFirst(LoadOptions loadOptions = null) { return base.GetFirst(loadOptions) as PBS; } /// <summary> /// 分页查询所有的实体类 /// </summary> /// <param name="paging"></param> /// <param name="loadOptions">数据加载时选项(贪婪加载等)。</param> /// <returns></returns> [DebuggerStepThrough] public new PBSList GetAll(PagingInfo paging = null, LoadOptions loadOptions = null) { return base.GetAll(paging, loadOptions) as PBSList; } /// <summary> /// 获取指定 id 集合的实体列表。 /// </summary> /// <param name="idList"></param> /// <param name="loadOptions">数据加载时选项(贪婪加载等)。</param> /// <returns></returns> [DebuggerStepThrough] public new PBSList GetByIdList(object[] idList, LoadOptions loadOptions = null) { return base.GetByIdList(idList, loadOptions) as PBSList; } /// <summary> /// 通过组合父对象的 Id 列表,查找所有的组合子对象的集合。 /// </summary> /// <param name="parentIdList"></param> /// <param name="paging">分页信息。</param> /// <param name="loadOptions">数据加载时选项(贪婪加载等)。</param> /// <returns></returns> [DebuggerStepThrough] public new PBSList GetByParentIdList(object[] parentIdList, PagingInfo paging = null, LoadOptions loadOptions = null) { return base.GetByParentIdList(parentIdList, paging, loadOptions) as PBSList; } /// <summary> /// 通过父对象 Id 分页查询子对象的集合。 /// </summary> /// <param name="parentId"></param> /// <param name="paging">分页信息。</param> /// <param name="loadOptions">数据加载时选项(贪婪加载等)。</param> /// <returns></returns> [DebuggerStepThrough] public new PBSList GetByParentId(object parentId, PagingInfo paging = null, LoadOptions loadOptions = null) { return base.GetByParentId(parentId, paging, loadOptions) as PBSList; } /// <summary> /// 通过 CommonQueryCriteria 来查询实体列表。 /// </summary> /// <param name="criteria">常用查询条件。</param> /// <returns></returns> [DebuggerStepThrough] public new PBSList GetBy(CommonQueryCriteria criteria) { return base.GetBy(criteria) as PBSList; } /// <summary> /// 通过 CommonQueryCriteria 来查询单一实体。 /// </summary> /// <param name="criteria">常用查询条件。</param> /// <returns></returns> [DebuggerStepThrough] public new PBS GetFirstBy(CommonQueryCriteria criteria) { return base.GetFirstBy(criteria) as PBS; } /// <summary> /// 递归查找所有树型子 /// </summary> /// <param name="treeIndex"></param> /// <param name="loadOptions">数据加载时选项(贪婪加载等)。</param> /// <returns></returns> [DebuggerStepThrough] public new PBSList GetByTreeParentIndex(string treeIndex, LoadOptions loadOptions = null) { return base.GetByTreeParentIndex(treeIndex, loadOptions) as PBSList; } /// <summary> /// 查找指定树节点的直接子节点。 /// </summary> /// <param name="treePId">需要查找的树节点的Id.</param> /// <param name="loadOptions">数据加载时选项(贪婪加载等)。</param> /// <returns></returns> [DebuggerStepThrough] public new PBSList GetByTreePId(object treePId, LoadOptions loadOptions = null) { return base.GetByTreePId(treePId, loadOptions) as PBSList; } #endregion } }
27.726073
125
0.511606
[ "MIT" ]
zgynhqf/trunk
Test/Rafy.UnitTest/.g.cs/PBS.g.cs
9,723
C#
using System; using System.Collections.Generic; using System.IO; using System.Threading.Tasks; using WalletWasabi.WebClients; using Microsoft.AspNetCore.Builder; using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using Swashbuckle.AspNetCore.Swagger; using WalletWasabi.Logging; using WalletWasabi.Interfaces; using WalletWasabi.Backend.Middlewares; namespace WalletWasabi.Backend { public class Startup { // This method gets called by the runtime. Use this method to add services to the container. public void ConfigureServices(IServiceCollection services) { services.AddMemoryCache(); services.AddMvc() .AddControllersAsServices(); // Register the Swagger generator, defining one or more Swagger documents services.AddSwaggerGen(c => { c.SwaggerDoc($"v{Helpers.Constants.BackendMajorVersion}", new Info { Version = $"v{Helpers.Constants.BackendMajorVersion}", Title = "Wasabi Wallet API", Description = "Privacy focused, ZeroLink compliant Bitcoin Web API.", License = new License { Name = "Use under MIT.", Url = "https://github.com/zkSNACKs/WalletWasabi/blob/master/LICENSE.md" } }); // Set the comments path for the Swagger JSON and UI. var basePath = AppContext.BaseDirectory; var xmlPath = Path.Combine(basePath, "WalletWasabi.Backend.xml"); c.IncludeXmlComments(xmlPath); }); services.AddLogging(Logging => Logging.AddFilter((s, level) => level >= Microsoft.Extensions.Logging.LogLevel.Warning)); services.AddSingleton<IExchangeRateProvider>(new ExchangeRateProvider()); } // This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env) { app.UseStaticFiles(); // Enable middleware to serve generated Swagger as a JSON endpoint. app.UseSwagger(); // Enable middleware to serve swagger-ui (HTML, JS, CSS, etc.), specifying the Swagger JSON endpoint. app.UseSwaggerUI(c => { c.SwaggerEndpoint("/swagger/v2/swagger.json", "Wasabi Wallet API V2"); }); // So to correctly handle HEAD requests. // https://www.tpeczek.com/2017/10/exploring-head-method-behavior-in.html // https://github.com/tpeczek/Demo.AspNetCore.Mvc.CosmosDB/blob/master/Demo.AspNetCore.Mvc.CosmosDB/Middlewares/HeadMethodMiddleware.cs app.UseMiddleware<HeadMethodMiddleware>(); app.UseMvc(); var applicationLifetime = app.ApplicationServices.GetRequiredService<IApplicationLifetime>(); applicationLifetime.ApplicationStopping.Register(OnShutdown); // Don't register async, that won't hold up the shutdown } private void OnShutdown() { CleanupAsync().GetAwaiter().GetResult(); // This is needed, if async function is regisered then it won't wait until it finishes } private async Task CleanupAsync() { Global.Coordinator?.Dispose(); Logger.LogInfo<Startup>("Coordinator is disposed."); var stopTasks = new List<Task>(); if (!(Global.IndexBuilderService is null)) { Global.IndexBuilderService.NewBlock -= Global.IndexBuilderService_NewBlockAsync; var t = Global.IndexBuilderService.StopAsync(); stopTasks.Add(t); } if (!(Global.RoundConfigWatcher is null)) { var t = Global.RoundConfigWatcher.StopAsync(); stopTasks.Add(t); } await Task.WhenAll(stopTasks); Logger.LogInfo<Startup>("IndexBuilderService is disposed."); Logger.LogInfo<Startup>("RoundConfigWatcher is disposed."); } } }
33.92381
138
0.739191
[ "MIT" ]
BrianSipple/WalletWasabi
WalletWasabi.Backend/Startup.cs
3,564
C#
using Microsoft.AspNetCore.Hosting; using Microsoft.Extensions.Configuration; using Microsoft.Extensions.Hosting; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace Coupe.Account.API { public class Program { public static void Main(string[] args) { CreateHostBuilder(args).Build().Run(); } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }); } }
25.888889
70
0.645207
[ "MIT" ]
OfficialYeti/Coupe
src/Account/Coupe.Account.API/Program.cs
699
C#
using System; using System.Linq; using System.Collections.Generic; using cqhttp.Cyan.Events.CQEvents; using cqhttp.Cyan.Utils; using System.Reflection; namespace cqhttp.Cyan.Events { [AttributeUsage (AttributeTargets.Class | AttributeTargets.Interface, AllowMultiple = false)] class DiscriminatorValueAttribute : Attribute { public string _value { get; private set; } public DiscriminatorValueAttribute (string value) => _value = value; } class BaseEventDiscriminatorOptions : DiscriminatorOptions { public override Type BaseType => typeof (Events.CQEvents.Base.CQEvent); public override Type FallbackType => typeof (UnknownEvent); public override string DiscriminatorFieldName => throw new NotImplementedException (); public override bool SerializeDiscriminator => true; public override IEnumerable<(string TypeName, Type Type)> GetDiscriminatedTypes () { foreach (var t in GetSubtypes (BaseType)) { var attr = t.GetCustomAttribute<DiscriminatorValueAttribute> (false); if (attr != null) yield return (attr._value, t.AsType ()); } } public TypeInfo[] GetSubtypes (Type type) { return type.Assembly.GetTypes ().AsParallel ().Where ( (t) => t.IsSubclassOf (type) ).Select (t => t.GetTypeInfo ()).ToArray (); } } class EventDiscriminatorOptions : BaseEventDiscriminatorOptions { public override string DiscriminatorFieldName => "post_type"; public override IEnumerable<(string TypeName, Type Type)> GetDiscriminatedTypes () { yield return ("request", typeof (CQEvents.Base.RequestEvent)); yield return ("message", typeof (CQEvents.Base.MessageEvent)); yield return ("notice", typeof (CQEvents.Base.NoticeEvent)); yield return ("meta_event", typeof (CQEvents.MetaEvents.MetaEvent)); } } class RequestEventDiscriminatorOptions : BaseEventDiscriminatorOptions { public override Type BaseType => typeof (Events.CQEvents.Base.RequestEvent); public override string DiscriminatorFieldName => "request_type"; } class NoticeEventDiscriminatorOptions : BaseEventDiscriminatorOptions { public override Type BaseType => typeof (Events.CQEvents.Base.NoticeEvent); public override string DiscriminatorFieldName => "notice_type"; } class MessageEventDiscriminatorOptions : BaseEventDiscriminatorOptions { public override Type BaseType => typeof (Events.CQEvents.Base.MessageEvent); public override string DiscriminatorFieldName => "message_type"; } class MetaEventDiscriminatorOptions : BaseEventDiscriminatorOptions { public override Type BaseType => typeof (CQEvents.MetaEvents.MetaEvent); public override string DiscriminatorFieldName => "meta_event_type"; } class NotifyNoticeEventDiscriminatorOptions : BaseEventDiscriminatorOptions { public override Type BaseType => typeof (CQEvents.NotifyEvent); public override string DiscriminatorFieldName => "sub_type"; } }
52.466667
97
0.702986
[ "MIT" ]
frank-bots/cqhttp.Cyan
cqhttp.Cyan/Events/Serialization.cs
3,148
C#
using UnityEngine; using System.Collections; //Needs to refernece LobbyHook using UnityStandardAssets.Network; public class GameLobbyHook : LobbyHook { public override void OnLobbyServerSceneLoadedForPlayer(UnityEngine.Networking.NetworkManager manager, GameObject lobbyPlayer, GameObject gamePlayer) { LobbyPlayer l = lobbyPlayer.GetComponent<LobbyPlayer>(); GamePlayer player_obj = gamePlayer.GetComponent<GamePlayer>(); player_obj.number = l.slot; player_obj.color = l.playerColor; player_obj.playerName = l.playerName; GameManager.AddPlayer(player_obj); } }
29.35
149
0.797274
[ "MIT" ]
TobiahZ/UnityNetwork
UnityNetwork/Assets/NewExample/GameLobbyHook.cs
589
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("tSecret")] [assembly: AssemblyDescription("tSecret Xamarin Forms Version")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Manabu Tonosaki")] [assembly: AssemblyProduct("tSecret")] [assembly: AssemblyCopyright("Copyright © 2020 Manabu Tonosaki")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("2.0.0.0")] [assembly: AssemblyFileVersion("2.0.0.0")] [assembly: ComVisible(false)]
37.571429
84
0.743346
[ "MIT" ]
mtonosaki/tSecret
tSecretXamarin/tSecretXamarin.UWP/Properties/AssemblyInfo.cs
1,055
C#
#region Copyright /* * The original .NET implementation of the SimMetrics library is taken from the Java * source and converted to NET using the Microsoft Java converter. * It is notclear who made the initial convertion to .NET. * * This updated version has started with the 1.0 .NET release of SimMetrics and used * FxCop (http://www.gotdotnet.com/team/fxcop/) to highlight areas where changes needed * to be made to the converted code. * * this version with updates Copyright (c) 2006 Chris Parkinson. * * For any queries on the .NET version please contact me through the * sourceforge web address. * * SimMetrics - SimMetrics is a java library of Similarity or Distance * Metrics, e.g. Levenshtein Distance, that provide float based similarity * measures between string Data. All metrics return consistant measures * rather than unbounded similarity scores. * * Copyright (C) 2005 Sam Chapman - Open Source Release v1.1 * * Please Feel free to contact me about this library, I would appreciate * knowing quickly what you wish to use it for and any criticisms/comments * upon the SimMetric library. * * email: s.chapman@dcs.shef.ac.uk * www: http://www.dcs.shef.ac.uk/~sam/ * www: http://www.dcs.shef.ac.uk/~sam/stringmetrics.html * * address: Sam Chapman, * Department of Computer Science, * University of Sheffield, * Sheffield, * S. Yorks, * S1 4DP * United Kingdom, * * This program is free software; you can redistribute it and/or modify it * under the terms of the GNU General Public License as published by the * Free Software Foundation; either version 2 of the License, or (at your * option) any later version. * * This program is distributed in the hope that it will be useful, but * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY * or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License * for more details. * * You should have received a copy of the GNU General Public License along * with this program; if not, write to the Free Software Foundation, Inc., * 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ #endregion namespace SimMetricsApi { using System; /// <summary> /// abstract class used as a base for all affine gap classes /// </summary> [Serializable] abstract public class AbstractAffineGapCost : IAffineGapCost { /// <summary> /// get cost between characters. /// </summary> /// <param name="textToGap">the string to get the cost of a gap</param> /// <param name="stringIndexStartGap">the index within the string to test a start gap from</param> /// <param name="stringIndexEndGap">the index within the string to test a end gap to</param> /// <returns>the cost of a Gap G</returns> abstract public double GetCost(string textToGap, int stringIndexStartGap, int stringIndexEndGap); /// <summary> /// returns the maximum possible cost. /// </summary> abstract public double MaxCost { get; } /// <summary> /// returns the minimum possible cost. /// </summary> abstract public double MinCost { get; } /// <summary> /// returns the name of the cost function. /// </summary> abstract public string ShortDescriptionString { get; } } }
39.701149
106
0.674001
[ "MIT" ]
FrozenInclude/BadWordFilter
src/BadWordFilter/sim/BaseClass/abstract/AbstractAffineGapCost.cs
3,454
C#
using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.Linq.Expressions; #if CONTRACTS_FULL_SHIM using Contract = System.Diagnostics.ContractsShim.Contract; #else using Contract = System.Diagnostics.Contracts.Contract; // SHIM'D #endif namespace KSoft { // Based on http://www.codeproject.com/KB/cs/EnumComparer.aspx public static class EnumComparer { public static EnumComparer<TEnum> For<TEnum>() where TEnum : struct, IComparable, IConvertible, IFormattable { Contract.Ensures(Contract.Result<EnumComparer<TEnum>>() != null); return EnumComparer<TEnum>.Instance; } }; /// <summary> /// A fast and efficient implementation of <see cref="IEqualityComparer{T}"/> for Enum types. /// Useful for dictionaries that use Enums as their keys. /// /// Also implements <see cref="IComparer{T}"/> /// </summary> /// <example> /// <code> /// var dict = new Dictionary&lt;DayOfWeek, string&gt;(EnumComparer&lt;DayOfWeek&gt;.Instance); /// </code> /// </example> /// <typeparam name="TEnum">The type of the Enum.</typeparam> /// <remarks>ATTN: This code is based on the following article: http://www.codeproject.com/KB/cs/EnumComparer.aspx</remarks> public sealed class EnumComparer<TEnum> : Reflection.EnumUtilBase<TEnum>, IComparer<TEnum>, IEqualityComparer<TEnum> where TEnum : struct, IComparable, IConvertible, IFormattable { const string kCompareMethodName = "CompareTo"; static readonly Func<TEnum, TEnum, bool> kEqualsMethod; static readonly Func<TEnum, int> kGetHashCodeMethod; static readonly Func<TEnum, TEnum, int> kCompareMethod; /// <summary>The singleton accessor.</summary> public static readonly EnumComparer<TEnum> Instance; /// <summary>Initializes the <see cref="EnumComparer{TEnum}"/> class by generating the GetHashCode and Equals methods.</summary> [SuppressMessage("Microsoft.Design", "CA1810:InitializeReferenceTypeStaticFieldsInline")] static EnumComparer() { Reflection.EnumUtils.AssertTypeIsEnum(kEnumType); Reflection.EnumUtils.AssertUnderlyingTypeIsSupported(kEnumType, kUnderlyingType); kGetHashCodeMethod = GenerateGetHashCodeMethod(); kEqualsMethod = GenerateEqualsMethod(); kCompareMethod = GenerateCompareMethod(); Instance = new EnumComparer<TEnum>(); } /// <summary>Private constructor to prevent user instantiation.</summary> EnumComparer() { } #region IEqualityComparer<TEnum> Members /// <summary>Determines whether the specified objects are equal.</summary> /// <param name="x">The first object of type <typeparamref name="TEnum"/> to compare.</param> /// <param name="y">The second object of type <typeparamref name="TEnum"/> to compare.</param> /// <returns> /// true if the specified objects are equal; otherwise, false. /// </returns> public bool Equals(TEnum x, TEnum y) { return kEqualsMethod(x, y); } /// <summary>Returns a hash code for the specified object.</summary> /// <param name="obj">The <see cref="System.Object"/> for which a hash code is to be returned.</param> /// <returns>A hash code for the specified object.</returns> /// <exception cref="System.ArgumentNullException"> /// The type of <paramref name="obj"/> is a reference type and <paramref name="obj"/> is null. /// </exception> public int GetHashCode(TEnum obj) { return kGetHashCodeMethod(obj); } /// <summary>Generates a comparison method similar to this: /// <code> /// bool Equals(TEnum x, TEnum y) /// { /// return x == y; /// } /// </code> /// </summary> /// <returns>The generated method.</returns> static Func<TEnum, TEnum, bool> GenerateEqualsMethod() { var xParam = Expression.Parameter(kEnumType, "x"); var yParam = Expression.Parameter(kEnumType, "y"); var equalExpression = Expression.Equal(xParam, yParam); var lambda = Expression.Lambda<Func<TEnum, TEnum, bool>>(equalExpression, xParam, yParam); return lambda.Compile(); } /// <summary>Generates a GetHashCode method similar to this: /// <code> /// int GetHashCode(TEnum obj) /// { /// return ((int)obj).GetHashCode(); /// } /// </code> /// </summary> /// <returns>The generated method.</returns> static Func<TEnum, int> GenerateGetHashCodeMethod() { var objParam = Expression.Parameter(kEnumType, "obj"); var convertExpression = Expression.Convert(objParam, kUnderlyingType); var getHashCodeMethod = kUnderlyingType.GetMethod("GetHashCode"); var getHashCodeExpression = Expression.Call(convertExpression, getHashCodeMethod); var lambda = Expression.Lambda<Func<TEnum, int>>(getHashCodeExpression, objParam); return lambda.Compile(); } #endregion #region IComparer<TEnum> Members public int Compare(TEnum x, TEnum y) { return kCompareMethod(x, y); } /// <summary>Generates a comparison method similar to this: /// <code> /// int Compare(TEnum x, TEnum y) /// { /// return ( (int)x ).CompareTo( (int)y ); /// } /// </code> /// Where 'int' is the underlying integer type. /// </summary> /// <returns>The generated method.</returns> static Func<TEnum, TEnum, int> GenerateCompareMethod() { var xParam = Expression.Parameter(Reflection.EnumUtil<TEnum>.EnumType, "x"); var yParam = Expression.Parameter(Reflection.EnumUtil<TEnum>.EnumType, "y"); var xAsInt = Expression.Convert(xParam, kUnderlyingType); var yAsInt = Expression.Convert(yParam, kUnderlyingType); var compareExpression = Expression.Call(xAsInt, kCompareMethodName, null, yAsInt); var lambda = Expression.Lambda<Func<TEnum, TEnum, int>>(compareExpression, xParam, yParam); return lambda.Compile(); } #endregion }; }
37.525641
131
0.687906
[ "MIT" ]
KornnerStudios/KSoft
KSoft/Enum/EnumComparer.cs
5,856
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Razor.Language.Syntax; using Xunit; namespace Microsoft.AspNetCore.Razor.Language.Legacy { public class TagHelperParseTreeRewriterTest : TagHelperRewritingTestBase { public static TheoryData GetAttributeNameValuePairsData { get { Func<string, string, KeyValuePair<string, string>> kvp = (key, value) => new KeyValuePair<string, string>(key, value); var empty = Enumerable.Empty<KeyValuePair<string, string>>(); var csharp = TagHelperParseTreeRewriter.Rewriter.InvalidAttributeValueMarker; // documentContent, expectedPairs return new TheoryData<string, IEnumerable<KeyValuePair<string, string>>> { { "<a>", empty }, { "<a @{ } href='~/home'>", empty }, { "<a href=\"@true\">", new[] { kvp("href", csharp) } }, { "<a href=\"prefix @true suffix\">", new[] { kvp("href", $"prefix{csharp} suffix") } }, { "<a href=~/home>", new[] { kvp("href", "~/home") } }, { "<a href=~/home @{ } nothing='something'>", new[] { kvp("href", "~/home") } }, { "<a href=\"@DateTime.Now::0\" class='btn btn-success' random>", new[] { kvp("href", $"{csharp}::0"), kvp("class", "btn btn-success"), kvp("random", "") } }, { "<a href=>", new[] { kvp("href", "") } }, { "<a href='\"> ", new[] { kvp("href", "\"> ") } }, { "<a href'", new[] { kvp("href'", "") } }, }; } } [Theory] [MemberData(nameof(GetAttributeNameValuePairsData))] public void GetAttributeNameValuePairs_ParsesPairsCorrectly( string documentContent, IEnumerable<KeyValuePair<string, string>> expectedPairs ) { // Arrange var errorSink = new ErrorSink(); var parseResult = ParseDocument(documentContent); var document = parseResult.Root; var parseTreeRewriter = new TagHelperParseTreeRewriter.Rewriter( parseResult.Source, null, Enumerable.Empty<TagHelperDescriptor>(), parseResult.Options.FeatureFlags, errorSink ); // Assert - Guard var rootBlock = Assert.IsType<RazorDocumentSyntax>(document); var rootMarkup = Assert.IsType<MarkupBlockSyntax>(rootBlock.Document); var childBlock = Assert.Single(rootMarkup.Children); var element = Assert.IsType<MarkupElementSyntax>(childBlock); Assert.Empty(errorSink.Errors); // Act var pairs = parseTreeRewriter.GetAttributeNameValuePairs(element.StartTag); // Assert Assert.Equal(expectedPairs, pairs); } public static TagHelperDescriptor[] PartialRequiredParentTags_Descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("StrongTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("strong")) .TagMatchingRuleDescriptor(rule => rule.RequireTagName("div")) .Build(), TagHelperDescriptorBuilder .Create("CatchALlTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("*")) .Build(), TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .Build(), }; [Fact] public void UnderstandsPartialRequiredParentTags1() { var document = "<p><strong>"; EvaluateData(PartialRequiredParentTags_Descriptors, document); } [Fact] public void UnderstandsPartialRequiredParentTags2() { var document = "<p><strong></strong>"; EvaluateData(PartialRequiredParentTags_Descriptors, document); } [Fact] public void UnderstandsPartialRequiredParentTags3() { var document = "<p><strong></p><strong>"; EvaluateData(PartialRequiredParentTags_Descriptors, document); } [Fact] public void UnderstandsPartialRequiredParentTags4() { var document = "<<p><<strong></</strong</strong></p>"; EvaluateData(PartialRequiredParentTags_Descriptors, document); } [Fact] public void UnderstandsPartialRequiredParentTags5() { var document = "<<p><<strong></</strong></strong></p>"; EvaluateData(PartialRequiredParentTags_Descriptors, document); } [Fact] public void UnderstandsPartialRequiredParentTags6() { var document = "<<p><<custom></<</custom></custom></p>"; EvaluateData(PartialRequiredParentTags_Descriptors, document); } public static TagHelperDescriptor[] NestedVoidSelfClosingRequiredParent_Descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("InputTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("input") .RequireTagStructure(TagStructure.WithoutEndTag) ) .Build(), TagHelperDescriptorBuilder .Create("StrongTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("strong").RequireParentTag("p") ) .TagMatchingRuleDescriptor( rule => rule.RequireTagName("strong").RequireParentTag("input") ) .Build(), TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .Build(), }; [Fact] public void UnderstandsNestedVoidSelfClosingRequiredParent1() { var document = "<input><strong></strong>"; EvaluateData(NestedVoidSelfClosingRequiredParent_Descriptors, document); } [Fact] public void UnderstandsNestedVoidSelfClosingRequiredParent2() { var document = "<p><input><strong></strong></p>"; EvaluateData(NestedVoidSelfClosingRequiredParent_Descriptors, document); } [Fact] public void UnderstandsNestedVoidSelfClosingRequiredParent3() { var document = "<p><br><strong></strong></p>"; EvaluateData(NestedVoidSelfClosingRequiredParent_Descriptors, document); } [Fact] public void UnderstandsNestedVoidSelfClosingRequiredParent4() { var document = "<p><p><br></p><strong></strong></p>"; EvaluateData(NestedVoidSelfClosingRequiredParent_Descriptors, document); } [Fact] public void UnderstandsNestedVoidSelfClosingRequiredParent5() { var document = "<input><strong></strong>"; EvaluateData(NestedVoidSelfClosingRequiredParent_Descriptors, document); } [Fact] public void UnderstandsNestedVoidSelfClosingRequiredParent6() { var document = "<p><input /><strong /></p>"; EvaluateData(NestedVoidSelfClosingRequiredParent_Descriptors, document); } [Fact] public void UnderstandsNestedVoidSelfClosingRequiredParent7() { var document = "<p><br /><strong /></p>"; EvaluateData(NestedVoidSelfClosingRequiredParent_Descriptors, document); } [Fact] public void UnderstandsNestedVoidSelfClosingRequiredParent8() { var document = "<p><p><br /></p><strong /></p>"; EvaluateData(NestedVoidSelfClosingRequiredParent_Descriptors, document); } public static TagHelperDescriptor[] NestedRequiredParent_Descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("StrongTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("strong").RequireParentTag("p") ) .TagMatchingRuleDescriptor( rule => rule.RequireTagName("strong").RequireParentTag("div") ) .Build(), TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .Build(), }; [Fact] public void UnderstandsNestedRequiredParent1() { var document = "<strong></strong>"; EvaluateData(NestedRequiredParent_Descriptors, document); } [Fact] public void UnderstandsNestedRequiredParent2() { var document = "<p><strong></strong></p>"; EvaluateData(NestedRequiredParent_Descriptors, document); } [Fact] public void UnderstandsNestedRequiredParent3() { var document = "<div><strong></strong></div>"; EvaluateData(NestedRequiredParent_Descriptors, document); } [Fact] public void UnderstandsNestedRequiredParent4() { var document = "<strong><strong></strong></strong>"; EvaluateData(NestedRequiredParent_Descriptors, document); } [Fact] public void UnderstandsNestedRequiredParent5() { var document = "<p><strong><strong></strong></strong></p>"; EvaluateData(NestedRequiredParent_Descriptors, document); } [Fact] public void UnderstandsTagHelperPrefixAndAllowedChildren() { // Arrange var documentContent = "<th:p><th:strong></th:strong></th:p>"; var descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .AllowChildTag("strong") .Build(), TagHelperDescriptorBuilder .Create("StrongTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("strong")) .Build(), }; // Act & Assert EvaluateData(descriptors, documentContent, tagHelperPrefix: "th:"); } [Fact] public void UnderstandsTagHelperPrefixAndAllowedChildrenAndRequireParent() { // Arrange var documentContent = "<th:p><th:strong></th:strong></th:p>"; var descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .AllowChildTag("strong") .Build(), TagHelperDescriptorBuilder .Create("StrongTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("strong").RequireParentTag("p") ) .Build(), }; // Act & Assert EvaluateData(descriptors, documentContent, tagHelperPrefix: "th:"); } [Fact] public void InvalidStructure_UnderstandsTHPrefixAndAllowedChildrenAndRequireParent() { // Rewrite_InvalidStructure_UnderstandsTagHelperPrefixAndAllowedChildrenAndRequireParent // Arrange var documentContent = "<th:p></th:strong></th:p>"; var descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .AllowChildTag("strong") .Build(), TagHelperDescriptorBuilder .Create("StrongTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("strong").RequireParentTag("p") ) .Build(), }; // Act & Assert EvaluateData(descriptors, documentContent, tagHelperPrefix: "th:"); } [Fact] public void NonTagHelperChild_UnderstandsTagHelperPrefixAndAllowedChildren() { // Arrange var documentContent = "<th:p><strong></strong></th:p>"; var descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .AllowChildTag("strong") .Build(), }; // Act & Assert EvaluateData(descriptors, documentContent, tagHelperPrefix: "th:"); } [Fact] public void DoesNotUnderstandTagHelpersInInvalidHtmlTypedScriptTags1() { var document = "<script type><input /></script>"; RunParseTreeRewriterTest(document, "input"); } [Fact] public void DoesNotUnderstandTagHelpersInInvalidHtmlTypedScriptTags2() { var document = "<script types='text/html'><input /></script>"; RunParseTreeRewriterTest(document, "input"); } [Fact] public void DoesNotUnderstandTagHelpersInInvalidHtmlTypedScriptTags3() { var document = "<script type='text/html invalid'><input /></script>"; RunParseTreeRewriterTest(document, "input"); } [Fact] public void DoesNotUnderstandTagHelpersInInvalidHtmlTypedScriptTags4() { var document = "<script type='text/ng-*' type='text/html'><input /></script>"; RunParseTreeRewriterTest(document, "input"); } [Fact] public void UnderstandsTagHelpersInHtmlTypedScriptTags1() { var document = "<script type='text/html'><input /></script>"; RunParseTreeRewriterTest(document, "p", "input"); } [Fact] public void UnderstandsTagHelpersInHtmlTypedScriptTags2() { var document = "<script id='scriptTag' type='text/html' class='something'><input /></script>"; RunParseTreeRewriterTest(document, "p", "input"); } [Fact] public void UnderstandsTagHelpersInHtmlTypedScriptTags3() { var document = "<script type='text/html'><p><script type='text/html'><input /></script></p></script>"; RunParseTreeRewriterTest(document, "p", "input"); } [Fact] public void UnderstandsTagHelpersInHtmlTypedScriptTags4() { var document = "<script type='text/html'><p><script type='text/ html'><input /></script></p></script>"; RunParseTreeRewriterTest(document, "p", "input"); } [Fact] public void CanHandleInvalidChildrenWithWhitespace() { // Arrange var documentContent = $"<p>{Environment.NewLine} <strong>{Environment.NewLine} Hello" + $"{Environment.NewLine} </strong>{Environment.NewLine}</p>"; var descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .AllowChildTag("br") .Build() }; // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void RecoversWhenRequiredAttributeMismatchAndRestrictedChildren() { // Arrange var documentContent = "<strong required><strong></strong></strong>"; var descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("StrongTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("strong") .RequireAttributeDescriptor(attribute => attribute.Name("required")) ) .AllowChildTag("br") .Build() }; // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void CanHandleMultipleTagHelpersWithAllowedChildren_OneNull() { // Arrange var documentContent = "<p><strong>Hello World</strong><br></p>"; var descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("PTagHelper1", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .AllowChildTag("strong") .AllowChildTag("br") .Build(), TagHelperDescriptorBuilder .Create("PTagHelper2", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .Build(), TagHelperDescriptorBuilder .Create("StrongTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("strong")) .Build(), TagHelperDescriptorBuilder .Create("BRTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("br") .RequireTagStructure(TagStructure.WithoutEndTag) ) .Build(), }; // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void CanHandleMultipleTagHelpersWithAllowedChildren() { // Arrange var documentContent = "<p><strong>Hello World</strong><br></p>"; var descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("PTagHelper1", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .AllowChildTag("strong") .Build(), TagHelperDescriptorBuilder .Create("PTagHelper2", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .AllowChildTag("br") .Build(), TagHelperDescriptorBuilder .Create("StrongTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("strong")) .Build(), TagHelperDescriptorBuilder .Create("BRTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("br") .RequireTagStructure(TagStructure.WithoutEndTag) ) .Build(), }; // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsAllowedChildren1() { // Arrange var documentContent = "<p><br /></p>"; var descriptors = GetAllowedChildrenTagHelperDescriptors(new[] { "br" }); // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsAllowedChildren2() { // Arrange var documentContent = $"<p>{Environment.NewLine}<br />{Environment.NewLine}</p>"; var descriptors = GetAllowedChildrenTagHelperDescriptors(new[] { "br" }); // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsAllowedChildren3() { // Arrange var documentContent = "<p><br></p>"; var descriptors = GetAllowedChildrenTagHelperDescriptors(new[] { "strong" }); // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsAllowedChildren4() { // Arrange var documentContent = "<p>Hello</p>"; var descriptors = GetAllowedChildrenTagHelperDescriptors(new[] { "strong" }); // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsAllowedChildren5() { // Arrange var documentContent = "<p><hr /></p>"; var descriptors = GetAllowedChildrenTagHelperDescriptors(new[] { "br", "strong" }); // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsAllowedChildren6() { // Arrange var documentContent = "<p><br>Hello</p>"; var descriptors = GetAllowedChildrenTagHelperDescriptors(new[] { "strong" }); // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsAllowedChildren7() { // Arrange var documentContent = "<p><strong>Title:</strong><br />Something</p>"; var descriptors = GetAllowedChildrenTagHelperDescriptors(new[] { "strong" }); // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsAllowedChildren8() { // Arrange var documentContent = "<p><strong>Title:</strong><br />Something</p>"; var descriptors = GetAllowedChildrenTagHelperDescriptors(new[] { "strong", "br" }); // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsAllowedChildren9() { // Arrange var documentContent = "<p> <strong>Title:</strong> <br /> Something</p>"; var descriptors = GetAllowedChildrenTagHelperDescriptors(new[] { "strong", "br" }); // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsAllowedChildren10() { // Arrange var documentContent = "<p><strong>Title:<br><em>A Very Cool</em></strong><br />Something</p>"; var descriptors = GetAllowedChildrenTagHelperDescriptors(new[] { "strong" }); // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsAllowedChildren11() { // Arrange var documentContent = "<p><custom>Title:<br><em>A Very Cool</em></custom><br />Something</p>"; var descriptors = GetAllowedChildrenTagHelperDescriptors(new[] { "custom" }); // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsAllowedChildren12() { // Arrange var documentContent = "<p></</p>"; var descriptors = GetAllowedChildrenTagHelperDescriptors(new[] { "custom" }); // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsAllowedChildren13() { // Arrange var documentContent = "<p><</p>"; var descriptors = GetAllowedChildrenTagHelperDescriptors(new[] { "custom" }); // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsAllowedChildren14() { // Arrange var documentContent = "<p><custom><br>:<strong><strong>Hello</strong></strong>:<input></custom></p>"; var descriptors = GetAllowedChildrenTagHelperDescriptors(new[] { "custom", "strong" }); // Act & Assert EvaluateData(descriptors, documentContent); } private TagHelperDescriptor[] GetAllowedChildrenTagHelperDescriptors( string[] allowedChildren ) { var pTagHelperBuilder = TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")); var strongTagHelperBuilder = TagHelperDescriptorBuilder .Create("StrongTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("strong")); foreach (var childTag in allowedChildren) { pTagHelperBuilder.AllowChildTag(childTag); strongTagHelperBuilder.AllowChildTag(childTag); } var descriptors = new TagHelperDescriptor[] { pTagHelperBuilder.Build(), strongTagHelperBuilder.Build(), TagHelperDescriptorBuilder .Create("BRTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("br") .RequireTagStructure(TagStructure.WithoutEndTag) ) .Build(), }; return descriptors; } [Fact] public void AllowsSimpleHtmlCommentsAsChildren() { // Arrange var allowedChildren = new List<string> { "b" }; var literal = "asdf"; var commentOutput = "Hello World"; var document = $"<p><b>{literal}</b><!--{commentOutput}--></p>"; var pTagHelperBuilder = TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")); foreach (var childTag in allowedChildren) { pTagHelperBuilder.AllowChildTag(childTag); } var descriptors = new TagHelperDescriptor[] { pTagHelperBuilder.Build() }; // Act & Assert EvaluateData(descriptors, document); } [Fact] public void DoesntAllowSimpleHtmlCommentsAsChildrenWhenFeatureFlagIsOff() { // Arrange var allowedChildren = new List<string> { "b" }; var comment1 = "Hello"; var document = $"<p><!--{comment1}--></p>"; var pTagHelperBuilder = TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")); foreach (var childTag in allowedChildren) { pTagHelperBuilder.AllowChildTag(childTag); } var descriptors = new TagHelperDescriptor[] { pTagHelperBuilder.Build() }; // Act & Assert EvaluateData( descriptors, document, featureFlags: RazorParserFeatureFlags.Create( RazorLanguageVersion.Version_2_0, FileKinds.Legacy ) ); } [Fact] public void FailsForContentWithCommentsAsChildren() { // Arrange var allowedChildren = new List<string> { "b" }; var comment1 = "Hello"; var literal = "asdf"; var comment2 = "World"; var document = $"<p><!--{comment1}-->{literal}<!--{comment2}--></p>"; var pTagHelperBuilder = TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")); foreach (var childTag in allowedChildren) { pTagHelperBuilder.AllowChildTag(childTag); } var descriptors = new TagHelperDescriptor[] { pTagHelperBuilder.Build() }; // Act & Assert EvaluateData(descriptors, document); } [Fact] public void AllowsRazorCommentsAsChildren() { // Arrange var allowedChildren = new List<string> { "b" }; var literal = "asdf"; var commentOutput = $"@*{literal}*@"; var document = $"<p><b>{literal}</b>{commentOutput}</p>"; var pTagHelperBuilder = TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")); foreach (var childTag in allowedChildren) { pTagHelperBuilder.AllowChildTag(childTag); } var descriptors = new TagHelperDescriptor[] { pTagHelperBuilder.Build() }; // Act & Assert EvaluateData(descriptors, document); } [Fact] public void AllowsRazorMarkupInHtmlComment() { // Arrange var allowedChildren = new List<string> { "b" }; var literal = "asdf"; var part1 = "Hello "; var part2 = "World"; var commentStart = "<!--"; var commentEnd = "-->"; var document = $"<p><b>{literal}</b>{commentStart}{part1}@{part2}{commentEnd}</p>"; var pTagHelperBuilder = TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")); foreach (var childTag in allowedChildren) { pTagHelperBuilder.AllowChildTag(childTag); } var descriptors = new TagHelperDescriptor[] { pTagHelperBuilder.Build() }; // Act & Assert EvaluateData(descriptors, document); } [Fact] public void UnderstandsNullTagNameWithAllowedChildrenForCatchAll() { // Arrange var documentContent = "<p></</p>"; var descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .AllowChildTag("custom") .Build(), TagHelperDescriptorBuilder .Create("CatchAllTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("*")) .Build(), }; // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void UnderstandsNullTagNameWithAllowedChildrenForCatchAllWithPrefix() { // Arrange var documentContent = "<th:p></</th:p>"; var descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("PTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("p")) .AllowChildTag("custom") .Build(), TagHelperDescriptorBuilder .Create("CatchAllTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("*")) .Build(), }; // Act & Assert EvaluateData(descriptors, documentContent, "th:"); } [Fact] public void CanHandleStartTagOnlyTagTagMode() { // Arrange var documentContent = "<input>"; var descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("InputTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("input") .RequireTagStructure(TagStructure.WithoutEndTag) ) .Build() }; // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void CreatesErrorForWithoutEndTagTagStructureForEndTags() { // Arrange var documentContent = "</input>"; var descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("InputTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("input") .RequireTagStructure(TagStructure.WithoutEndTag) ) .Build() }; // Act & Assert EvaluateData(descriptors, documentContent); } [Fact] public void CreatesErrorForInconsistentTagStructures() { // Arrange var documentContent = "<input>"; var descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("InputTagHelper1", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("input") .RequireTagStructure(TagStructure.WithoutEndTag) ) .Build(), TagHelperDescriptorBuilder .Create("InputTagHelper2", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("input") .RequireTagStructure(TagStructure.NormalOrSelfClosing) ) .Build() }; // Act & Assert EvaluateData(descriptors, documentContent); } public static TagHelperDescriptor[] RequiredAttribute_Descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("pTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("p") .RequireAttributeDescriptor(attribute => attribute.Name("class")) ) .Build(), TagHelperDescriptorBuilder .Create("divTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("div") .RequireAttributeDescriptor(attribute => attribute.Name("class")) .RequireAttributeDescriptor(attribute => attribute.Name("style")) ) .Build(), TagHelperDescriptorBuilder .Create("catchAllTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("*") .RequireAttributeDescriptor(attribute => attribute.Name("catchAll")) ) .Build() }; [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly1() { EvaluateData(RequiredAttribute_Descriptors, "<p />"); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly2() { EvaluateData(RequiredAttribute_Descriptors, "<p></p>"); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly3() { EvaluateData(RequiredAttribute_Descriptors, "<div />"); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly4() { EvaluateData(RequiredAttribute_Descriptors, "<div></div>"); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly5() { EvaluateData(RequiredAttribute_Descriptors, "<p class=\"btn\" />"); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly6() { EvaluateData(RequiredAttribute_Descriptors, "<p class=\"@DateTime.Now\" />"); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly7() { EvaluateData(RequiredAttribute_Descriptors, "<p class=\"btn\">words and spaces</p>"); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly8() { EvaluateData( RequiredAttribute_Descriptors, "<p class=\"@DateTime.Now\">words and spaces</p>" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly9() { EvaluateData( RequiredAttribute_Descriptors, "<p class=\"btn\">words<strong>and</strong>spaces</p>" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly10() { EvaluateData(RequiredAttribute_Descriptors, "<strong catchAll=\"hi\" />"); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly11() { EvaluateData(RequiredAttribute_Descriptors, "<strong catchAll=\"@DateTime.Now\" />"); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly12() { EvaluateData( RequiredAttribute_Descriptors, "<strong catchAll=\"hi\">words and spaces</strong>" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly13() { EvaluateData( RequiredAttribute_Descriptors, "<strong catchAll=\"@DateTime.Now\">words and spaces</strong>" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly14() { EvaluateData(RequiredAttribute_Descriptors, "<div class=\"btn\" />"); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly15() { EvaluateData(RequiredAttribute_Descriptors, "<div class=\"btn\"></div>"); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly16() { EvaluateData(RequiredAttribute_Descriptors, "<p notRequired=\"a\" class=\"btn\" />"); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly17() { EvaluateData( RequiredAttribute_Descriptors, "<p notRequired=\"@DateTime.Now\" class=\"btn\" />" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly18() { EvaluateData( RequiredAttribute_Descriptors, "<p notRequired=\"a\" class=\"btn\">words and spaces</p>" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly19() { EvaluateData(RequiredAttribute_Descriptors, "<div style=\"\" class=\"btn\" />"); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly20() { EvaluateData( RequiredAttribute_Descriptors, "<div style=\"@DateTime.Now\" class=\"btn\" />" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly21() { EvaluateData( RequiredAttribute_Descriptors, "<div style=\"\" class=\"btn\">words and spaces</div>" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly22() { EvaluateData( RequiredAttribute_Descriptors, "<div style=\"@DateTime.Now\" class=\"@DateTime.Now\">words and spaces</div>" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly23() { EvaluateData( RequiredAttribute_Descriptors, "<div style=\"\" class=\"btn\">words<strong>and</strong>spaces</div>" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly24() { EvaluateData(RequiredAttribute_Descriptors, "<p class=\"btn\" catchAll=\"hi\" />"); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly25() { EvaluateData( RequiredAttribute_Descriptors, "<p class=\"btn\" catchAll=\"hi\">words and spaces</p>" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly26() { EvaluateData( RequiredAttribute_Descriptors, "<div style=\"\" class=\"btn\" catchAll=\"hi\" />" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly27() { EvaluateData( RequiredAttribute_Descriptors, "<div style=\"\" class=\"btn\" catchAll=\"hi\" >words and spaces</div>" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly28() { EvaluateData( RequiredAttribute_Descriptors, "<div style=\"\" class=\"btn\" catchAll=\"@@hi\" >words and spaces</div>" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly29() { EvaluateData( RequiredAttribute_Descriptors, "<div style=\"@DateTime.Now\" class=\"@DateTime.Now\" catchAll=\"@DateTime.Now\" >words and spaces</div>" ); } [Fact] public void RequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly30() { EvaluateData( RequiredAttribute_Descriptors, "<div style=\"\" class=\"btn\" catchAll=\"hi\" >words<strong>and</strong>spaces</div>" ); } public static TagHelperDescriptor[] NestedRequiredAttribute_Descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("pTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("p") .RequireAttributeDescriptor(attribute => attribute.Name("class")) ) .Build(), TagHelperDescriptorBuilder .Create("catchAllTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("*") .RequireAttributeDescriptor(attribute => attribute.Name("catchAll")) ) .Build(), }; [Fact] public void NestedRequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly1() { EvaluateData(NestedRequiredAttribute_Descriptors, "<p class=\"btn\"><p></p></p>"); } [Fact] public void NestedRequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly2() { EvaluateData( NestedRequiredAttribute_Descriptors, "<strong catchAll=\"hi\"><strong></strong></strong>" ); } [Fact] public void NestedRequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly3() { EvaluateData( NestedRequiredAttribute_Descriptors, "<p class=\"btn\"><strong><p></p></strong></p>" ); } [Fact] public void NestedRequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly4() { EvaluateData( NestedRequiredAttribute_Descriptors, "<strong catchAll=\"hi\"><p><strong></strong></p></strong>" ); } [Fact] public void NestedRequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly5() { EvaluateData( NestedRequiredAttribute_Descriptors, "<p class=\"btn\"><strong catchAll=\"hi\"><p></p></strong></p>" ); } [Fact] public void NestedRequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly6() { EvaluateData( NestedRequiredAttribute_Descriptors, "<strong catchAll=\"hi\"><p class=\"btn\"><strong></strong></p></strong>" ); } [Fact] public void NestedRequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly7() { EvaluateData( NestedRequiredAttribute_Descriptors, "<p class=\"btn\"><p class=\"btn\"><p></p></p></p>" ); } [Fact] public void NestedRequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly8() { EvaluateData( NestedRequiredAttribute_Descriptors, "<strong catchAll=\"hi\"><strong catchAll=\"hi\"><strong></strong></strong></strong>" ); } [Fact] public void NestedRequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly9() { EvaluateData( NestedRequiredAttribute_Descriptors, "<p class=\"btn\"><p><p><p class=\"btn\"><p></p></p></p></p></p>" ); } [Fact] public void NestedRequiredAttributeDescriptorsCreateTagHelperBlocksCorrectly10() { EvaluateData( NestedRequiredAttribute_Descriptors, "<strong catchAll=\"hi\"><strong><strong><strong catchAll=\"hi\"><strong></strong></strong></strong></strong></strong>" ); } public static TagHelperDescriptor[] MalformedRequiredAttribute_Descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("pTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("p") .RequireAttributeDescriptor(attribute => attribute.Name("class")) ) .Build(), }; [Fact] public void RequiredAttributeDescriptorsCreateMalformedTagHelperBlocksCorrectly1() { EvaluateData(MalformedRequiredAttribute_Descriptors, "<p"); } [Fact] public void RequiredAttributeDescriptorsCreateMalformedTagHelperBlocksCorrectly2() { EvaluateData(MalformedRequiredAttribute_Descriptors, "<p class=\"btn\""); } [Fact] public void RequiredAttributeDescriptorsCreateMalformedTagHelperBlocksCorrectly3() { EvaluateData( MalformedRequiredAttribute_Descriptors, "<p notRequired=\"hi\" class=\"btn\"" ); } [Fact] public void RequiredAttributeDescriptorsCreateMalformedTagHelperBlocksCorrectly4() { EvaluateData(MalformedRequiredAttribute_Descriptors, "<p></p"); } [Fact] public void RequiredAttributeDescriptorsCreateMalformedTagHelperBlocksCorrectly5() { EvaluateData(MalformedRequiredAttribute_Descriptors, "<p class=\"btn\"></p"); } [Fact] public void RequiredAttributeDescriptorsCreateMalformedTagHelperBlocksCorrectly6() { EvaluateData( MalformedRequiredAttribute_Descriptors, "<p notRequired=\"hi\" class=\"btn\"></p" ); } [Fact] public void RequiredAttributeDescriptorsCreateMalformedTagHelperBlocksCorrectly7() { EvaluateData(MalformedRequiredAttribute_Descriptors, "<p class=\"btn\" <p>"); } [Fact] public void RequiredAttributeDescriptorsCreateMalformedTagHelperBlocksCorrectly8() { EvaluateData( MalformedRequiredAttribute_Descriptors, "<p notRequired=\"hi\" class=\"btn\" <p>" ); } [Fact] public void RequiredAttributeDescriptorsCreateMalformedTagHelperBlocksCorrectly9() { EvaluateData(MalformedRequiredAttribute_Descriptors, "<p class=\"btn\" </p"); } [Fact] public void RequiredAttributeDescriptorsCreateMalformedTagHelperBlocksCorrectly10() { EvaluateData( MalformedRequiredAttribute_Descriptors, "<p notRequired=\"hi\" class=\"btn\" </p" ); } [Fact] public void RequiredAttributeDescriptorsCreateMalformedTagHelperBlocksCorrectly11() { var document = "<p class='foo'>@if(true){</p>}</p>"; EvaluateData(MalformedRequiredAttribute_Descriptors, document); } public static TagHelperDescriptor[] PrefixedTagHelperColon_Descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("mythTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("myth")) .Build(), TagHelperDescriptorBuilder .Create("mythTagHelper2", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("myth2")) .BoundAttributeDescriptor( attribute => attribute .Name("bound") .PropertyName("Bound") .TypeName(typeof(bool).FullName) ) .Build() }; public static TagHelperDescriptor[] PrefixedTagHelperCatchAll_Descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("mythTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor(rule => rule.RequireTagName("*")) .Build(), }; [Fact] public void AllowsPrefixedTagHelpers1() { EvaluateData(PrefixedTagHelperCatchAll_Descriptors, "<th: />", tagHelperPrefix: "th:"); } [Fact] public void AllowsPrefixedTagHelpers2() { EvaluateData( PrefixedTagHelperCatchAll_Descriptors, "<th:>words and spaces</th:>", tagHelperPrefix: "th:" ); } [Fact] public void AllowsPrefixedTagHelpers3() { EvaluateData(PrefixedTagHelperColon_Descriptors, "<th:myth />", tagHelperPrefix: "th:"); } [Fact] public void AllowsPrefixedTagHelpers4() { EvaluateData( PrefixedTagHelperColon_Descriptors, "<th:myth></th:myth>", tagHelperPrefix: "th:" ); } [Fact] public void AllowsPrefixedTagHelpers5() { EvaluateData( PrefixedTagHelperColon_Descriptors, "<th:myth><th:my2th></th:my2th></th:myth>", tagHelperPrefix: "th:" ); } [Fact] public void AllowsPrefixedTagHelpers6() { EvaluateData( PrefixedTagHelperColon_Descriptors, "<!th:myth />", tagHelperPrefix: "th:" ); } [Fact] public void AllowsPrefixedTagHelpers7() { EvaluateData( PrefixedTagHelperColon_Descriptors, "<!th:myth></!th:myth>", tagHelperPrefix: "th:" ); } [Fact] public void AllowsPrefixedTagHelpers8() { EvaluateData( PrefixedTagHelperColon_Descriptors, "<th:myth class=\"btn\" />", tagHelperPrefix: "th:" ); } [Fact] public void AllowsPrefixedTagHelpers9() { EvaluateData( PrefixedTagHelperColon_Descriptors, "<th:myth2 class=\"btn\" />", tagHelperPrefix: "th:" ); } [Fact] public void AllowsPrefixedTagHelpers10() { EvaluateData( PrefixedTagHelperColon_Descriptors, "<th:myth class=\"btn\">words and spaces</th:myth>", tagHelperPrefix: "th:" ); } [Fact] public void AllowsPrefixedTagHelpers11() { EvaluateData( PrefixedTagHelperColon_Descriptors, "<th:myth2 bound=\"@DateTime.Now\" />", tagHelperPrefix: "th:" ); } [Fact] public void AllowsTHElementOptForCompleteTextTagInCSharpBlock_WithAttrTextTag1() { RunParseTreeRewriterTest("@{<!text class=\"btn\">}", "p", "text"); } [Fact] public void AllowsTHElementOptForCompleteTextTagInCSharpBlock_WithAttrTextTag2() { RunParseTreeRewriterTest("@{<!text class=\"btn\"></!text>}", "p", "text"); } [Fact] public void AllowsTHElementOptForCompleteTextTagInCSharpBlock_WithAttrTextTag3() { RunParseTreeRewriterTest( "@{<!text class=\"btn\">words with spaces</!text>}", "p", "text" ); } [Fact] public void AllowsTHElementOptForCompleteTextTagInCSharpBlock_WithAttrTextTag4() { RunParseTreeRewriterTest( "@{<!text class='btn1 btn2' class2=btn></!text>}", "p", "text" ); } [Fact] public void AllowsTHElementOptForCompleteTextTagInCSharpBlock_WithAttrTextTag5() { RunParseTreeRewriterTest( "@{<!text class='btn1 @DateTime.Now btn2'></!text>}", "p", "text" ); } [Fact] public void AllowsTHElementOptForCompleteTextTagInCSharpBlock_WithBlockTextTag1() { RunParseTreeRewriterTest("@{<!text>}", "p", "text"); } [Fact] public void AllowsTHElementOptForCompleteTextTagInCSharpBlock_WithBlockTextTag2() { RunParseTreeRewriterTest("@{</!text>}", "p", "text"); } [Fact] public void AllowsTHElementOptForCompleteTextTagInCSharpBlock_WithBlockTextTag3() { RunParseTreeRewriterTest("@{<!text></!text>}", "p", "text"); } [Fact] public void AllowsTHElementOptForCompleteTextTagInCSharpBlock_WithBlockTextTag4() { RunParseTreeRewriterTest("@{<!text>words and spaces</!text>}", "p", "text"); } [Fact] public void AllowsTHElementOptForCompleteTextTagInCSharpBlock_WithBlockTextTag5() { RunParseTreeRewriterTest("@{<!text></text>}", "p", "text"); } [Fact] public void AllowsTHElementOptForCompleteTextTagInCSharpBlock_WithBlockTextTag6() { RunParseTreeRewriterTest("@{<text></!text>}", "p", "text"); } [Fact] public void AllowsTHElementOptForCompleteTextTagInCSharpBlock_WithBlockTextTag7() { RunParseTreeRewriterTest("@{<!text><text></text></!text>}", "p", "text"); } [Fact] public void AllowsTHElementOptForCompleteTextTagInCSharpBlock_WithBlockTextTag8() { RunParseTreeRewriterTest("@{<text><!text></!text>}", "p", "text"); } [Fact] public void AllowsTHElementOptForCompleteTextTagInCSharpBlock_WithBlockTextTag9() { RunParseTreeRewriterTest("@{<!text></!text></text>}", "p", "text"); } [Fact] public void AllowsTagHelperElementOptForIncompleteTextTagInCSharpBlock1() { RunParseTreeRewriterTest("@{<!text}", "text"); } [Fact] public void AllowsTagHelperElementOptForIncompleteTextTagInCSharpBlock2() { RunParseTreeRewriterTest("@{<!text /}", "text"); } [Fact] public void AllowsTagHelperElementOptForIncompleteTextTagInCSharpBlock3() { RunParseTreeRewriterTest("@{<!text class=}", "text"); } [Fact] public void AllowsTagHelperElementOptForIncompleteTextTagInCSharpBlock4() { RunParseTreeRewriterTest("@{<!text class=\"btn}", "text"); } [Fact] public void AllowsTagHelperElementOptForIncompleteTextTagInCSharpBlock5() { RunParseTreeRewriterTest("@{<!text class=\"btn\"}", "text"); } [Fact] public void AllowsTagHelperElementOptForIncompleteTextTagInCSharpBlock6() { RunParseTreeRewriterTest("@{<!text class=\"btn\" /}", "text"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTMLInCSharpBlock1() { RunParseTreeRewriterTest("@{<!}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTMLInCSharpBlock2() { RunParseTreeRewriterTest("@{<!p}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTMLInCSharpBlock3() { RunParseTreeRewriterTest("@{<!p /}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTMLInCSharpBlock4() { RunParseTreeRewriterTest("@{<!p class=}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTMLInCSharpBlock5() { RunParseTreeRewriterTest("@{<!p class=\"btn}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTMLInCSharpBlock6() { RunParseTreeRewriterTest("@{<!p class=\"btn@@}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTMLInCSharpBlock7() { RunParseTreeRewriterTest("@{<!p class=\"btn\"}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTMLInCSharpBlock8() { RunParseTreeRewriterTest("@{<!p class=\"btn\" /}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTML1() { RunParseTreeRewriterTest("<!", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTML2() { RunParseTreeRewriterTest("<!p", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTML3() { RunParseTreeRewriterTest("<!p /", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTML4() { RunParseTreeRewriterTest("<!p class=", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTML5() { RunParseTreeRewriterTest("<!p class=\"btn", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTML6() { RunParseTreeRewriterTest("<!p class=\"btn\"", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptForIncompleteHTML7() { RunParseTreeRewriterTest("<!p class=\"btn\" /", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithBlockData1() { RunParseTreeRewriterTest("@{<!p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithBlockData2() { RunParseTreeRewriterTest("@{</!p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithBlockData3() { RunParseTreeRewriterTest("@{<!p></!p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithBlockData4() { RunParseTreeRewriterTest("@{<!p>words and spaces</!p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithBlockData5() { RunParseTreeRewriterTest("@{<!p></p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithBlockData6() { RunParseTreeRewriterTest("@{<p></!p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithBlockData7() { RunParseTreeRewriterTest("@{<p><!p></!p></p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithBlockData8() { RunParseTreeRewriterTest("@{<p><!p></!p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithBlockData9() { RunParseTreeRewriterTest("@{<!p></!p></p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithBlockData10() { RunParseTreeRewriterTest("@{<strong></!p></strong>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithBlockData11() { RunParseTreeRewriterTest("@{<strong></strong><!p></!p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithBlockData12() { RunParseTreeRewriterTest("@{<p><strong></!strong><!p></strong></!p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithAttributeData1() { RunParseTreeRewriterTest("@{<!p class=\"btn\">}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithAttributeData2() { RunParseTreeRewriterTest("@{<!p class=\"btn\"></!p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithAttributeData3() { RunParseTreeRewriterTest("@{<!p class=\"btn\">words with spaces</!p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithAttributeData4() { RunParseTreeRewriterTest("@{<!p class='btn1 btn2' class2=btn></!p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutCSharp_WithAttributeData5() { RunParseTreeRewriterTest("@{<!p class='btn1 @DateTime.Now btn2'></!p>}", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithBlockData1() { RunParseTreeRewriterTest("<!p>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithBlockData2() { RunParseTreeRewriterTest("</!p>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithBlockData3() { RunParseTreeRewriterTest("<!p></!p>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithBlockData4() { RunParseTreeRewriterTest("<!p>words and spaces</!p>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithBlockData5() { RunParseTreeRewriterTest("<!p></p>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithBlockData6() { RunParseTreeRewriterTest("<p></!p>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithBlockData7() { RunParseTreeRewriterTest("<p><!p></!p></p>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithBlockData8() { RunParseTreeRewriterTest("<p><!p></!p>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithBlockData9() { RunParseTreeRewriterTest("<!p></!p></p>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithBlockData10() { RunParseTreeRewriterTest("<strong></!p></strong>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithBlockData11() { RunParseTreeRewriterTest("<strong></strong><!p></!p>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithBlockData12() { RunParseTreeRewriterTest("<p><strong></!strong><!p></strong></!p>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithAttributeData1() { RunParseTreeRewriterTest("<!p class=\"btn\">", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithAttributeData2() { RunParseTreeRewriterTest("<!p class=\"btn\"></!p>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithAttributeData3() { RunParseTreeRewriterTest("<!p class=\"btn\">words and spaces</!p>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithAttributeData4() { RunParseTreeRewriterTest("<!p class='btn1 btn2' class2=btn></!p>", "strong", "p"); } [Fact] public void AllowsTagHelperElementOptOutHTML_WithAttributeData5() { RunParseTreeRewriterTest("<!p class='btn1 @DateTime.Now btn2'></!p>", "strong", "p"); } [Fact] public void DoesNotRewriteTextTagTransitionTagHelpers1() { RunParseTreeRewriterTest("<text>Hello World</text>", "p", "text"); } [Fact] public void DoesNotRewriteTextTagTransitionTagHelpers2() { RunParseTreeRewriterTest("@{<text>Hello World</text>}", "p", "text"); } [Fact] public void DoesNotRewriteTextTagTransitionTagHelpers3() { RunParseTreeRewriterTest("@{<text><p>Hello World</p></text>}", "p", "text"); } [Fact] public void DoesNotRewriteTextTagTransitionTagHelpers4() { RunParseTreeRewriterTest("@{<p><text>Hello World</text></p>}", "p", "text"); } [Fact] public void DoesNotRewriteSpecialTagTagHelpers1() { RunParseTreeRewriterTest( "<foo><!-- Hello World --></foo>", "!--", "?xml", "![CDATA[", "!DOCTYPE" ); } [Fact] public void DoesNotRewriteSpecialTagTagHelpers2() { RunParseTreeRewriterTest( "<foo><!-- @foo --></foo>", "!--", "?xml", "![CDATA[", "!DOCTYPE" ); } [Fact] public void DoesNotRewriteSpecialTagTagHelpers3() { RunParseTreeRewriterTest( "<foo><?xml Hello World ?></foo>", "!--", "?xml", "![CDATA[", "!DOCTYPE" ); } [Fact] public void DoesNotRewriteSpecialTagTagHelpers4() { RunParseTreeRewriterTest( "<foo><?xml @foo ?></foo>", "!--", "?xml", "![CDATA[", "!DOCTYPE" ); } [Fact] public void DoesNotRewriteSpecialTagTagHelpers5() { RunParseTreeRewriterTest( "<foo><!DOCTYPE @foo ></foo>", "!--", "?xml", "![CDATA[", "!DOCTYPE" ); } [Fact] public void DoesNotRewriteSpecialTagTagHelpers6() { RunParseTreeRewriterTest( "<foo><!DOCTYPE hello=\"world\" ></foo>", "!--", "?xml", "![CDATA[", "!DOCTYPE" ); } [Fact] public void DoesNotRewriteSpecialTagTagHelpers7() { RunParseTreeRewriterTest( "<foo><![CDATA[ Hello World ]]></foo>", "!--", "?xml", "![CDATA[", "!DOCTYPE" ); } [Fact] public void DoesNotRewriteSpecialTagTagHelpers8() { RunParseTreeRewriterTest( "<foo><![CDATA[ @foo ]]></foo>", "!--", "?xml", "![CDATA[", "!DOCTYPE" ); } [Fact] public void RewritesNestedTagHelperTagBlocks1() { RunParseTreeRewriterTest("<p><div></div></p>", "p", "div"); } [Fact] public void RewritesNestedTagHelperTagBlocks2() { RunParseTreeRewriterTest("<p>Hello World <div></div></p>", "p", "div"); } [Fact] public void RewritesNestedTagHelperTagBlocks3() { RunParseTreeRewriterTest("<p>Hel<p>lo</p></p> <p><div>World</div></p>", "p", "div"); } [Fact] public void RewritesNestedTagHelperTagBlocks4() { RunParseTreeRewriterTest( "<p>Hel<strong>lo</strong></p> <p><span>World</span></p>", "p", "div" ); } [Fact] public void HandlesMalformedNestedNonTagHelperTags_Correctly() { RunParseTreeRewriterTest("<div>@{</div>}"); } [Fact] public void HandlesNonTagHelperStartAndEndVoidTags_Correctly() { RunParseTreeRewriterTest("<input>Foo</input>"); } public static TagHelperDescriptor[] CaseSensitive_Descriptors = new TagHelperDescriptor[] { TagHelperDescriptorBuilder .Create("pTagHelper", "SomeAssembly") .SetCaseSensitive() .BoundAttributeDescriptor( attribute => attribute .Name("bound") .PropertyName("Bound") .TypeName(typeof(bool).FullName) ) .TagMatchingRuleDescriptor( rule => rule.RequireTagName("p") .RequireAttributeDescriptor(attribute => attribute.Name("class")) ) .Build(), TagHelperDescriptorBuilder .Create("catchAllTagHelper", "SomeAssembly") .TagMatchingRuleDescriptor( rule => rule.RequireTagName("*") .RequireAttributeDescriptor(attribute => attribute.Name("catchAll")) ) .Build(), }; [Fact] public void HandlesCaseSensitiveTagHelpersCorrectly1() { EvaluateData(CaseSensitive_Descriptors, "<p class='foo' catchAll></p>"); } [Fact] public void HandlesCaseSensitiveTagHelpersCorrectly2() { EvaluateData(CaseSensitive_Descriptors, "<p CLASS='foo' CATCHAll></p>"); } [Fact] public void HandlesCaseSensitiveTagHelpersCorrectly3() { EvaluateData(CaseSensitive_Descriptors, "<P class='foo' CATCHAll></P>"); } [Fact] public void HandlesCaseSensitiveTagHelpersCorrectly4() { EvaluateData(CaseSensitive_Descriptors, "<P class='foo'></P>"); } [Fact] public void HandlesCaseSensitiveTagHelpersCorrectly5() { EvaluateData(CaseSensitive_Descriptors, "<p Class='foo'></p>"); } } }
34.337267
135
0.529658
[ "Apache-2.0" ]
belav/aspnetcore
src/Razor/Microsoft.AspNetCore.Razor.Language/test/Legacy/TagHelperParseTreeRewriterTest.cs
75,645
C#
/* * THIS FILE WAS GENERATED BY PLOTLY.BLAZOR.GENERATOR */ using System; using System.Collections.Generic; using System.Diagnostics.CodeAnalysis; using System.IO; using System.Linq; using System.Runtime.Serialization.Formatters.Binary; using System.Text.Json.Serialization; namespace Plotly.Blazor.LayoutLib.PolarLib { /// <summary> /// The RadialAxis class. /// </summary> [System.CodeDom.Compiler.GeneratedCode("Plotly.Blazor.Generator", "1.0.0.0")] [Serializable] public class RadialAxis : IEquatable<RadialAxis> { /// <summary> /// A single toggle to hide the axis while preserving interaction like dragging. /// Default is true when a cheater plot is present on the axis, otherwise false /// </summary> [JsonPropertyName(@"visible")] public bool? Visible { get; set;} /// <summary> /// Sets the axis type. By default, plotly attempts to determined the axis type /// by looking into the data of the traces that referenced the axis in question. /// </summary> [JsonPropertyName(@"type")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.TypeEnum? Type { get; set;} /// <summary> /// Using <c>strict</c> a numeric string in trace data is not converted to a /// number. Using &#39;convert types&#39; a numeric string in trace data may /// be treated as a number during automatic axis <c>type</c> detection. Defaults /// to layout.autotypenumbers. /// </summary> [JsonPropertyName(@"autotypenumbers")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.AutoTypeNumbersEnum? AutoTypeNumbers { get; set;} /// <summary> /// Determines whether or not the range of this axis is computed in relation /// to the input data. See <c>rangemode</c> for more info. If <c>range</c> is /// provided, then <c>autorange</c> is set to <c>false</c>. /// </summary> [JsonPropertyName(@"autorange")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.AutoRangeEnum? AutoRange { get; set;} /// <summary> /// If <c>tozero</c>`, the range extends to 0, regardless of the input data /// If <c>nonnegative</c>, the range is non-negative, regardless of the input /// data. If <c>normal</c>, the range is computed in relation to the extrema /// of the input data (same behavior as for cartesian axes). /// </summary> [JsonPropertyName(@"rangemode")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.RangeModeEnum? RangeMode { get; set;} /// <summary> /// Sets the range of this axis. If the axis <c>type</c> is <c>log</c>, then /// you must take the log of your desired range (e.g. to set the range from /// 1 to 100, set the range from 0 to 2). If the axis <c>type</c> is <c>date</c>, /// it should be date strings, like date data, though Date objects and unix /// milliseconds will be accepted and converted to strings. If the axis <c>type</c> /// is <c>category</c>, it should be numbers, using the scale where each category /// is assigned a serial number from zero in the order it appears. /// </summary> [JsonPropertyName(@"range")] public IList<object> Range { get; set;} /// <summary> /// Specifies the ordering logic for the case of categorical variables. By default, /// plotly uses <c>trace</c>, which specifies the order that is present in the /// data supplied. Set <c>categoryorder</c> to &#39;category ascending&#39; /// or &#39;category descending&#39; if order should be determined by the alphanumerical /// order of the category names. Set <c>categoryorder</c> to <c>array</c> to /// derive the ordering from the attribute <c>categoryarray</c>. If a category /// is not found in the <c>categoryarray</c> array, the sorting behavior for /// that attribute will be identical to the <c>trace</c> mode. The unspecified /// categories will follow the categories in <c>categoryarray</c>. Set <c>categoryorder</c> /// to &#39;total ascending&#39; or &#39;total descending&#39; if order should /// be determined by the numerical order of the values. Similarly, the order /// can be determined by the min, max, sum, mean or median of all the values. /// </summary> [JsonPropertyName(@"categoryorder")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.CategoryOrderEnum? CategoryOrder { get; set;} /// <summary> /// Sets the order in which categories on this axis appear. Only has an effect /// if <c>categoryorder</c> is set to <c>array</c>. Used with <c>categoryorder</c>. /// </summary> [JsonPropertyName(@"categoryarray")] public IList<object> CategoryArray { get; set;} /// <summary> /// Sets the angle (in degrees) from which the radial axis is drawn. Note that /// by default, radial axis line on the theta=0 line corresponds to a line pointing /// right (like what mathematicians prefer). Defaults to the first <c>polar.sector</c> /// angle. /// </summary> [JsonPropertyName(@"angle")] public decimal? Angle { get; set;} /// <summary> /// Determines on which side of radial axis line the tick and tick labels appear. /// </summary> [JsonPropertyName(@"side")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.SideEnum? Side { get; set;} /// <summary> /// Gets or sets the Title. /// </summary> [JsonPropertyName(@"title")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.Title Title { get; set;} /// <summary> /// Sets the hover text formatting rule using d3 formatting mini-languages which /// are very similar to those in Python. For numbers, see: https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md#d3_format. /// And for dates see: https://github.com/d3/d3-time-format#locale_format. We /// add two items to d3&#39;s date formatter: <c>%h</c> for half of the year /// as a decimal number as well as <c>%{n}f</c> for fractional seconds with /// n digits. For example, &#39;2016-10-13 09:15:23.456&#39; with tickformat /// <c>%H~%M~%S.%2f</c> would display <c>09~15~23.46</c> /// </summary> [JsonPropertyName(@"hoverformat")] public string HoverFormat { get; set;} /// <summary> /// Controls persistence of user-driven changes in axis <c>range</c>, <c>autorange</c>, /// <c>angle</c>, and <c>title</c> if in &#39;editable: true&#39; configuration. /// Defaults to <c>polar&lt;N&gt;.uirevision</c>. /// </summary> [JsonPropertyName(@"uirevision")] public object UiRevision { get; set;} /// <summary> /// Sets default for all colors associated with this axis all at once: line, /// font, tick, and grid colors. Grid color is lightened by blending this with /// the plot background Individual pieces can override this. /// </summary> [JsonPropertyName(@"color")] public object Color { get; set;} /// <summary> /// Determines whether or not a line bounding this axis is drawn. /// </summary> [JsonPropertyName(@"showline")] public bool? ShowLine { get; set;} /// <summary> /// Sets the axis line color. /// </summary> [JsonPropertyName(@"linecolor")] public object LineColor { get; set;} /// <summary> /// Sets the width (in px) of the axis line. /// </summary> [JsonPropertyName(@"linewidth")] public decimal? LineWidth { get; set;} /// <summary> /// Determines whether or not grid lines are drawn. If <c>true</c>, the grid /// lines are drawn at every tick mark. /// </summary> [JsonPropertyName(@"showgrid")] public bool? ShowGrid { get; set;} /// <summary> /// Sets the color of the grid lines. /// </summary> [JsonPropertyName(@"gridcolor")] public object GridColor { get; set;} /// <summary> /// Sets the width (in px) of the grid lines. /// </summary> [JsonPropertyName(@"gridwidth")] public decimal? GridWidth { get; set;} /// <summary> /// Sets the tick mode for this axis. If <c>auto</c>, the number of ticks is /// set via <c>nticks</c>. If <c>linear</c>, the placement of the ticks is determined /// by a starting position <c>tick0</c> and a tick step <c>dtick</c> (<c>linear</c> /// is the default value if <c>tick0</c> and <c>dtick</c> are provided). If /// <c>array</c>, the placement of the ticks is set via <c>tickvals</c> and /// the tick text is <c>ticktext</c>. (<c>array</c> is the default value if /// <c>tickvals</c> is provided). /// </summary> [JsonPropertyName(@"tickmode")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.TickModeEnum? TickMode { get; set;} /// <summary> /// Specifies the maximum number of ticks for the particular axis. The actual /// number of ticks will be chosen automatically to be less than or equal to /// <c>nticks</c>. Has an effect only if <c>tickmode</c> is set to <c>auto</c>. /// </summary> [JsonPropertyName(@"nticks")] public int? NTicks { get; set;} /// <summary> /// Sets the placement of the first tick on this axis. Use with <c>dtick</c>. /// If the axis <c>type</c> is <c>log</c>, then you must take the log of your /// starting tick (e.g. to set the starting tick to 100, set the <c>tick0</c> /// to 2) except when <c>dtick</c>=<c>L&lt;f&gt;</c> (see <c>dtick</c> for more /// info). If the axis <c>type</c> is <c>date</c>, it should be a date string, /// like date data. If the axis <c>type</c> is <c>category</c>, it should be /// a number, using the scale where each category is assigned a serial number /// from zero in the order it appears. /// </summary> [JsonPropertyName(@"tick0")] public object Tick0 { get; set;} /// <summary> /// Sets the step in-between ticks on this axis. Use with <c>tick0</c>. Must /// be a positive number, or special strings available to <c>log</c> and <c>date</c> /// axes. If the axis <c>type</c> is <c>log</c>, then ticks are set every 10^(n*dtick) /// where n is the tick number. For example, to set a tick mark at 1, 10, 100, /// 1000, ... set dtick to 1. To set tick marks at 1, 100, 10000, ... set dtick /// to 2. To set tick marks at 1, 5, 25, 125, 625, 3125, ... set dtick to log_10(5), /// or 0.69897000433. <c>log</c> has several special values; <c>L&lt;f&gt;</c>, /// where <c>f</c> is a positive number, gives ticks linearly spaced in value /// (but not position). For example <c>tick0</c> = 0.1, <c>dtick</c> = <c>L0.5</c> /// will put ticks at 0.1, 0.6, 1.1, 1.6 etc. To show powers of 10 plus small /// digits between, use <c>D1</c> (all digits) or <c>D2</c> (only 2 and 5). /// <c>tick0</c> is ignored for <c>D1</c> and <c>D2</c>. If the axis <c>type</c> /// is <c>date</c>, then you must convert the time to milliseconds. For example, /// to set the interval between ticks to one day, set <c>dtick</c> to 86400000.0. /// <c>date</c> also has special values <c>M&lt;n&gt;</c> gives ticks spaced /// by a number of months. <c>n</c> must be a positive integer. To set ticks /// on the 15th of every third month, set <c>tick0</c> to <c>2000-01-15</c> /// and <c>dtick</c> to <c>M3</c>. To set ticks every 4 years, set <c>dtick</c> /// to <c>M48</c> /// </summary> [JsonPropertyName(@"dtick")] public object DTick { get; set;} /// <summary> /// Sets the values at which ticks on this axis appear. Only has an effect if /// <c>tickmode</c> is set to <c>array</c>. Used with <c>ticktext</c>. /// </summary> [JsonPropertyName(@"tickvals")] public IList<object> TickVals { get; set;} /// <summary> /// Sets the text displayed at the ticks position via <c>tickvals</c>. Only /// has an effect if <c>tickmode</c> is set to <c>array</c>. Used with <c>tickvals</c>. /// </summary> [JsonPropertyName(@"ticktext")] public IList<object> TickText { get; set;} /// <summary> /// Determines whether ticks are drawn or not. If **, this axis&#39; ticks are /// not drawn. If <c>outside</c> (<c>inside</c>), this axis&#39; are drawn outside /// (inside) the axis lines. /// </summary> [JsonPropertyName(@"ticks")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.TicksEnum? Ticks { get; set;} /// <summary> /// Sets the tick length (in px). /// </summary> [JsonPropertyName(@"ticklen")] public decimal? TickLen { get; set;} /// <summary> /// Sets the tick width (in px). /// </summary> [JsonPropertyName(@"tickwidth")] public decimal? TickWidth { get; set;} /// <summary> /// Sets the tick color. /// </summary> [JsonPropertyName(@"tickcolor")] public object TickColor { get; set;} /// <summary> /// Determines whether or not the tick labels are drawn. /// </summary> [JsonPropertyName(@"showticklabels")] public bool? ShowTickLabels { get; set;} /// <summary> /// If <c>all</c>, all tick labels are displayed with a prefix. If <c>first</c>, /// only the first tick is displayed with a prefix. If <c>last</c>, only the /// last tick is displayed with a suffix. If <c>none</c>, tick prefixes are /// hidden. /// </summary> [JsonPropertyName(@"showtickprefix")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.ShowTickPrefixEnum? ShowTickPrefix { get; set;} /// <summary> /// Sets a tick label prefix. /// </summary> [JsonPropertyName(@"tickprefix")] public string TickPrefix { get; set;} /// <summary> /// Same as <c>showtickprefix</c> but for tick suffixes. /// </summary> [JsonPropertyName(@"showticksuffix")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.ShowTickSuffixEnum? ShowTickSuffix { get; set;} /// <summary> /// Sets a tick label suffix. /// </summary> [JsonPropertyName(@"ticksuffix")] public string TickSuffix { get; set;} /// <summary> /// If <c>all</c>, all exponents are shown besides their significands. If <c>first</c>, /// only the exponent of the first tick is shown. If <c>last</c>, only the exponent /// of the last tick is shown. If <c>none</c>, no exponents appear. /// </summary> [JsonPropertyName(@"showexponent")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.ShowExponentEnum? ShowExponent { get; set;} /// <summary> /// Determines a formatting rule for the tick exponents. For example, consider /// the number 1,000,000,000. If <c>none</c>, it appears as 1,000,000,000. If /// <c>e</c>, 1e+9. If <c>E</c>, 1E+9. If <c>power</c>, 1x10^9 (with 9 in a /// super script). If <c>SI</c>, 1G. If <c>B</c>, 1B. /// </summary> [JsonPropertyName(@"exponentformat")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.ExponentFormatEnum? ExponentFormat { get; set;} /// <summary> /// Hide SI prefix for 10^n if |n| is below this number. This only has an effect /// when <c>tickformat</c> is <c>SI</c> or <c>B</c>. /// </summary> [JsonPropertyName(@"minexponent")] public decimal? MinExponent { get; set;} /// <summary> /// If <c>true</c>, even 4-digit integers are separated /// </summary> [JsonPropertyName(@"separatethousands")] public bool? SeparateThousands { get; set;} /// <summary> /// Sets the tick font. /// </summary> [JsonPropertyName(@"tickfont")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.TickFont TickFont { get; set;} /// <summary> /// Sets the angle of the tick labels with respect to the horizontal. For example, /// a <c>tickangle</c> of -90 draws the tick labels vertically. /// </summary> [JsonPropertyName(@"tickangle")] public decimal? TickAngle { get; set;} /// <summary> /// Sets the tick label formatting rule using d3 formatting mini-languages which /// are very similar to those in Python. For numbers, see: https://github.com/d3/d3-3.x-api-reference/blob/master/Formatting.md#d3_format. /// And for dates see: https://github.com/d3/d3-time-format#locale_format. We /// add two items to d3&#39;s date formatter: <c>%h</c> for half of the year /// as a decimal number as well as <c>%{n}f</c> for fractional seconds with /// n digits. For example, &#39;2016-10-13 09:15:23.456&#39; with tickformat /// <c>%H~%M~%S.%2f</c> would display <c>09~15~23.46</c> /// </summary> [JsonPropertyName(@"tickformat")] public string TickFormat { get; set;} /// <summary> /// Gets or sets the TickFormatStops. /// </summary> [JsonPropertyName(@"tickformatstops")] public IList<Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.TickFormatStop> TickFormatStops { get; set;} /// <summary> /// Sets the layer on which this axis is displayed. If &#39;above traces&#39;, /// this axis is displayed above all the subplot&#39;s traces If &#39;below /// traces&#39;, this axis is displayed below all the subplot&#39;s traces, /// but above the grid lines. Useful when used together with scatter-like traces /// with <c>cliponaxis</c> set to <c>false</c> to show markers and/or text nodes /// above this axis. /// </summary> [JsonPropertyName(@"layer")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.LayerEnum? Layer { get; set;} /// <summary> /// Sets the calendar system to use for <c>range</c> and <c>tick0</c> if this /// is a date axis. This does not set the calendar for interpreting data on /// this axis, that&#39;s specified in the trace or via the global <c>layout.calendar</c> /// </summary> [JsonPropertyName(@"calendar")] public Plotly.Blazor.LayoutLib.PolarLib.RadialAxisLib.CalendarEnum? Calendar { get; set;} /// <summary> /// Sets the source reference on Chart Studio Cloud for categoryarray . /// </summary> [JsonPropertyName(@"categoryarraysrc")] public string CategoryArraySrc { get; set;} /// <summary> /// Sets the source reference on Chart Studio Cloud for tickvals . /// </summary> [JsonPropertyName(@"tickvalssrc")] public string TickValsSrc { get; set;} /// <summary> /// Sets the source reference on Chart Studio Cloud for ticktext . /// </summary> [JsonPropertyName(@"ticktextsrc")] public string TickTextSrc { get; set;} /// <inheritdoc /> public override bool Equals(object obj) { if (!(obj is RadialAxis other)) return false; return ReferenceEquals(this, obj) || Equals(other); } /// <inheritdoc /> public bool Equals([AllowNull] RadialAxis other) { if (other == null) return false; if (ReferenceEquals(this, other)) return true; return ( Visible == other.Visible || Visible != null && Visible.Equals(other.Visible) ) && ( Type == other.Type || Type != null && Type.Equals(other.Type) ) && ( AutoTypeNumbers == other.AutoTypeNumbers || AutoTypeNumbers != null && AutoTypeNumbers.Equals(other.AutoTypeNumbers) ) && ( AutoRange == other.AutoRange || AutoRange != null && AutoRange.Equals(other.AutoRange) ) && ( RangeMode == other.RangeMode || RangeMode != null && RangeMode.Equals(other.RangeMode) ) && ( Equals(Range, other.Range) || Range != null && other.Range != null && Range.SequenceEqual(other.Range) ) && ( CategoryOrder == other.CategoryOrder || CategoryOrder != null && CategoryOrder.Equals(other.CategoryOrder) ) && ( Equals(CategoryArray, other.CategoryArray) || CategoryArray != null && other.CategoryArray != null && CategoryArray.SequenceEqual(other.CategoryArray) ) && ( Angle == other.Angle || Angle != null && Angle.Equals(other.Angle) ) && ( Side == other.Side || Side != null && Side.Equals(other.Side) ) && ( Title == other.Title || Title != null && Title.Equals(other.Title) ) && ( HoverFormat == other.HoverFormat || HoverFormat != null && HoverFormat.Equals(other.HoverFormat) ) && ( UiRevision == other.UiRevision || UiRevision != null && UiRevision.Equals(other.UiRevision) ) && ( Color == other.Color || Color != null && Color.Equals(other.Color) ) && ( ShowLine == other.ShowLine || ShowLine != null && ShowLine.Equals(other.ShowLine) ) && ( LineColor == other.LineColor || LineColor != null && LineColor.Equals(other.LineColor) ) && ( LineWidth == other.LineWidth || LineWidth != null && LineWidth.Equals(other.LineWidth) ) && ( ShowGrid == other.ShowGrid || ShowGrid != null && ShowGrid.Equals(other.ShowGrid) ) && ( GridColor == other.GridColor || GridColor != null && GridColor.Equals(other.GridColor) ) && ( GridWidth == other.GridWidth || GridWidth != null && GridWidth.Equals(other.GridWidth) ) && ( TickMode == other.TickMode || TickMode != null && TickMode.Equals(other.TickMode) ) && ( NTicks == other.NTicks || NTicks != null && NTicks.Equals(other.NTicks) ) && ( Tick0 == other.Tick0 || Tick0 != null && Tick0.Equals(other.Tick0) ) && ( DTick == other.DTick || DTick != null && DTick.Equals(other.DTick) ) && ( Equals(TickVals, other.TickVals) || TickVals != null && other.TickVals != null && TickVals.SequenceEqual(other.TickVals) ) && ( Equals(TickText, other.TickText) || TickText != null && other.TickText != null && TickText.SequenceEqual(other.TickText) ) && ( Ticks == other.Ticks || Ticks != null && Ticks.Equals(other.Ticks) ) && ( TickLen == other.TickLen || TickLen != null && TickLen.Equals(other.TickLen) ) && ( TickWidth == other.TickWidth || TickWidth != null && TickWidth.Equals(other.TickWidth) ) && ( TickColor == other.TickColor || TickColor != null && TickColor.Equals(other.TickColor) ) && ( ShowTickLabels == other.ShowTickLabels || ShowTickLabels != null && ShowTickLabels.Equals(other.ShowTickLabels) ) && ( ShowTickPrefix == other.ShowTickPrefix || ShowTickPrefix != null && ShowTickPrefix.Equals(other.ShowTickPrefix) ) && ( TickPrefix == other.TickPrefix || TickPrefix != null && TickPrefix.Equals(other.TickPrefix) ) && ( ShowTickSuffix == other.ShowTickSuffix || ShowTickSuffix != null && ShowTickSuffix.Equals(other.ShowTickSuffix) ) && ( TickSuffix == other.TickSuffix || TickSuffix != null && TickSuffix.Equals(other.TickSuffix) ) && ( ShowExponent == other.ShowExponent || ShowExponent != null && ShowExponent.Equals(other.ShowExponent) ) && ( ExponentFormat == other.ExponentFormat || ExponentFormat != null && ExponentFormat.Equals(other.ExponentFormat) ) && ( MinExponent == other.MinExponent || MinExponent != null && MinExponent.Equals(other.MinExponent) ) && ( SeparateThousands == other.SeparateThousands || SeparateThousands != null && SeparateThousands.Equals(other.SeparateThousands) ) && ( TickFont == other.TickFont || TickFont != null && TickFont.Equals(other.TickFont) ) && ( TickAngle == other.TickAngle || TickAngle != null && TickAngle.Equals(other.TickAngle) ) && ( TickFormat == other.TickFormat || TickFormat != null && TickFormat.Equals(other.TickFormat) ) && ( Equals(TickFormatStops, other.TickFormatStops) || TickFormatStops != null && other.TickFormatStops != null && TickFormatStops.SequenceEqual(other.TickFormatStops) ) && ( Layer == other.Layer || Layer != null && Layer.Equals(other.Layer) ) && ( Calendar == other.Calendar || Calendar != null && Calendar.Equals(other.Calendar) ) && ( CategoryArraySrc == other.CategoryArraySrc || CategoryArraySrc != null && CategoryArraySrc.Equals(other.CategoryArraySrc) ) && ( TickValsSrc == other.TickValsSrc || TickValsSrc != null && TickValsSrc.Equals(other.TickValsSrc) ) && ( TickTextSrc == other.TickTextSrc || TickTextSrc != null && TickTextSrc.Equals(other.TickTextSrc) ); } /// <inheritdoc /> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { var hashCode = 41; if (Visible != null) hashCode = hashCode * 59 + Visible.GetHashCode(); if (Type != null) hashCode = hashCode * 59 + Type.GetHashCode(); if (AutoTypeNumbers != null) hashCode = hashCode * 59 + AutoTypeNumbers.GetHashCode(); if (AutoRange != null) hashCode = hashCode * 59 + AutoRange.GetHashCode(); if (RangeMode != null) hashCode = hashCode * 59 + RangeMode.GetHashCode(); if (Range != null) hashCode = hashCode * 59 + Range.GetHashCode(); if (CategoryOrder != null) hashCode = hashCode * 59 + CategoryOrder.GetHashCode(); if (CategoryArray != null) hashCode = hashCode * 59 + CategoryArray.GetHashCode(); if (Angle != null) hashCode = hashCode * 59 + Angle.GetHashCode(); if (Side != null) hashCode = hashCode * 59 + Side.GetHashCode(); if (Title != null) hashCode = hashCode * 59 + Title.GetHashCode(); if (HoverFormat != null) hashCode = hashCode * 59 + HoverFormat.GetHashCode(); if (UiRevision != null) hashCode = hashCode * 59 + UiRevision.GetHashCode(); if (Color != null) hashCode = hashCode * 59 + Color.GetHashCode(); if (ShowLine != null) hashCode = hashCode * 59 + ShowLine.GetHashCode(); if (LineColor != null) hashCode = hashCode * 59 + LineColor.GetHashCode(); if (LineWidth != null) hashCode = hashCode * 59 + LineWidth.GetHashCode(); if (ShowGrid != null) hashCode = hashCode * 59 + ShowGrid.GetHashCode(); if (GridColor != null) hashCode = hashCode * 59 + GridColor.GetHashCode(); if (GridWidth != null) hashCode = hashCode * 59 + GridWidth.GetHashCode(); if (TickMode != null) hashCode = hashCode * 59 + TickMode.GetHashCode(); if (NTicks != null) hashCode = hashCode * 59 + NTicks.GetHashCode(); if (Tick0 != null) hashCode = hashCode * 59 + Tick0.GetHashCode(); if (DTick != null) hashCode = hashCode * 59 + DTick.GetHashCode(); if (TickVals != null) hashCode = hashCode * 59 + TickVals.GetHashCode(); if (TickText != null) hashCode = hashCode * 59 + TickText.GetHashCode(); if (Ticks != null) hashCode = hashCode * 59 + Ticks.GetHashCode(); if (TickLen != null) hashCode = hashCode * 59 + TickLen.GetHashCode(); if (TickWidth != null) hashCode = hashCode * 59 + TickWidth.GetHashCode(); if (TickColor != null) hashCode = hashCode * 59 + TickColor.GetHashCode(); if (ShowTickLabels != null) hashCode = hashCode * 59 + ShowTickLabels.GetHashCode(); if (ShowTickPrefix != null) hashCode = hashCode * 59 + ShowTickPrefix.GetHashCode(); if (TickPrefix != null) hashCode = hashCode * 59 + TickPrefix.GetHashCode(); if (ShowTickSuffix != null) hashCode = hashCode * 59 + ShowTickSuffix.GetHashCode(); if (TickSuffix != null) hashCode = hashCode * 59 + TickSuffix.GetHashCode(); if (ShowExponent != null) hashCode = hashCode * 59 + ShowExponent.GetHashCode(); if (ExponentFormat != null) hashCode = hashCode * 59 + ExponentFormat.GetHashCode(); if (MinExponent != null) hashCode = hashCode * 59 + MinExponent.GetHashCode(); if (SeparateThousands != null) hashCode = hashCode * 59 + SeparateThousands.GetHashCode(); if (TickFont != null) hashCode = hashCode * 59 + TickFont.GetHashCode(); if (TickAngle != null) hashCode = hashCode * 59 + TickAngle.GetHashCode(); if (TickFormat != null) hashCode = hashCode * 59 + TickFormat.GetHashCode(); if (TickFormatStops != null) hashCode = hashCode * 59 + TickFormatStops.GetHashCode(); if (Layer != null) hashCode = hashCode * 59 + Layer.GetHashCode(); if (Calendar != null) hashCode = hashCode * 59 + Calendar.GetHashCode(); if (CategoryArraySrc != null) hashCode = hashCode * 59 + CategoryArraySrc.GetHashCode(); if (TickValsSrc != null) hashCode = hashCode * 59 + TickValsSrc.GetHashCode(); if (TickTextSrc != null) hashCode = hashCode * 59 + TickTextSrc.GetHashCode(); return hashCode; } } /// <summary> /// Checks for equality of the left RadialAxis and the right RadialAxis. /// </summary> /// <param name="left">Left RadialAxis.</param> /// <param name="right">Right RadialAxis.</param> /// <returns>Boolean</returns> public static bool operator == (RadialAxis left, RadialAxis right) { return Equals(left, right); } /// <summary> /// Checks for inequality of the left RadialAxis and the right RadialAxis. /// </summary> /// <param name="left">Left RadialAxis.</param> /// <param name="right">Right RadialAxis.</param> /// <returns>Boolean</returns> public static bool operator != (RadialAxis left, RadialAxis right) { return !Equals(left, right); } /// <summary> /// Gets a deep copy of this instance. /// </summary> /// <returns>RadialAxis</returns> public RadialAxis DeepClone() { return this.Copy(); } } }
47.261214
150
0.51968
[ "MIT" ]
yaqian256/Plotly.Blazor
Plotly.Blazor/LayoutLib/PolarLib/RadialAxis.cs
35,824
C#
using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using StardewModdingAPI; using StardewValley; using StardewValley.Menus; using System; using System.Collections.Generic; using System.Linq; namespace Shockah.CommonModCode.GMCM { public class MultiSelectTextOption<T> { private const int RowHeight = 60; private const float ColumnSpacing = 16f; private const float CheckboxScale = 4f; private const float Margin = 16f; private static readonly string ClickSoundName = "drumkit6"; private readonly Func<T, bool> GetValue; private readonly Action<T> AddValue; private readonly Action<T> RemoveValue; private readonly Func<string> Name; private readonly Func<float, int> Columns; private readonly T[] AllowedValues; private readonly Func<string>? Tooltip; private readonly Func<T, string>? FormatAllowedValue; private readonly Action? AfterValuesUpdated; private readonly Lazy<Texture2D> CheckedTexture = new(() => Game1.mouseCursors); private readonly Lazy<Rectangle> CheckedTextureSourceRect = new(() => OptionsCheckbox.sourceRectChecked); private readonly Lazy<Texture2D> UncheckedTexture = new(() => Game1.mouseCursors); private readonly Lazy<Rectangle> UncheckedTextureSourceRect = new(() => OptionsCheckbox.sourceRectUnchecked); private ISet<T> OriginalValues = new HashSet<T>(); private ISet<T> CurrentValues = new HashSet<T>(); private readonly Lazy<int> ActualColumns; private bool? LastMouseLeftPressed; public MultiSelectTextOption( Func<T, bool> getValue, Action<T> addValue, Action<T> removeValue, Func<string> name, Func<float, int> columns, T[] allowedValues, Func<string>? tooltip = null, Func<T, string>? formatAllowedValue = null, Action? afterValuesUpdated = null ) { this.GetValue = getValue; this.AddValue = addValue; this.RemoveValue = removeValue; this.Name = name; this.Columns = columns; this.AllowedValues = allowedValues; this.Tooltip = tooltip; this.FormatAllowedValue = formatAllowedValue; this.AfterValuesUpdated = afterValuesUpdated; ActualColumns = new(() => Columns(GetGMCMSize().X)); } private void Initialize() { OriginalValues = AllowedValues.Where(v => GetValue(v)).ToHashSet(); CurrentValues = OriginalValues.ToHashSet(); } internal void AddToGMCM(IGenericModConfigMenuApi api, IManifest mod) { api.AddComplexOption( mod: mod, name: Name, tooltip: Tooltip, draw: (b, position) => Draw(b, position), height: () => GetHeight(), beforeMenuOpened: () => { LastMouseLeftPressed = null; Initialize(); }, beforeMenuClosed: () => Initialize(), afterReset: () => Initialize(), beforeSave: () => BeforeSave() ); } private void BeforeSave() { bool hasAnyChange = false; foreach (var allowedValue in AllowedValues) { bool wasSet = OriginalValues.Contains(allowedValue); bool isSet = CurrentValues.Contains(allowedValue); if (wasSet != isSet) { if (isSet) AddValue(allowedValue); else RemoveValue(allowedValue); hasAnyChange = true; } } if (hasAnyChange) { OriginalValues = CurrentValues.ToHashSet(); AfterValuesUpdated?.Invoke(); } } private Vector2 GetGMCMSize() => new(Math.Min(1200, Game1.uiViewport.Width - 200), Game1.uiViewport.Height - 128 - 116); private Vector2 GetGMCMPosition(Vector2? size = null) { Vector2 gmcmSize = size ?? GetGMCMSize(); return new((Game1.uiViewport.Width - gmcmSize.X) / 2, (Game1.uiViewport.Height - gmcmSize.Y) / 2); } private int GetHeight() { int rows = (int)Math.Ceiling(1f * AllowedValues.Length / ActualColumns.Value) + 1; // extra row, we're not rendering inline return rows * RowHeight; } private void Draw(SpriteBatch b, Vector2 basePosition) { bool mouseLeftPressed = Game1.input.GetMouseState().LeftButton == ButtonState.Pressed; bool didClick = mouseLeftPressed && LastMouseLeftPressed == false; LastMouseLeftPressed = mouseLeftPressed; int mouseX = Constants.TargetPlatform == GamePlatform.Android ? Game1.getMouseX() : Game1.getOldMouseX(); int mouseY = Constants.TargetPlatform == GamePlatform.Android ? Game1.getMouseY() : Game1.getOldMouseY(); int columns = ActualColumns.Value; Vector2 gmcmSize = GetGMCMSize(); Vector2 gmcmPosition = GetGMCMPosition(gmcmSize); bool hoverGMCM = mouseX >= gmcmPosition.X && mouseY >= gmcmPosition.Y && mouseX < gmcmPosition.X + gmcmSize.X && mouseY < gmcmPosition.Y + gmcmSize.Y; float columnWidth = (gmcmSize.X - (columns - 1) * ColumnSpacing - Margin) / columns; Vector2 valueSize = new(columnWidth, RowHeight); int row = 1; int column = 0; foreach (T allowedValue in AllowedValues) { Vector2 valuePosition = new(gmcmPosition.X + Margin + (valueSize.X + ColumnSpacing) * column, basePosition.Y + valueSize.Y * row); bool isChecked = CurrentValues.Contains(allowedValue); Texture2D texture = isChecked ? CheckedTexture.Value : UncheckedTexture.Value; Rectangle textureSourceRect = isChecked ? CheckedTextureSourceRect.Value : UncheckedTextureSourceRect.Value; string text = FormatAllowedValue is null ? $"{allowedValue}" : FormatAllowedValue(allowedValue); b.Draw(texture, valuePosition + new Vector2(0, 3), textureSourceRect, Color.White, 0, Vector2.Zero, CheckboxScale, SpriteEffects.None, 0); Utility.drawTextWithShadow(b, text, Game1.dialogueFont, valuePosition + new Vector2(textureSourceRect.Width * CheckboxScale + 8, 0), Game1.textColor, 1f); bool hoverCheckbox = mouseX >= valuePosition.X && mouseY >= valuePosition.Y && mouseX < valuePosition.X + textureSourceRect.Width * CheckboxScale && mouseY < valuePosition.Y + textureSourceRect.Height * CheckboxScale; if (hoverGMCM && hoverCheckbox && didClick) { if (CurrentValues.Contains(allowedValue)) CurrentValues.Remove(allowedValue); else CurrentValues.Add(allowedValue); Game1.playSound(ClickSoundName); } if (++column == columns) { row++; column = 0; } } } } public static class MultiSelectTextOptionExtensions { public static void AddMultiSelectTextOption<T>( this IGenericModConfigMenuApi api, IManifest mod, Func<T, bool> getValue, Action<T> addValue, Action<T> removeValue, Func<string> name, Func<float, int> columns, T[] allowedValues, Func<string>? tooltip = null, Func<T, string>? formatAllowedValue = null, Action? afterValuesUpdated = null ) { var option = new MultiSelectTextOption<T>(getValue, addValue, removeValue, name, columns, allowedValues, tooltip, formatAllowedValue, afterValuesUpdated); option.AddToGMCM(api, mod); } public static void AddMultiSelectTextOption<T>( this IGenericModConfigMenuApi api, IManifest mod, Func<IReadOnlySet<T>> getValues, Action<IReadOnlySet<T>> setValues, Func<string> name, Func<float, int> columns, T[] allowedValues, Func<string>? tooltip = null, Func<T, string>? formatAllowedValue = null ) { Lazy<IReadOnlySet<T>> originalValues = new(() => getValues()); Lazy<ISet<T>> currentValues = new(() => originalValues.Value.ToHashSet()); AddMultiSelectTextOption( api: api, mod: mod, getValue: originalValues.Value.Contains, addValue: value => currentValues.Value.Add(value), removeValue: value => currentValues.Value.Remove(value), name: name, columns: columns, allowedValues: allowedValues, tooltip: tooltip, formatAllowedValue: formatAllowedValue, afterValuesUpdated: () => setValues((IReadOnlySet<T>)currentValues.Value) ); } } }
34.141593
221
0.712286
[ "Apache-2.0" ]
Shockah/Stardew-Valley-Mods
_Common/GMCM/MultiSelectTextOption.cs
7,718
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the managedblockchain-2018-09-24.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.ManagedBlockchain.Model { /// <summary> /// Container for the parameters to the ListNetworks operation. /// Returns information about the networks in which the current AWS account participates. /// /// /// <para> /// Applies to Hyperledger Fabric and Ethereum. /// </para> /// </summary> public partial class ListNetworksRequest : AmazonManagedBlockchainRequest { private Framework _framework; private int? _maxResults; private string _name; private string _nextToken; private NetworkStatus _status; /// <summary> /// Gets and sets the property Framework. /// <para> /// An optional framework specifier. If provided, only networks of this framework type /// are listed. /// </para> /// </summary> public Framework Framework { get { return this._framework; } set { this._framework = value; } } // Check to see if Framework property is set internal bool IsSetFramework() { return this._framework != null; } /// <summary> /// Gets and sets the property MaxResults. /// <para> /// The maximum number of networks to list. /// </para> /// </summary> [AWSProperty(Min=1, Max=10)] public int MaxResults { get { return this._maxResults.GetValueOrDefault(); } set { this._maxResults = value; } } // Check to see if MaxResults property is set internal bool IsSetMaxResults() { return this._maxResults.HasValue; } /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the network. /// </para> /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property NextToken. /// <para> /// The pagination token that indicates the next set of results to retrieve. /// </para> /// </summary> [AWSProperty(Max=128)] public string NextToken { get { return this._nextToken; } set { this._nextToken = value; } } // Check to see if NextToken property is set internal bool IsSetNextToken() { return this._nextToken != null; } /// <summary> /// Gets and sets the property Status. /// <para> /// An optional status specifier. If provided, only networks currently in this status /// are listed. /// </para> /// /// <para> /// Applies only to Hyperledger Fabric. /// </para> /// </summary> public NetworkStatus Status { get { return this._status; } set { this._status = value; } } // Check to see if Status property is set internal bool IsSetStatus() { return this._status != null; } } }
29.789116
116
0.548755
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ManagedBlockchain/Generated/Model/ListNetworksRequest.cs
4,379
C#
using System; using System.Collections.Generic; using System.Text; namespace NewAge.Redis.Interfaces { /// <summary> /// 所有缓存需要继承的接口(不做任何实现) 实现接口依赖注入 /// 接口的命名规则 是在其实现类的基础名称前加I /// 此接口不要轻易更改名字 /// </summary> public interface IRedisDependency { } }
16.705882
37
0.658451
[ "MIT" ]
godzff/NewAge.Redis
src/Interfaces/IRedisDependency.cs
398
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("11. Orders")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("11. Orders")] [assembly: System.Reflection.AssemblyTitleAttribute("11. Orders")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generated by the MSBuild WriteCodeFragment class.
40.833333
80
0.640816
[ "MIT" ]
rythm-net/SoftUni
Fundamentals with C#/T04 - Basic Syntax, Conditional Statements, Loops/exercise/11. Orders/obj/Debug/net6.0/11. Orders.AssemblyInfo.cs
980
C#
using System; using System.Threading.Tasks; using Microsoft.AspNetCore.SignalR; using Microsoft.Extensions.Logging; using ChatLe.Models; namespace ChatLe.Hubs { /// <summary> /// Chat Hub /// </summary> public class ChatHub : Hub { readonly IServiceProvider _provider; /// <summary> /// The chat repository manager /// </summary> public IChatManager<string, ChatLeUser, Conversation, Attendee, Message, NotificationConnection> Manager { get { return _provider.GetService(typeof(IChatManager<string, ChatLeUser, Conversation, Attendee, Message, NotificationConnection>)) as IChatManager<string, ChatLeUser, Conversation, Attendee, Message, NotificationConnection>; } } /// <summary> /// Logger /// </summary> public ILogger Logger { get; private set; } /// <summary> /// Constructor /// </summary> /// <param name="manager">The chat repository manager</param> /// <param name="loggerFactory">The logger factory</param> public ChatHub(IServiceProvider provider, ILoggerFactory loggerFactory) : base() { if (provider == null) throw new ArgumentNullException("provider"); if (loggerFactory == null) throw new ArgumentNullException("loggerFactory"); Logger = loggerFactory.CreateLogger<ChatHub>(); Logger.LogInformation("constructor"); _provider = provider; } /// <summary> /// Called when the connection connects to this hub instance. /// <para>Create a signalR group for the connected user with is name</para> /// </summary> /// <returns>a <see cref="Task"/></returns> public override async Task OnConnectedAsync() { string name = Context.User.Identity.Name; if (string.IsNullOrEmpty(name)) { return; } Logger.LogInformation("OnConnected " + name); await Manager.AddConnectionIdAsync(name, Context.ConnectionId, "signalR"); await Groups.AddToGroupAsync(Context.ConnectionId, name); await Clients.All.SendAsync("userConnected", new { id = name }); await base.OnConnectedAsync(); } /// <summary> /// Called when a connection disconnects from this hub gracefully or due to a timeout. /// <para>Remove the signalR group for the user</para> /// </summary> /// <param name="stopCalled">true, if stop was called on the client closing the connection gracefully; false, /// <para>if the connection has been lost for longer than the Configuration.IConfigurationManager.DisconnectTimeout.</para> /// <para>Timeouts can be caused by clients reconnecting to another SignalR server in scaleout.</para> /// </param> /// <returns>a <see cref="Task"/></returns> public override async Task OnDisconnectedAsync(Exception ex) { bool stopCalled = ex != null; Logger.LogInformation("OnDisconnected stopCalled " + stopCalled); try { var user = await Manager.RemoveConnectionIdAsync(Context.ConnectionId, "signalR", true); if (user != null) await Clients.All.SendAsync("userDisconnected", new { id = user.UserName, isRemoved = user.IsGuess }); } catch (Exception e) { Logger.LogError(e, "ChatHub OnDisconnecteAssync error : {0}", e.Message); } await base.OnDisconnectedAsync(ex); } } }
34.22449
224
0.664281
[ "Apache-2.0" ]
aguacongas/chatle
src/chatle/Hubs/ChatHub.cs
3,356
C#
using System; using System.Collections.Concurrent; using System.Collections.Generic; using System.Runtime.CompilerServices; using Monq.Core.Authorization.Models; [assembly: InternalsVisibleTo("Monq.Core.Authorization.Tests")] namespace Monq.Core.Authorization.Helpers { /// <summary> /// Хранилище пакетов прав пользователей. /// </summary> internal static class PacketRepository { static readonly ConcurrentDictionary<long, IEnumerable<PacketViewModel>> _packets = new ConcurrentDictionary<long, IEnumerable<PacketViewModel>>(); static readonly ConcurrentDictionary<long, IEnumerable<SystemPacketMapViewModel>> _systemPacketMaps = new ConcurrentDictionary<long, IEnumerable<SystemPacketMapViewModel>>(); /// <summary> /// Получить пакеты прав по идентификатору пользователя. /// </summary> /// <param name="userId">Идентификатор пользователя.</param> /// <returns>Коллекция пакетов прав пользователя <see cref="IEnumerable{PacketViewModel}"/>.</returns> public static IEnumerable<PacketViewModel> Get(in long userId) => _packets.TryGetValue(userId, out var packets) ? packets : Array.Empty<PacketViewModel>(); /// <summary> /// Получить соответствия системных пакетов прав. /// </summary> /// <returns>Коллекция соответствий системных пакетов прав <see cref="IEnumerable{SystemPacketMapViewModel}"/>.</returns> public static IEnumerable<SystemPacketMapViewModel> GetSystemPacketMaps(in long userId) => _systemPacketMaps.TryGetValue(userId, out var systemPacketMaps) ? systemPacketMaps : Array.Empty<SystemPacketMapViewModel>(); /// <summary> /// Установить соответствие пользователя с правом. /// </summary> /// <param name="userId">Идентификатор пользователя.</param> /// <param name="grant">Пакет прав пользователя <see cref="PacketViewModel"/>.</param> public static void Set(in long userId, in PacketViewModel grant) => _packets[userId] = new[] { grant }; /// <summary> /// Установить соответствие пользователя с пакетом прав. /// </summary> /// <param name="userId">Идентификатор пользователя.</param> /// <param name="grants">Коллекция пакетов прав пользователя <see cref="IEnumerable{PacketViewModel}"/>.</param> public static void Set(in long userId, in IEnumerable<PacketViewModel> grants) => _packets[userId] = grants; /// <summary> /// Установить соответствие системных пакетов прав. /// </summary> /// <param name="userId">Идентификатор пользователя.</param> /// <param name="systemPacketMaps">Коллекция соответствия для системных пакетов прав <see cref="IEnumerable{SystemPacketMapViewModel}"/>.</param> public static void SetSystemPacketMaps(in long userId, in IEnumerable<SystemPacketMapViewModel> systemPacketMaps) => _systemPacketMaps[userId] = systemPacketMaps; } }
49.322581
153
0.685415
[ "Apache-2.0" ]
MONQDL/Monq.Core.Authorization
src/Monq.Core.Authorization/Helpers/PacketRepository.cs
3,578
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace Tools.Debugger.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "16.1.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.592593
151
0.581852
[ "MIT" ]
jbatonnet/System
Source/[Tools]/Tools.Debugger/Properties/Settings.Designer.cs
1,071
C#
using Senparc.NeuChar.App.MessageHandlers; using Senparc.NeuChar.MessageHandlers.CheckSignatures; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Senparc.CO2NET.HttpUtility; using Senparc.CO2NET.Trace; using System.IO; using Senparc.NeuChar.App.Entities; #if NET45 using System.Web.Mvc; #else using Microsoft.AspNetCore.Mvc; #endif namespace Senparc.NeuChar.App.Controllers { /// <summary> /// 用于快速实现 NeuChar 开发者发布的 App 与 NeuChar 平台交互(如状态发送)的默认 Controller /// <para>如果你有已经自己实现的带有 MessageHandler 的 Controller,也可以不使用这个基类</para> /// </summary> public abstract class NeuCharAppController : Controller { protected abstract string Token { get; } readonly Func<string> _getRandomFileName = () => SystemTime.Now.ToString("yyyyMMdd-HHmmss") + Guid.NewGuid().ToString("n").Substring(0, 6); /// <summary> /// 后台验证地址(使用Get),微信后台的“接口配置信息”的Url填写如:http://sdk.weixin.senparc.com/weixin /// </summary> [HttpGet] [ActionName("NeuCharApp")] public ActionResult Get(PostModel postModel, string echostr, string neucharAppId) { postModel.Token = Token; postModel.AppId = neucharAppId;//加密暂时用不到 if (postModel.Signature == CheckSignatureWeChat.GetSignature(postModel)) { return Content(echostr); //返回随机字符串则表示验证通过 } else { return Content($"failed:{postModel.Signature},{CheckSignatureWeChat.GetSignature(postModel.Timestamp, postModel.Nonce, Token)}。" + $"如果你在浏览器中看到这句话,说明此地址可以被作为 NeuChar - App后台的Url,请注意保持Token一致。"); } } /// <summary> /// 最简化的处理流程(不加密) /// </summary> [HttpPost] [ActionName("NeuCharApp")] public ActionResult Post(PostModel postModel, string neucharAppId) { postModel.Token = Token; postModel.AppId = neucharAppId;// $"NeuCharApp:AppId:{neucharAppId}"; if (postModel.Signature != CheckSignatureWeChat.GetSignature(postModel)) { return Content("参数错误!"); } //postModel.EncodingAESKey = EncodingAESKey;//根据自己后台的设置保持一致 //postModel.AppId = AppId;//根据自己后台的设置保持一致 NeuCharAppMessageHandler messageHandler = null; try { #if NET45 messageHandler = new NeuCharAppMessageHandler(Request.InputStream, postModel); #else messageHandler = new NeuCharAppMessageHandler(Request.GetRequestMemoryStream(), postModel); #endif messageHandler.SaveRequestMessageLog();//记录 Request 日志(可选) messageHandler.Execute();//执行微信处理过程(关键) messageHandler.SaveResponseMessageLog();//记录 Response 日志(可选) var responseText = messageHandler.TextResponseMessage ?? ""; return Content(responseText); } catch (Exception ex) { #region 异常处理 SenparcTrace.Log($"NeuCharAppMessageHandler错误:{ex.Message}"); var logPath = Path.Combine(messageHandler.GetLogPath(), $"Error_{_getRandomFileName()}.txt"); using (TextWriter tw = new StreamWriter(logPath)) { tw.WriteLine("ExecptionMessage:" + ex.Message); tw.WriteLine(ex.Source); tw.WriteLine(ex.StackTrace); //tw.WriteLine("InnerExecptionMessage:" + ex.InnerException.Message); if (messageHandler.ResponseDocument != null) { tw.WriteLine(messageHandler.ResponseDocument.ToString()); } if (ex.InnerException != null) { tw.WriteLine("========= InnerException ========="); tw.WriteLine(ex.InnerException.Message); tw.WriteLine(ex.InnerException.Source); tw.WriteLine(ex.InnerException.StackTrace); } tw.Flush(); tw.Close(); } return Content(""); #endregion } } } }
35.349593
147
0.574747
[ "Apache-2.0" ]
edison1105/NeuChar
src/Senparc.NeuChar.App/Controllers/NeuCharAppController.cs
4,786
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Reflection; namespace Cake.Frosting.Internal; internal static class TypeExtensions { public static string GetTaskName(this Type task) { if (task is null) { throw new ArgumentNullException(nameof(task)); } var attribute = task.GetCustomAttribute<TaskNameAttribute>(); return attribute != null ? attribute.Name : task.Name; } }
28.363636
71
0.69391
[ "MIT" ]
ecampidoglio/cake
src/Cake.Frosting/Internal/Extensions/TypeExtensions.cs
626
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Diagnostics; using System.Globalization; using System.Linq; using System.Linq.Expressions; using System.Reflection; using JetBrains.Annotations; using Microsoft.EntityFrameworkCore.Diagnostics; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata.Builders; using Microsoft.EntityFrameworkCore.Metadata.Conventions; using Microsoft.EntityFrameworkCore.Metadata.Conventions.Internal; using Microsoft.EntityFrameworkCore.Utilities; using Microsoft.EntityFrameworkCore.ValueGeneration.Internal; namespace Microsoft.EntityFrameworkCore.Metadata.Internal { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public class InternalEntityTypeBuilder : AnnotatableBuilder<EntityType, InternalModelBuilder>, IConventionEntityTypeBuilder { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public InternalEntityTypeBuilder([NotNull] EntityType metadata, [NotNull] InternalModelBuilder modelBuilder) : base(metadata, modelBuilder) { } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalKeyBuilder PrimaryKey( [CanBeNull] IReadOnlyList<string> propertyNames, ConfigurationSource configurationSource) => PrimaryKey(GetOrCreateProperties(propertyNames, configurationSource, required: true), configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalKeyBuilder PrimaryKey( [CanBeNull] IReadOnlyList<MemberInfo> clrMembers, ConfigurationSource configurationSource) => PrimaryKey(GetOrCreateProperties(clrMembers, configurationSource), configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalKeyBuilder PrimaryKey( [CanBeNull] IReadOnlyList<Property> properties, ConfigurationSource configurationSource) { if (!CanSetPrimaryKey(properties, configurationSource)) { return null; } InternalKeyBuilder keyBuilder = null; if (properties == null) { Metadata.SetPrimaryKey(properties, configurationSource); } else { var previousPrimaryKey = Metadata.FindPrimaryKey(); if (previousPrimaryKey != null && PropertyListComparer.Instance.Compare(previousPrimaryKey.Properties, properties) == 0) { previousPrimaryKey.UpdateConfigurationSource(configurationSource); return Metadata.SetPrimaryKey(properties, configurationSource).Builder; } using (ModelBuilder.Metadata.ConventionDispatcher.DelayConventions()) { keyBuilder = HasKeyInternal(properties, configurationSource); if (keyBuilder == null) { return null; } Metadata.SetPrimaryKey(keyBuilder.Metadata.Properties, configurationSource); foreach (var key in Metadata.GetDeclaredKeys().ToList()) { if (key == keyBuilder.Metadata) { continue; } var referencingForeignKeys = key .GetReferencingForeignKeys() .Where(fk => fk.GetPrincipalKeyConfigurationSource() == null) .ToList(); foreach (var referencingForeignKey in referencingForeignKeys) { DetachRelationship(referencingForeignKey).Attach(); } } if (previousPrimaryKey?.Builder != null) { RemoveKeyIfUnused(previousPrimaryKey, configurationSource); } } } // TODO: Use convention batch to get the updated builder, see #15898 if (keyBuilder?.Metadata.Builder == null) { properties = GetActualProperties(properties, null); return properties == null ? null : Metadata.FindPrimaryKey(properties).Builder; } return keyBuilder; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanSetPrimaryKey( [CanBeNull] IReadOnlyList<IConventionProperty> properties, ConfigurationSource configurationSource) { var previousPrimaryKey = Metadata.FindPrimaryKey(); if (properties == null) { if (previousPrimaryKey == null) { return true; } } else if (previousPrimaryKey != null && PropertyListComparer.Instance.Compare(previousPrimaryKey.Properties, properties) == 0) { return true; } return configurationSource.Overrides(Metadata.GetPrimaryKeyConfigurationSource()) && (properties == null || !Metadata.IsKeyless || configurationSource.Overrides(Metadata.GetIsKeylessConfigurationSource())); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalKeyBuilder HasKey([NotNull] IReadOnlyList<string> propertyNames, ConfigurationSource configurationSource) => HasKeyInternal(GetOrCreateProperties(propertyNames, configurationSource, required: true), configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalKeyBuilder HasKey([NotNull] IReadOnlyList<MemberInfo> clrMembers, ConfigurationSource configurationSource) => HasKeyInternal(GetOrCreateProperties(clrMembers, configurationSource), configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalKeyBuilder HasKey([NotNull] IReadOnlyList<Property> properties, ConfigurationSource? configurationSource) => HasKeyInternal(properties, configurationSource); private InternalKeyBuilder HasKeyInternal(IReadOnlyList<Property> properties, ConfigurationSource? configurationSource) { if (properties == null) { return null; } var actualProperties = GetActualProperties(properties, configurationSource); var key = Metadata.FindDeclaredKey(actualProperties); if (key == null) { if (configurationSource == null) { return null; } if (Metadata.IsKeyless && !configurationSource.Overrides(Metadata.GetIsKeylessConfigurationSource())) { return null; } if (Metadata.GetIsKeylessConfigurationSource() != ConfigurationSource.Explicit) { Metadata.SetIsKeyless(false, configurationSource.Value); } var containingForeignKeys = actualProperties .SelectMany(p => p.GetContainingForeignKeys().Where(k => k.DeclaringEntityType != Metadata)) .ToList(); if (containingForeignKeys.Any(fk => !configurationSource.Overrides(fk.GetPropertiesConfigurationSource()))) { return null; } if (configurationSource != ConfigurationSource.Explicit // let it throw for explicit && actualProperties.Any(p => !p.Builder.CanSetIsRequired(true, configurationSource))) { return null; } using (Metadata.Model.ConventionDispatcher.DelayConventions()) { foreach (var foreignKey in containingForeignKeys) { if (foreignKey.GetPropertiesConfigurationSource() == ConfigurationSource.Explicit) { // let it throw for explicit continue; } foreignKey.Builder.HasForeignKey((IReadOnlyList<Property>)null, configurationSource.Value); } foreach (var actualProperty in actualProperties) { actualProperty.Builder.IsRequired(true, configurationSource.Value); } key = Metadata.AddKey(actualProperties, configurationSource.Value); } if (key.Builder == null) { key = Metadata.FindDeclaredKey(actualProperties); } } else if (configurationSource.HasValue) { key.UpdateConfigurationSource(configurationSource.Value); Metadata.SetIsKeyless(false, configurationSource.Value); } return key?.Builder; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder HasNoKey([NotNull] Key key, ConfigurationSource configurationSource) { var currentConfigurationSource = key.GetConfigurationSource(); if (!configurationSource.Overrides(currentConfigurationSource)) { return null; } using (Metadata.Model.ConventionDispatcher.DelayConventions()) { var detachedRelationships = key.GetReferencingForeignKeys().ToList().Select(DetachRelationship).ToList(); Metadata.RemoveKey(key); foreach (var detachedRelationship in detachedRelationships) { detachedRelationship.Attach(); } RemoveUnusedImplicitProperties(key.Properties); foreach (var property in key.Properties) { if (!property.IsKey() && property.ClrType.IsNullableType() && !property.GetContainingForeignKeys().Any(fk => fk.IsRequired)) { // TODO: This should be handled by reference tracking, see #15898 property.Builder?.IsRequired(null, configurationSource); } } } return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanRemoveKey([NotNull] Key key, ConfigurationSource configurationSource) => configurationSource.Overrides(key.GetConfigurationSource()); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static List<(InternalKeyBuilder, ConfigurationSource?)> DetachKeys([NotNull] IEnumerable<Key> keysToDetach) { var keysToDetachList = (keysToDetach as List<Key>) ?? keysToDetach.ToList(); if (keysToDetachList.Count == 0) { return null; } var detachedKeys = new List<(InternalKeyBuilder, ConfigurationSource?)>(); foreach (var keyToDetach in keysToDetachList) { var detachedKey = DetachKey(keyToDetach); detachedKeys.Add(detachedKey); } return detachedKeys; } private static (InternalKeyBuilder, ConfigurationSource?) DetachKey(Key keyToDetach) { var entityTypeBuilder = keyToDetach.DeclaringEntityType.Builder; var keyBuilder = keyToDetach.Builder; var primaryKeyConfigurationSource = keyToDetach.IsPrimaryKey() ? keyToDetach.DeclaringEntityType.GetPrimaryKeyConfigurationSource() : null; if (entityTypeBuilder == null) { keyToDetach.DeclaringEntityType.RemoveKey(keyToDetach.Properties); } else { entityTypeBuilder.HasNoKey(keyToDetach, keyToDetach.GetConfigurationSource()); } return (keyBuilder, primaryKeyConfigurationSource); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder HasNoKey(ConfigurationSource configurationSource) { if (Metadata.IsKeyless) { Metadata.SetIsKeyless(true, configurationSource); return this; } if (!CanRemoveKey(configurationSource)) { return null; } using (Metadata.Model.ConventionDispatcher.DelayConventions()) { foreach (var foreignKey in Metadata.GetReferencingForeignKeys().ToList()) { foreignKey.DeclaringEntityType.Builder.HasNoRelationship(foreignKey, configurationSource); } foreach (var foreignKey in Metadata.GetForeignKeys()) { foreignKey.HasPrincipalToDependent((string)null, configurationSource); } foreach (var key in Metadata.GetKeys().ToList()) { if (key.GetConfigurationSource() != ConfigurationSource.Explicit) { HasNoKey(key, configurationSource); } } Metadata.SetIsKeyless(true, configurationSource); return this; } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanRemoveKey(ConfigurationSource configurationSource) => Metadata.IsKeyless || (configurationSource.Overrides(Metadata.GetIsKeylessConfigurationSource()) && !Metadata.GetKeys().Any(key => !configurationSource.Overrides(key.GetConfigurationSource())) && !Metadata.GetReferencingForeignKeys().Any(fk => !configurationSource.Overrides(fk.GetConfigurationSource())) && !Metadata.GetForeignKeys() .Any(fk => !configurationSource.Overrides(fk.GetPrincipalToDependentConfigurationSource()))); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalPropertyBuilder Property( [CanBeNull] Type propertyType, [NotNull] string propertyName, ConfigurationSource? configurationSource) => Property(propertyType, propertyName, typeConfigurationSource: configurationSource, configurationSource: configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalPropertyBuilder Property( [CanBeNull] Type propertyType, [NotNull] string propertyName, ConfigurationSource? typeConfigurationSource, ConfigurationSource? configurationSource) => Property( propertyType, propertyName, memberInfo: null, typeConfigurationSource, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalPropertyBuilder Property([NotNull] string propertyName, ConfigurationSource? configurationSource) => Property(propertyType: null, propertyName, memberInfo: null, typeConfigurationSource: null, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalPropertyBuilder Property([NotNull] MemberInfo memberInfo, ConfigurationSource? configurationSource) => Property(memberInfo.GetMemberType(), memberInfo.GetSimpleMemberName(), memberInfo, configurationSource, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalPropertyBuilder IndexerProperty( [CanBeNull] Type propertyType, [NotNull] string propertyName, ConfigurationSource? configurationSource) { var indexerPropertyInfo = Metadata.FindIndexerPropertyInfo(); if (indexerPropertyInfo == null) { throw new InvalidOperationException( CoreStrings.NonIndexerEntityType(propertyName, Metadata.DisplayName(), typeof(string).ShortDisplayName())); } return Property(propertyType, propertyName, indexerPropertyInfo, configurationSource, configurationSource); } private InternalPropertyBuilder Property( [CanBeNull] Type propertyType, [NotNull] string propertyName, [CanBeNull] MemberInfo memberInfo, ConfigurationSource? typeConfigurationSource, ConfigurationSource? configurationSource) { var entityType = Metadata; List<Property> propertiesToDetach = null; var existingProperty = entityType.FindProperty(propertyName); if (existingProperty != null) { if (existingProperty.DeclaringEntityType != Metadata) { if (!IsIgnored(propertyName, configurationSource)) { Metadata.RemoveIgnored(propertyName); } entityType = existingProperty.DeclaringEntityType; } var existingMember = existingProperty.GetIdentifyingMemberInfo(); if ((memberInfo == null || existingMember.IsOverridenBy(memberInfo)) && (propertyType == null || propertyType == existingProperty.ClrType)) { if (configurationSource.HasValue) { existingProperty.UpdateConfigurationSource(configurationSource.Value); } if (propertyType != null && typeConfigurationSource.HasValue) { existingProperty.UpdateTypeConfigurationSource(typeConfigurationSource.Value); } return existingProperty.Builder; } if (memberInfo == null || (memberInfo is PropertyInfo propertyInfo && propertyInfo.IsIndexerProperty())) { if (existingProperty.GetTypeConfigurationSource() is ConfigurationSource existingTypeConfigurationSource && !typeConfigurationSource.Overrides(existingTypeConfigurationSource)) { return null; } memberInfo ??= existingProperty.GetIdentifyingMemberInfo(); } else if (!configurationSource.Overrides(existingProperty.GetConfigurationSource())) { return null; } if (propertyType == null) { propertyType = existingProperty.ClrType; } propertiesToDetach = new List<Property> { existingProperty }; } else { if (!configurationSource.HasValue || IsIgnored(propertyName, configurationSource)) { return null; } foreach (var conflictingServiceProperty in Metadata.FindServicePropertiesInHierarchy(propertyName)) { if (!configurationSource.Overrides(conflictingServiceProperty.GetConfigurationSource())) { return null; } } foreach (var conflictingNavigation in Metadata.FindNavigationsInHierarchy(propertyName)) { var foreignKey = conflictingNavigation.ForeignKey; var navigationConfigurationSource = conflictingNavigation.GetConfigurationSource(); if (!configurationSource.Overrides(navigationConfigurationSource)) { return null; } if (navigationConfigurationSource == ConfigurationSource.Explicit) { throw new InvalidOperationException( CoreStrings.PropertyCalledOnNavigation(propertyName, Metadata.DisplayName())); } } foreach (var conflictingSkipNavigation in Metadata.FindSkipNavigationsInHierarchy(propertyName)) { if (!configurationSource.Overrides(conflictingSkipNavigation.GetConfigurationSource())) { return null; } } if (memberInfo == null) { memberInfo = Metadata.ClrType?.GetMembersInHierarchy(propertyName).FirstOrDefault(); } if (propertyType == null) { if (memberInfo == null) { throw new InvalidOperationException(CoreStrings.NoPropertyType(propertyName, Metadata.DisplayName())); } propertyType = memberInfo.GetMemberType(); typeConfigurationSource = ConfigurationSource.Explicit; } else if (memberInfo != null && propertyType != memberInfo.GetMemberType() && memberInfo != Metadata.FindIndexerPropertyInfo() && typeConfigurationSource != null) { return null; } foreach (var derivedType in Metadata.GetDerivedTypes()) { var derivedProperty = derivedType.FindDeclaredProperty(propertyName); if (derivedProperty != null) { if (propertiesToDetach == null) { propertiesToDetach = new List<Property>(); } propertiesToDetach.Add(derivedProperty); } } } InternalPropertyBuilder builder; using (Metadata.Model.ConventionDispatcher.DelayConventions()) { var detachedProperties = propertiesToDetach == null ? null : DetachProperties(propertiesToDetach); if (existingProperty == null) { Metadata.RemoveIgnored(propertyName); foreach (var conflictingServiceProperty in Metadata.FindServicePropertiesInHierarchy(propertyName)) { if (conflictingServiceProperty.GetConfigurationSource() != ConfigurationSource.Explicit) { conflictingServiceProperty.DeclaringEntityType.RemoveServiceProperty(conflictingServiceProperty); } } foreach (var conflictingNavigation in Metadata.FindNavigationsInHierarchy(propertyName)) { if (conflictingNavigation.GetConfigurationSource() == ConfigurationSource.Explicit) { continue; } var foreignKey = conflictingNavigation.ForeignKey; if (foreignKey.GetConfigurationSource() == ConfigurationSource.Convention) { foreignKey.DeclaringEntityType.Builder.HasNoRelationship(foreignKey, ConfigurationSource.Convention); } else if (foreignKey.Builder.HasNavigation( (string)null, conflictingNavigation.IsOnDependent, configurationSource.Value) == null) { return null; } } foreach (var conflictingSkipNavigation in Metadata.FindSkipNavigationsInHierarchy(propertyName)) { if (conflictingSkipNavigation.GetConfigurationSource() == ConfigurationSource.Explicit) { continue; } var inverse = conflictingSkipNavigation.Inverse; if (inverse?.Builder != null && inverse.GetConfigurationSource() != ConfigurationSource.Explicit) { inverse.DeclaringEntityType.Builder.HasNoSkipNavigation(inverse, configurationSource.Value); } conflictingSkipNavigation.DeclaringEntityType.Builder.HasNoSkipNavigation( conflictingSkipNavigation, configurationSource.Value); } } builder = entityType.AddProperty( propertyName, propertyType, memberInfo, typeConfigurationSource, configurationSource.Value).Builder; detachedProperties?.Attach(this); } return builder.Metadata.Builder == null ? Metadata.FindProperty(propertyName)?.Builder : builder; } private bool CanRemoveProperty( [NotNull] Property property, ConfigurationSource configurationSource, bool canOverrideSameSource = true) { Check.NotNull(property, nameof(property)); Check.DebugAssert(property.DeclaringEntityType == Metadata, "property.DeclaringEntityType != Metadata"); var currentConfigurationSource = property.GetConfigurationSource(); return configurationSource.Overrides(currentConfigurationSource) && (canOverrideSameSource || (configurationSource != currentConfigurationSource)); } private ConfigurationSource? RemoveProperty( Property property, ConfigurationSource configurationSource, bool canOverrideSameSource = true) { var currentConfigurationSource = property.GetConfigurationSource(); if (!configurationSource.Overrides(currentConfigurationSource) || !(canOverrideSameSource || (configurationSource != currentConfigurationSource))) { return null; } using (Metadata.Model.ConventionDispatcher.DelayConventions()) { var detachedRelationships = property.GetContainingForeignKeys().ToList() .Select(DetachRelationship).ToList(); foreach (var key in property.GetContainingKeys().ToList()) { detachedRelationships.AddRange( key.GetReferencingForeignKeys().ToList() .Select(DetachRelationship)); var removed = key.DeclaringEntityType.Builder.HasNoKey(key, configurationSource); Check.DebugAssert(removed != null, "removed is null"); } foreach (var index in property.GetContainingIndexes().ToList()) { var removed = index.DeclaringEntityType.Builder.HasNoIndex(index, configurationSource); Check.DebugAssert(removed != null, "removed is null"); } if (property.Builder != null) { var removedProperty = Metadata.RemoveProperty(property.Name); Check.DebugAssert(removedProperty == property, "removedProperty != property"); } foreach (var relationshipSnapshot in detachedRelationships) { relationshipSnapshot.Attach(); } } return currentConfigurationSource; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IMutableNavigationBase Navigation([NotNull] MemberInfo memberInfo) => Navigation(memberInfo.GetSimpleMemberName()); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IMutableNavigationBase Navigation([NotNull] string navigationName) { var existingNavigation = Metadata.FindNavigation(navigationName); var existingSkipNavigation = Metadata.FindSkipNavigation(navigationName); if (existingNavigation == null && existingSkipNavigation == null) { throw new InvalidOperationException( CoreStrings.CanOnlyConfigureExistingNavigations(navigationName, Metadata.DisplayName())); } return ((IMutableNavigationBase)existingNavigation) ?? existingSkipNavigation; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalServicePropertyBuilder ServiceProperty( [NotNull] MemberInfo memberInfo, ConfigurationSource? configurationSource) { var propertyName = memberInfo.GetSimpleMemberName(); List<ServiceProperty> propertiesToDetach = null; InternalServicePropertyBuilder builder = null; var existingProperty = Metadata.FindServiceProperty(propertyName); if (existingProperty != null) { if (existingProperty.DeclaringEntityType != Metadata) { if (!IsIgnored(propertyName, configurationSource)) { Metadata.RemoveIgnored(propertyName); } } if (existingProperty.GetIdentifyingMemberInfo().IsOverridenBy(memberInfo)) { if (configurationSource.HasValue) { existingProperty.UpdateConfigurationSource(configurationSource.Value); } return existingProperty.Builder; } if (!configurationSource.Overrides(existingProperty.GetConfigurationSource())) { return null; } propertiesToDetach = new List<ServiceProperty> { existingProperty }; } else if (!CanAddServiceProperty(memberInfo, configurationSource)) { return null; } else { foreach (var derivedType in Metadata.GetDerivedTypes()) { var derivedProperty = derivedType.FindDeclaredServiceProperty(propertyName); if (derivedProperty != null) { if (propertiesToDetach == null) { propertiesToDetach = new List<ServiceProperty>(); } propertiesToDetach.Add(derivedProperty); } } } using (ModelBuilder.Metadata.ConventionDispatcher.DelayConventions()) { List<InternalServicePropertyBuilder> detachedProperties = null; if (propertiesToDetach != null) { detachedProperties = new List<InternalServicePropertyBuilder>(); foreach (var propertyToDetach in propertiesToDetach) { detachedProperties.Add(DetachServiceProperty(propertyToDetach)); } } if (existingProperty == null) { Metadata.RemoveIgnored(propertyName); foreach (var conflictingProperty in Metadata.FindPropertiesInHierarchy(propertyName).ToList()) { if (conflictingProperty.GetConfigurationSource() != ConfigurationSource.Explicit) { conflictingProperty.DeclaringEntityType.Builder.RemoveProperty(conflictingProperty, configurationSource.Value); } } foreach (var conflictingNavigation in Metadata.FindNavigationsInHierarchy(propertyName).ToList()) { if (conflictingNavigation.GetConfigurationSource() == ConfigurationSource.Explicit) { continue; } var foreignKey = conflictingNavigation.ForeignKey; if (foreignKey.GetConfigurationSource() == ConfigurationSource.Convention) { foreignKey.DeclaringEntityType.Builder.HasNoRelationship(foreignKey, ConfigurationSource.Convention); } else if (foreignKey.Builder.HasNavigation( (string)null, conflictingNavigation.IsOnDependent, configurationSource.Value) == null) { return null; } } foreach (var conflictingSkipNavigation in Metadata.FindSkipNavigationsInHierarchy(propertyName).ToList()) { if (conflictingSkipNavigation.GetConfigurationSource() == ConfigurationSource.Explicit) { continue; } var inverse = conflictingSkipNavigation.Inverse; if (inverse?.Builder != null && inverse.GetConfigurationSource() != ConfigurationSource.Explicit) { inverse.DeclaringEntityType.Builder.HasNoSkipNavigation(inverse, configurationSource.Value); } conflictingSkipNavigation.DeclaringEntityType.Builder.HasNoSkipNavigation( conflictingSkipNavigation, configurationSource.Value); } } builder = Metadata.AddServiceProperty(memberInfo, configurationSource.Value).Builder; if (detachedProperties != null) { foreach (var detachedProperty in detachedProperties) { detachedProperty.Attach(this); } } } return builder.Metadata.Builder == null ? Metadata.FindServiceProperty(propertyName)?.Builder : builder; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanHaveServiceProperty([NotNull] MemberInfo memberInfo, ConfigurationSource? configurationSource) { var existingProperty = Metadata.FindServiceProperty(memberInfo); return existingProperty != null ? existingProperty.DeclaringEntityType == Metadata || (configurationSource.HasValue && configurationSource.Value.Overrides(existingProperty.GetConfigurationSource())) : CanAddServiceProperty(memberInfo, configurationSource); } private bool CanAddServiceProperty([NotNull] MemberInfo memberInfo, ConfigurationSource? configurationSource) { var propertyName = memberInfo.GetSimpleMemberName(); if (!configurationSource.HasValue || IsIgnored(propertyName, configurationSource)) { return false; } foreach (var conflictingProperty in Metadata.FindMembersInHierarchy(propertyName)) { if (!configurationSource.Overrides(conflictingProperty.GetConfigurationSource()) && (!(conflictingProperty is ServiceProperty derivedServiceProperty) || !memberInfo.IsOverridenBy(derivedServiceProperty.GetIdentifyingMemberInfo()))) { return false; } } return true; } private static InternalServicePropertyBuilder DetachServiceProperty(ServiceProperty serviceProperty) { var builder = serviceProperty?.Builder; if (builder == null) { return null; } serviceProperty.DeclaringEntityType.RemoveServiceProperty(serviceProperty); return builder; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanHaveNavigation([NotNull] string navigationName, ConfigurationSource? configurationSource) => !IsIgnored(navigationName, configurationSource) && Metadata.FindPropertiesInHierarchy(navigationName).Cast<IConventionPropertyBase>() .Concat(Metadata.FindServicePropertiesInHierarchy(navigationName)) .Concat(Metadata.FindSkipNavigationsInHierarchy(navigationName)) .All(m => configurationSource.Overrides(m.GetConfigurationSource())); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanHaveSkipNavigation([NotNull] string skipNavigationName, ConfigurationSource? configurationSource) => !IsIgnored(skipNavigationName, configurationSource) && Metadata.FindPropertiesInHierarchy(skipNavigationName).Cast<IConventionPropertyBase>() .Concat(Metadata.FindServicePropertiesInHierarchy(skipNavigationName)) .Concat(Metadata.FindNavigationsInHierarchy(skipNavigationName)) .All(m => configurationSource.Overrides(m.GetConfigurationSource())); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool IsIgnored([NotNull] string name, ConfigurationSource? configurationSource) { Check.NotEmpty(name, nameof(name)); return configurationSource != ConfigurationSource.Explicit && !configurationSource.OverridesStrictly(Metadata.FindIgnoredConfigurationSource(name)); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder Ignore([NotNull] string name, ConfigurationSource configurationSource) { var ignoredConfigurationSource = Metadata.FindIgnoredConfigurationSource(name); if (ignoredConfigurationSource.HasValue) { if (ignoredConfigurationSource.Value.Overrides(configurationSource)) { return this; } } else if (!CanIgnore(name, configurationSource, shouldThrow: true)) { return null; } using (Metadata.Model.ConventionDispatcher.DelayConventions()) { Metadata.AddIgnored(name, configurationSource); var navigation = Metadata.FindNavigation(name); if (navigation != null) { var foreignKey = navigation.ForeignKey; Check.DebugAssert(navigation.DeclaringEntityType == Metadata, "navigation.DeclaringEntityType != Metadata"); var navigationConfigurationSource = navigation.GetConfigurationSource(); if (foreignKey.GetConfigurationSource() != navigationConfigurationSource) { var removedNavigation = foreignKey.Builder.HasNavigation( (MemberInfo)null, navigation.IsOnDependent, configurationSource); Check.DebugAssert(removedNavigation != null, "removedNavigation is null"); } else { var removedForeignKey = foreignKey.DeclaringEntityType.Builder.HasNoRelationship( foreignKey, configurationSource); Check.DebugAssert(removedForeignKey != null, "removedForeignKey is null"); } } else { var property = Metadata.FindProperty(name); if (property != null) { Check.DebugAssert(property.DeclaringEntityType == Metadata, "property.DeclaringEntityType != Metadata"); var removedProperty = RemoveProperty(property, configurationSource); Check.DebugAssert(removedProperty != null, "removedProperty is null"); } else { var skipNavigation = Metadata.FindSkipNavigation(name); if (skipNavigation != null) { var inverse = skipNavigation.Inverse; if (inverse?.Builder != null && inverse.GetConfigurationSource() != ConfigurationSource.Explicit) { inverse.DeclaringEntityType.Builder.HasNoSkipNavigation(inverse, configurationSource); } Check.DebugAssert( skipNavigation.DeclaringEntityType == Metadata, "skipNavigation.DeclaringEntityType != Metadata"); Metadata.Builder.HasNoSkipNavigation(skipNavigation, configurationSource); } else { var serviceProperty = Metadata.FindServiceProperty(name); if (serviceProperty != null) { Check.DebugAssert( serviceProperty.DeclaringEntityType == Metadata, "serviceProperty.DeclaringEntityType != Metadata"); Metadata.RemoveServiceProperty(serviceProperty); } } } } foreach (var derivedType in Metadata.GetDerivedTypes()) { var derivedIgnoredSource = derivedType.FindDeclaredIgnoredConfigurationSource(name); if (derivedIgnoredSource.HasValue) { if (configurationSource.Overrides(derivedIgnoredSource)) { derivedType.RemoveIgnored(name); } continue; } var derivedNavigation = derivedType.FindDeclaredNavigation(name); if (derivedNavigation != null) { var foreignKey = derivedNavigation.ForeignKey; if (foreignKey.GetConfigurationSource() != derivedNavigation.GetConfigurationSource()) { if (derivedNavigation.GetConfigurationSource() != ConfigurationSource.Explicit) { foreignKey.Builder.HasNavigation( (MemberInfo)null, derivedNavigation.IsOnDependent, configurationSource); } } else if (foreignKey.GetConfigurationSource() != ConfigurationSource.Explicit) { foreignKey.DeclaringEntityType.Builder.HasNoRelationship( foreignKey, configurationSource); } } else { var derivedProperty = derivedType.FindDeclaredProperty(name); if (derivedProperty != null) { derivedType.Builder.RemoveProperty( derivedProperty, configurationSource, canOverrideSameSource: configurationSource != ConfigurationSource.Explicit); } else { var skipNavigation = derivedType.FindDeclaredSkipNavigation(name); if (skipNavigation != null) { var inverse = skipNavigation.Inverse; if (inverse?.Builder != null && inverse.GetConfigurationSource() != ConfigurationSource.Explicit) { inverse.DeclaringEntityType.Builder.HasNoSkipNavigation(inverse, configurationSource); } if (skipNavigation.GetConfigurationSource() != ConfigurationSource.Explicit) { derivedType.Builder.HasNoSkipNavigation(skipNavigation, configurationSource); } } else { var derivedServiceProperty = derivedType.FindDeclaredServiceProperty(name); if (derivedServiceProperty != null && configurationSource.Overrides(derivedServiceProperty.GetConfigurationSource()) && derivedServiceProperty.GetConfigurationSource() != ConfigurationSource.Explicit) { derivedType.RemoveServiceProperty(name); } } } } } } return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanIgnore([NotNull] string name, ConfigurationSource configurationSource) => CanIgnore(name, configurationSource, shouldThrow: false); private bool CanIgnore(string name, ConfigurationSource configurationSource, bool shouldThrow) { var ignoredConfigurationSource = Metadata.FindIgnoredConfigurationSource(name); if (ignoredConfigurationSource.HasValue) { return true; } var navigation = Metadata.FindNavigation(name); if (navigation != null) { if (navigation.DeclaringEntityType != Metadata) { if (shouldThrow) { throw new InvalidOperationException( CoreStrings.InheritedPropertyCannotBeIgnored( name, Metadata.DisplayName(), navigation.DeclaringEntityType.DisplayName())); } return false; } if (!configurationSource.Overrides(navigation.GetConfigurationSource())) { return false; } } else { var property = Metadata.FindProperty(name); if (property != null) { if (property.DeclaringEntityType != Metadata) { if (shouldThrow) { throw new InvalidOperationException( CoreStrings.InheritedPropertyCannotBeIgnored( name, Metadata.DisplayName(), property.DeclaringEntityType.DisplayName())); } return false; } if (!property.DeclaringEntityType.Builder.CanRemoveProperty( property, configurationSource, canOverrideSameSource: true)) { return false; } } else { var skipNavigation = Metadata.FindSkipNavigation(name); if (skipNavigation != null) { if (skipNavigation.DeclaringEntityType != Metadata) { if (shouldThrow) { throw new InvalidOperationException( CoreStrings.InheritedPropertyCannotBeIgnored( name, Metadata.DisplayName(), skipNavigation.DeclaringEntityType.DisplayName())); } return false; } if (!configurationSource.Overrides(skipNavigation.GetConfigurationSource())) { return false; } } else { var serviceProperty = Metadata.FindServiceProperty(name); if (serviceProperty != null) { if (serviceProperty.DeclaringEntityType != Metadata) { if (shouldThrow) { throw new InvalidOperationException( CoreStrings.InheritedPropertyCannotBeIgnored( name, Metadata.DisplayName(), serviceProperty.DeclaringEntityType.DisplayName())); } return false; } if (!configurationSource.Overrides(serviceProperty.GetConfigurationSource())) { return false; } } } } } return true; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder HasQueryFilter( [CanBeNull] LambdaExpression filter, ConfigurationSource configurationSource) { if (CanSetQueryFilter(filter, configurationSource)) { Metadata.SetQueryFilter(filter, configurationSource); return this; } return null; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanSetQueryFilter([CanBeNull] LambdaExpression filter, ConfigurationSource configurationSource) => configurationSource.Overrides(Metadata.GetQueryFilterConfigurationSource()) || Metadata.GetQueryFilter() == filter; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [Obsolete] public virtual InternalEntityTypeBuilder HasDefiningQuery( [CanBeNull] LambdaExpression query, ConfigurationSource configurationSource) { if (CanSetDefiningQuery(query, configurationSource)) { Metadata.SetDefiningQuery(query, configurationSource); return this; } return null; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [Obsolete] public virtual bool CanSetDefiningQuery([CanBeNull] LambdaExpression query, ConfigurationSource configurationSource) => configurationSource.Overrides(Metadata.GetDefiningQueryConfigurationSource()) || Metadata.GetDefiningQuery() == query; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder HasBaseType([CanBeNull] Type baseEntityType, ConfigurationSource configurationSource) { if (baseEntityType == null) { return HasBaseType((EntityType)null, configurationSource); } var baseType = ModelBuilder.Entity(baseEntityType, configurationSource); return baseType == null ? null : HasBaseType(baseType.Metadata, configurationSource); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder HasBaseType([CanBeNull] string baseEntityTypeName, ConfigurationSource configurationSource) { if (baseEntityTypeName == null) { return HasBaseType((EntityType)null, configurationSource); } var baseType = ModelBuilder.Entity(baseEntityTypeName, configurationSource); return baseType == null ? null : HasBaseType(baseType.Metadata, configurationSource); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder HasBaseType( [CanBeNull] EntityType baseEntityType, ConfigurationSource configurationSource) { if (Metadata.BaseType == baseEntityType) { Metadata.SetBaseType(baseEntityType, configurationSource); return this; } if (!CanSetBaseType(baseEntityType, configurationSource)) { return null; } using (Metadata.Model.ConventionDispatcher.DelayConventions()) { List<RelationshipSnapshot> detachedRelationships = null; List<InternalSkipNavigationBuilder> detachedSkipNavigations = null; PropertiesSnapshot detachedProperties = null; List<InternalServicePropertyBuilder> detachedServiceProperties = null; IReadOnlyList<(InternalKeyBuilder, ConfigurationSource?)> detachedKeys = null; // We use at least DataAnnotation as ConfigurationSource while removing to allow us // to remove metadata object which were defined in derived type // while corresponding annotations were present on properties in base type. var configurationSourceForRemoval = ConfigurationSource.DataAnnotation.Max(configurationSource); if (baseEntityType != null) { var baseMemberNames = baseEntityType.GetMembers() .ToDictionary(m => m.Name, m => (ConfigurationSource?)m.GetConfigurationSource()); var relationshipsToBeDetached = FindConflictingMembers( Metadata.GetDerivedTypesInclusive().SelectMany(et => et.GetDeclaredNavigations()), baseMemberNames, n => { var baseNavigation = baseEntityType.FindNavigation(n.Name); return baseNavigation != null && n.TargetEntityType == baseNavigation.TargetEntityType; }, n => n.ForeignKey.DeclaringEntityType.RemoveForeignKey(n.ForeignKey)) ?.Select(n => n.ForeignKey).ToHashSet(); foreach (var key in Metadata.GetDeclaredKeys().ToList()) { foreach (var referencingForeignKey in key.GetReferencingForeignKeys().ToList()) { var navigationToDependent = referencingForeignKey.PrincipalToDependent; if (navigationToDependent != null && baseMemberNames.TryGetValue(navigationToDependent.Name, out var baseConfigurationSource) && baseConfigurationSource == ConfigurationSource.Explicit && configurationSource == ConfigurationSource.Explicit && navigationToDependent.GetConfigurationSource() == ConfigurationSource.Explicit) { var baseProperty = baseEntityType.FindMembersInHierarchy(navigationToDependent.Name).Single(); if (!(baseProperty is INavigation)) { throw new InvalidOperationException( CoreStrings.DuplicatePropertiesOnBase( Metadata.DisplayName(), baseEntityType.DisplayName(), navigationToDependent.DeclaringType.DisplayName(), navigationToDependent.Name, baseProperty.DeclaringType.DisplayName(), baseProperty.Name)); } } if (relationshipsToBeDetached == null) { relationshipsToBeDetached = new HashSet<ForeignKey>(); } relationshipsToBeDetached.Add(referencingForeignKey); } } if (relationshipsToBeDetached != null) { detachedRelationships = new List<RelationshipSnapshot>(); foreach (var relationshipToBeDetached in relationshipsToBeDetached) { detachedRelationships.Add(DetachRelationship(relationshipToBeDetached)); } } var foreignKeysUsingKeyProperties = Metadata.GetDerivedTypesInclusive() .SelectMany(t => t.GetDeclaredForeignKeys()) .Where(fk => fk.Properties.Any(p => baseEntityType.FindProperty(p.Name)?.IsKey() == true)); foreach (var foreignKeyUsingKeyProperties in foreignKeysUsingKeyProperties.ToList()) { foreignKeyUsingKeyProperties.Builder.HasForeignKey((IReadOnlyList<Property>)null, configurationSourceForRemoval); } var skipNavigationsToDetach = FindConflictingMembers( Metadata.GetDerivedTypesInclusive().SelectMany(et => et.GetDeclaredSkipNavigations()), baseMemberNames, n => { var baseNavigation = baseEntityType.FindSkipNavigation(n.Name); return baseNavigation != null && n.TargetEntityType == baseNavigation.TargetEntityType; }, n => n.DeclaringEntityType.Builder.HasNoSkipNavigation(n, ConfigurationSource.Explicit)); if (skipNavigationsToDetach != null) { detachedSkipNavigations = new List<InternalSkipNavigationBuilder>(); foreach (var skipNavigation in skipNavigationsToDetach) { detachedSkipNavigations.Add(DetachSkipNavigation(skipNavigation)); } } detachedKeys = DetachKeys(Metadata.GetDeclaredKeys()); Metadata.SetIsKeyless(false, configurationSource); var propertiesToDetach = FindConflictingMembers( Metadata.GetDerivedTypesInclusive().SelectMany(et => et.GetDeclaredProperties()), baseMemberNames, n => baseEntityType.FindProperty(n.Name) != null, p => p.DeclaringEntityType.Builder.RemoveProperty(p, ConfigurationSource.Explicit)); if (propertiesToDetach != null) { detachedProperties = DetachProperties(propertiesToDetach); } var servicePropertiesToDetach = FindConflictingMembers( Metadata.GetDerivedTypesInclusive().SelectMany(et => et.GetDeclaredServiceProperties()), baseMemberNames, n => baseEntityType.FindServiceProperty(n.Name) != null, p => p.DeclaringEntityType.RemoveServiceProperty(p)); if (servicePropertiesToDetach != null) { detachedServiceProperties = new List<InternalServicePropertyBuilder>(); foreach (var serviceProperty in servicePropertiesToDetach) { detachedServiceProperties.Add(DetachServiceProperty(serviceProperty)); } } foreach (var ignoredMember in Metadata.GetIgnoredMembers().ToList()) { if (baseEntityType.FindIgnoredConfigurationSource(ignoredMember) .Overrides(Metadata.FindDeclaredIgnoredConfigurationSource(ignoredMember))) { Metadata.RemoveIgnored(ignoredMember); } } baseEntityType.UpdateConfigurationSource(configurationSource); } List<InternalIndexBuilder> detachedIndexes = null; HashSet<Property> removedInheritedPropertiesToDuplicate = null; if (Metadata.BaseType != null) { var removedInheritedProperties = new HashSet<Property>( Metadata.BaseType.GetProperties() .Where(p => baseEntityType == null || baseEntityType.FindProperty(p.Name) != p)); if (removedInheritedProperties.Count != 0) { removedInheritedPropertiesToDuplicate = new HashSet<Property>(); List<ForeignKey> relationshipsToBeDetached = null; foreach (var foreignKey in Metadata.GetDerivedTypesInclusive() .SelectMany(t => t.GetDeclaredForeignKeys())) { var shouldBeDetached = false; foreach (var property in foreignKey.Properties) { if (removedInheritedProperties.Contains(property)) { removedInheritedPropertiesToDuplicate.Add(property); shouldBeDetached = true; } } if (!shouldBeDetached) { continue; } if (relationshipsToBeDetached == null) { relationshipsToBeDetached = new List<ForeignKey>(); } relationshipsToBeDetached.Add(foreignKey); } foreach (var key in Metadata.GetKeys()) { if (key.ReferencingForeignKeys == null || !key.ReferencingForeignKeys.Any() || !key.Properties.Any(p => removedInheritedProperties.Contains(p))) { continue; } foreach (var referencingForeignKey in key.ReferencingForeignKeys.ToList()) { if (Metadata.IsAssignableFrom(referencingForeignKey.PrincipalEntityType)) { if (relationshipsToBeDetached == null) { relationshipsToBeDetached = new List<ForeignKey>(); } relationshipsToBeDetached.Add(referencingForeignKey); } } } if (relationshipsToBeDetached != null) { detachedRelationships = new List<RelationshipSnapshot>(); foreach (var relationshipToBeDetached in relationshipsToBeDetached) { detachedRelationships.Add(DetachRelationship(relationshipToBeDetached)); } } List<Index> indexesToBeDetached = null; foreach (var index in Metadata.GetDerivedTypesInclusive().SelectMany(e => e.GetDeclaredIndexes())) { var shouldBeDetached = false; foreach (var property in index.Properties) { if (removedInheritedProperties.Contains(property)) { removedInheritedPropertiesToDuplicate.Add(property); shouldBeDetached = true; } } if (!shouldBeDetached) { continue; } if (indexesToBeDetached == null) { indexesToBeDetached = new List<Index>(); } indexesToBeDetached.Add(index); } if (indexesToBeDetached != null) { detachedIndexes = new List<InternalIndexBuilder>(); foreach (var indexToBeDetached in indexesToBeDetached) { detachedIndexes.Add(DetachIndex(indexToBeDetached)); } } } } Metadata.SetBaseType(baseEntityType, configurationSource); if (removedInheritedPropertiesToDuplicate != null) { foreach (var property in removedInheritedPropertiesToDuplicate) { property.Builder?.Attach(this); } } if (detachedServiceProperties != null) { foreach (var detachedServiceProperty in detachedServiceProperties) { detachedServiceProperty.Attach(detachedServiceProperty.Metadata.DeclaringEntityType.Builder); } } detachedProperties?.Attach(this); if (detachedKeys != null) { foreach (var detachedKeyTuple in detachedKeys) { detachedKeyTuple.Item1.Attach(Metadata.RootType().Builder, detachedKeyTuple.Item2); } } if (detachedIndexes != null) { foreach (var detachedIndex in detachedIndexes) { detachedIndex.Attach(detachedIndex.Metadata.DeclaringEntityType.Builder); } } if (detachedSkipNavigations != null) { foreach (var detachedSkipNavigation in detachedSkipNavigations) { detachedSkipNavigation.Attach(); } } if (detachedRelationships != null) { foreach (var detachedRelationship in detachedRelationships) { detachedRelationship.Attach(); } } } return this; List<T> FindConflictingMembers<T>( IEnumerable<T> derivedMembers, Dictionary<string, ConfigurationSource?> baseMemberNames, Func<T, bool> compatibleWithBaseMember, Action<T> removeMember) where T : PropertyBase { List<T> membersToBeDetached = null; List<T> membersToBeRemoved = null; foreach (var member in derivedMembers) { ConfigurationSource? baseConfigurationSource = null; if ((!member.GetConfigurationSource().OverridesStrictly( baseEntityType.FindIgnoredConfigurationSource(member.Name)) && member.GetConfigurationSource() != ConfigurationSource.Explicit) || (baseMemberNames.TryGetValue(member.Name, out baseConfigurationSource) && baseConfigurationSource.Overrides(member.GetConfigurationSource()) && !compatibleWithBaseMember(member))) { if (baseConfigurationSource == ConfigurationSource.Explicit && configurationSource == ConfigurationSource.Explicit && member.GetConfigurationSource() == ConfigurationSource.Explicit) { continue; } if (membersToBeRemoved == null) { membersToBeRemoved = new List<T>(); } membersToBeRemoved.Add(member); continue; } if (baseConfigurationSource != null) { if (membersToBeDetached == null) { membersToBeDetached = new List<T>(); } membersToBeDetached.Add(member); } } if (membersToBeRemoved != null) { foreach (var memberToBeRemoved in membersToBeRemoved) { removeMember(memberToBeRemoved); } } return membersToBeDetached; } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanSetBaseType([NotNull] EntityType baseEntityType, ConfigurationSource configurationSource) { if (Metadata.BaseType == baseEntityType || configurationSource == ConfigurationSource.Explicit) { return true; } if (!configurationSource.Overrides(Metadata.GetBaseTypeConfigurationSource())) { return false; } if (baseEntityType == null) { return true; } var configurationSourceForRemoval = ConfigurationSource.DataAnnotation.Max(configurationSource); if (Metadata.GetDeclaredKeys().Any(k => !configurationSourceForRemoval.Overrides(k.GetConfigurationSource())) || (Metadata.IsKeyless && !configurationSource.Overrides(Metadata.GetIsKeylessConfigurationSource()))) { return false; } if (Metadata.GetDerivedTypesInclusive() .SelectMany(t => t.GetDeclaredForeignKeys()) .Where(fk => fk.Properties.Any(p => baseEntityType.FindProperty(p.Name)?.IsKey() == true)) .Any(fk => !configurationSourceForRemoval.Overrides(fk.GetPropertiesConfigurationSource()))) { return false; } var baseMembers = baseEntityType.GetMembers() .Where(m => m.GetConfigurationSource() == ConfigurationSource.Explicit) .ToDictionary(m => m.Name); foreach (var derivedMember in Metadata.GetDerivedTypesInclusive().SelectMany(et => et.GetDeclaredMembers())) { if (derivedMember.GetConfigurationSource() == ConfigurationSource.Explicit && baseMembers.TryGetValue(derivedMember.Name, out var baseMember)) { if (derivedMember is IProperty) { return baseMember is IProperty; } if (derivedMember is INavigation derivedNavigation) { return baseMember is INavigation baseNavigation && derivedNavigation.TargetEntityType == baseNavigation.TargetEntityType; } if (derivedMember is IServiceProperty) { return baseMember is IServiceProperty; } if (derivedMember is ISkipNavigation derivedSkipNavigation) { return baseMember is ISkipNavigation baseSkipNavigation && derivedSkipNavigation.TargetEntityType == baseSkipNavigation.TargetEntityType; } } } return true; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static PropertiesSnapshot DetachProperties([NotNull] IReadOnlyList<Property> propertiesToDetach) { if (propertiesToDetach.Count == 0) { return null; } List<RelationshipSnapshot> detachedRelationships = null; foreach (var propertyToDetach in propertiesToDetach) { foreach (var relationship in propertyToDetach.GetContainingForeignKeys().ToList()) { if (detachedRelationships == null) { detachedRelationships = new List<RelationshipSnapshot>(); } detachedRelationships.Add(DetachRelationship(relationship)); } } var detachedIndexes = DetachIndexes(propertiesToDetach.SelectMany(p => p.GetContainingIndexes()).Distinct()); var keysToDetach = propertiesToDetach.SelectMany(p => p.GetContainingKeys()).Distinct().ToList(); foreach (var key in keysToDetach) { foreach (var referencingForeignKey in key.GetReferencingForeignKeys().ToList()) { if (detachedRelationships == null) { detachedRelationships = new List<RelationshipSnapshot>(); } detachedRelationships.Add(DetachRelationship(referencingForeignKey)); } } var detachedKeys = DetachKeys(keysToDetach); var detachedProperties = new List<InternalPropertyBuilder>(); foreach (var propertyToDetach in propertiesToDetach) { var property = propertyToDetach.DeclaringEntityType.FindDeclaredProperty(propertyToDetach.Name); if (property != null) { var entityTypeBuilder = property.DeclaringEntityType.Builder; var propertyBuilder = property.Builder; // Reset convention configuration propertyBuilder.ValueGenerated(null, ConfigurationSource.Convention); propertyBuilder.AfterSave(null, ConfigurationSource.Convention); propertyBuilder.BeforeSave(null, ConfigurationSource.Convention); ConfigurationSource? removedConfigurationSource; if (entityTypeBuilder != null) { removedConfigurationSource = entityTypeBuilder .RemoveProperty(property, property.GetConfigurationSource()); } else { removedConfigurationSource = property.GetConfigurationSource(); property.DeclaringEntityType.RemoveProperty(property.Name); } Check.DebugAssert(removedConfigurationSource.HasValue, "removedConfigurationSource.HasValue is false"); detachedProperties.Add(propertyBuilder); } } return new PropertiesSnapshot(detachedProperties, detachedIndexes, detachedKeys, detachedRelationships); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanRemoveForeignKey([NotNull] ForeignKey foreignKey, ConfigurationSource configurationSource) { Check.DebugAssert(foreignKey.DeclaringEntityType == Metadata, "foreignKey.DeclaringEntityType != Metadata"); return configurationSource.Overrides(foreignKey.GetConfigurationSource()); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanRemoveSkipNavigation([NotNull] SkipNavigation skipNavigation, ConfigurationSource? configurationSource) { Check.DebugAssert(skipNavigation.DeclaringEntityType == Metadata, "skipNavigation.DeclaringEntityType != Metadata"); return configurationSource.Overrides(skipNavigation.GetConfigurationSource()); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static RelationshipSnapshot DetachRelationship([NotNull] ForeignKey foreignKey) => DetachRelationship(foreignKey, false); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static RelationshipSnapshot DetachRelationship([NotNull] ForeignKey foreignKey, bool includeDefinedType) { var detachedBuilder = foreignKey.Builder; var referencingSkipNavigations = foreignKey.ReferencingSkipNavigations? .Select(s => (s, s.GetForeignKeyConfigurationSource().Value)).ToList(); var relationshipConfigurationSource = foreignKey.DeclaringEntityType.Builder .HasNoRelationship(foreignKey, foreignKey.GetConfigurationSource()); Check.DebugAssert(relationshipConfigurationSource != null, "relationshipConfigurationSource is null"); EntityType.Snapshot definedSnapshot = null; if (includeDefinedType) { var dependentEntityType = foreignKey.DeclaringEntityType; if (dependentEntityType.DefiningEntityType == foreignKey.PrincipalEntityType && dependentEntityType.DefiningNavigationName == foreignKey.PrincipalToDependent?.Name) { definedSnapshot = DetachAllMembers(dependentEntityType); dependentEntityType.Model.Builder.HasNoEntityType(dependentEntityType, ConfigurationSource.Explicit); } } return new RelationshipSnapshot(detachedBuilder, definedSnapshot, referencingSkipNavigations); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder HasNoRelationship( [NotNull] ForeignKey foreignKey, ConfigurationSource configurationSource) { if (foreignKey.Builder == null) { return this; } var currentConfigurationSource = foreignKey.GetConfigurationSource(); if (!configurationSource.Overrides(currentConfigurationSource)) { return null; } if (foreignKey.ReferencingSkipNavigations != null) { foreach (var referencingSkipNavigation in foreignKey.ReferencingSkipNavigations.ToList()) { Check.DebugAssert( currentConfigurationSource.Overrides(referencingSkipNavigation.GetForeignKeyConfigurationSource()), "Setting the FK on the skip navigation should upgrade the configuration source"); referencingSkipNavigation.Builder.HasForeignKey(null, configurationSource); } } if (foreignKey.Builder == null) { return this; } Metadata.RemoveForeignKey(foreignKey); RemoveUnusedImplicitProperties(foreignKey.Properties); foreignKey.PrincipalKey.DeclaringEntityType.Builder?.RemoveKeyIfUnused(foreignKey.PrincipalKey); return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static EntityType.Snapshot DetachAllMembers([NotNull] EntityType entityType) { if (entityType.Builder == null) { return null; } if (entityType.HasDefiningNavigation()) { entityType.Model.AddDetachedEntityType( entityType.Name, entityType.DefiningNavigationName, entityType.DefiningEntityType.Name); } List<RelationshipSnapshot> detachedRelationships = null; foreach (var relationshipToBeDetached in entityType.GetDeclaredForeignKeys().ToList()) { if (detachedRelationships == null) { detachedRelationships = new List<RelationshipSnapshot>(); } var detachedRelationship = DetachRelationship(relationshipToBeDetached); if (detachedRelationship.Relationship.Metadata.GetConfigurationSource().Overrides(ConfigurationSource.DataAnnotation) || relationshipToBeDetached.IsOwnership) { detachedRelationships.Add(detachedRelationship); } } List<InternalSkipNavigationBuilder> detachedSkipNavigations = null; foreach (var skipNavigationsToBeDetached in entityType.GetDeclaredSkipNavigations().ToList()) { if (detachedSkipNavigations == null) { detachedSkipNavigations = new List<InternalSkipNavigationBuilder>(); } detachedSkipNavigations.Add(DetachSkipNavigation(skipNavigationsToBeDetached)); } List<(InternalKeyBuilder, ConfigurationSource?)> detachedKeys = null; foreach (var keyToDetach in entityType.GetDeclaredKeys().ToList()) { foreach (var relationshipToBeDetached in keyToDetach.GetReferencingForeignKeys().ToList()) { if (detachedRelationships == null) { detachedRelationships = new List<RelationshipSnapshot>(); } var detachedRelationship = DetachRelationship(relationshipToBeDetached, true); if (detachedRelationship.Relationship.Metadata.GetConfigurationSource().Overrides(ConfigurationSource.DataAnnotation) || relationshipToBeDetached.IsOwnership) { detachedRelationships.Add(detachedRelationship); } } if (keyToDetach.Builder == null) { continue; } if (detachedKeys == null) { detachedKeys = new List<(InternalKeyBuilder, ConfigurationSource?)>(); } var detachedKey = DetachKey(keyToDetach); if (detachedKey.Item1.Metadata.GetConfigurationSource().Overrides(ConfigurationSource.Explicit)) { detachedKeys.Add(detachedKey); } } List<InternalIndexBuilder> detachedIndexes = null; foreach (var index in entityType.GetDeclaredIndexes().ToList()) { if (detachedIndexes == null) { detachedIndexes = new List<InternalIndexBuilder>(); } var detachedIndex = DetachIndex(index); if (detachedIndex.Metadata.GetConfigurationSource().Overrides(ConfigurationSource.Explicit)) { detachedIndexes.Add(detachedIndex); } } var detachedProperties = DetachProperties(entityType.GetDeclaredProperties().ToList()); List<InternalServicePropertyBuilder> detachedServiceProperties = null; foreach (var servicePropertiesToBeDetached in entityType.GetDeclaredServiceProperties().ToList()) { if (detachedServiceProperties == null) { detachedServiceProperties = new List<InternalServicePropertyBuilder>(); } detachedServiceProperties.Add(DetachServiceProperty(servicePropertiesToBeDetached)); } return new EntityType.Snapshot( entityType, detachedProperties, detachedIndexes, detachedKeys, detachedRelationships, detachedSkipNavigations, detachedServiceProperties); } private void RemoveKeyIfUnused(Key key, ConfigurationSource configurationSource = ConfigurationSource.Convention) { if (Metadata.FindPrimaryKey() == key || key.ReferencingForeignKeys?.Any() == true) { return; } HasNoKey(key, configurationSource); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder RemoveUnusedImplicitProperties<T>([NotNull] IReadOnlyList<T> properties) where T : class, IConventionProperty { foreach (var property in properties) { if (property?.Builder != null && property.IsImplicitlyCreated()) { RemovePropertyIfUnused((Property)(object)property, ConfigurationSource.Convention); } } return this; } private static void RemovePropertyIfUnused(Property property, ConfigurationSource configurationSource) { if (property.Builder == null || !property.DeclaringEntityType.Builder.CanRemoveProperty(property, configurationSource) || property.GetContainingIndexes().Any() || property.GetContainingForeignKeys().Any() || property.GetContainingKeys().Any()) { return; } var removedProperty = property.DeclaringEntityType.RemoveProperty(property.Name); Check.DebugAssert(removedProperty == property, "removedProperty != property"); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalIndexBuilder HasIndex([NotNull] IReadOnlyList<string> propertyNames, ConfigurationSource configurationSource) => HasIndex(GetOrCreateProperties(propertyNames, configurationSource), configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalIndexBuilder HasIndex( [NotNull] IReadOnlyList<string> propertyNames, [NotNull] string name, ConfigurationSource configurationSource) => HasIndex(GetOrCreateProperties(propertyNames, configurationSource), name, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalIndexBuilder HasIndex( [NotNull] IReadOnlyList<MemberInfo> clrMembers, ConfigurationSource configurationSource) => HasIndex(GetOrCreateProperties(clrMembers, configurationSource), configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalIndexBuilder HasIndex( [NotNull] IReadOnlyList<MemberInfo> clrMembers, [NotNull] string name, ConfigurationSource configurationSource) => HasIndex(GetOrCreateProperties(clrMembers, configurationSource), name, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalIndexBuilder HasIndex( [CanBeNull] IReadOnlyList<Property> properties, ConfigurationSource configurationSource) { if (properties == null) { return null; } List<InternalIndexBuilder> detachedIndexes = null; var existingIndex = Metadata.FindIndex(properties); if (existingIndex == null) { detachedIndexes = Metadata.FindDerivedIndexes(properties).ToList().Select(DetachIndex).ToList(); } else if (existingIndex.DeclaringEntityType != Metadata) { return existingIndex.DeclaringEntityType.Builder.HasIndex(existingIndex, properties, null, configurationSource); } var indexBuilder = HasIndex(existingIndex, properties, null, configurationSource); if (detachedIndexes != null) { foreach (var detachedIndex in detachedIndexes) { detachedIndex.Attach(detachedIndex.Metadata.DeclaringEntityType.Builder); } } return indexBuilder; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalIndexBuilder HasIndex( [CanBeNull] IReadOnlyList<Property> properties, [NotNull] string name, ConfigurationSource configurationSource) { Check.NotEmpty(name, nameof(name)); if (properties == null) { return null; } List<InternalIndexBuilder> detachedIndexes = null; var existingIndex = Metadata.FindIndex(name); if (existingIndex != null && !existingIndex.Properties.SequenceEqual(properties)) { // use existing index only if properties match existingIndex = null; } if (existingIndex == null) { detachedIndexes = Metadata.FindDerivedIndexes(name) .Where(i => i.Properties.SequenceEqual(properties)) .ToList().Select(DetachIndex).ToList(); } else if (existingIndex.DeclaringEntityType != Metadata) { return existingIndex.DeclaringEntityType.Builder.HasIndex(existingIndex, properties, name, configurationSource); } var indexBuilder = HasIndex(existingIndex, properties, name, configurationSource); if (detachedIndexes != null) { foreach (var detachedIndex in detachedIndexes) { detachedIndex.Attach(detachedIndex.Metadata.DeclaringEntityType.Builder); } } return indexBuilder; } private InternalIndexBuilder HasIndex( Index index, IReadOnlyList<Property> properties, string name, ConfigurationSource configurationSource) { if (index == null) { if (name == null) { index = Metadata.AddIndex(properties, configurationSource); } else { index = Metadata.AddIndex(properties, name, configurationSource); } } else { index.UpdateConfigurationSource(configurationSource); } return index?.Builder; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder HasNoIndex([NotNull] Index index, ConfigurationSource configurationSource) { var currentConfigurationSource = index.GetConfigurationSource(); if (!configurationSource.Overrides(currentConfigurationSource)) { return null; } var removedIndex = index.Name == null ? Metadata.RemoveIndex(index.Properties) : Metadata.RemoveIndex(index.Name); Check.DebugAssert(removedIndex == index, "removedIndex != index"); RemoveUnusedImplicitProperties(index.Properties); return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanRemoveIndex([NotNull] Index index, ConfigurationSource configurationSource) => configurationSource.Overrides(index.GetConfigurationSource()); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public static List<InternalIndexBuilder> DetachIndexes([NotNull] IEnumerable<Index> indexesToDetach) { var indexesToDetachList = (indexesToDetach as List<Index>) ?? indexesToDetach.ToList(); if (indexesToDetachList.Count == 0) { return null; } var detachedIndexes = new List<InternalIndexBuilder>(); foreach (var indexToDetach in indexesToDetachList) { var detachedIndex = DetachIndex(indexToDetach); detachedIndexes.Add(detachedIndex); } return detachedIndexes; } private static InternalIndexBuilder DetachIndex(Index indexToDetach) { var entityTypeBuilder = indexToDetach.DeclaringEntityType.Builder; var indexBuilder = indexToDetach.Builder; var removedConfigurationSource = entityTypeBuilder.HasNoIndex(indexToDetach, indexToDetach.GetConfigurationSource()); Check.DebugAssert(removedConfigurationSource != null, "removedConfigurationSource is null"); return indexBuilder; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasRelationship( [NotNull] string principalEntityTypeName, [NotNull] IReadOnlyList<string> propertyNames, ConfigurationSource configurationSource) { Check.NotEmpty(principalEntityTypeName, nameof(principalEntityTypeName)); Check.NotEmpty(propertyNames, nameof(propertyNames)); var principalTypeBuilder = ModelBuilder.Entity(principalEntityTypeName, configurationSource); var principalKey = principalTypeBuilder?.Metadata.FindPrimaryKey(); return principalTypeBuilder == null ? null : HasForeignKey( principalTypeBuilder.Metadata, GetOrCreateProperties( propertyNames, configurationSource, principalKey?.Properties, useDefaultType: principalKey == null), null, configurationSource); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasRelationship( [NotNull] string principalEntityTypeName, [NotNull] IReadOnlyList<string> propertyNames, [NotNull] Key principalKey, ConfigurationSource configurationSource) { Check.NotEmpty(principalEntityTypeName, nameof(principalEntityTypeName)); Check.NotEmpty(propertyNames, nameof(propertyNames)); var principalTypeBuilder = ModelBuilder.Entity(principalEntityTypeName, configurationSource); return principalTypeBuilder == null ? null : HasForeignKey( principalTypeBuilder.Metadata, GetOrCreateProperties(propertyNames, configurationSource, principalKey.Properties), principalKey, configurationSource); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasRelationship( [NotNull] Type principalClrType, [NotNull] IReadOnlyList<MemberInfo> clrMembers, ConfigurationSource configurationSource) { Check.NotNull(principalClrType, nameof(principalClrType)); Check.NotEmpty(clrMembers, nameof(clrMembers)); var principalTypeBuilder = ModelBuilder.Entity(principalClrType, configurationSource); return principalTypeBuilder == null ? null : HasForeignKey( principalTypeBuilder.Metadata, GetOrCreateProperties(clrMembers, configurationSource), null, configurationSource); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasRelationship( [NotNull] Type principalClrType, [NotNull] IReadOnlyList<MemberInfo> clrMembers, [NotNull] Key principalKey, ConfigurationSource configurationSource) { Check.NotNull(principalClrType, nameof(principalClrType)); Check.NotEmpty(clrMembers, nameof(clrMembers)); var principalTypeBuilder = ModelBuilder.Entity(principalClrType, configurationSource); return principalTypeBuilder == null ? null : HasForeignKey( principalTypeBuilder.Metadata, GetOrCreateProperties(clrMembers, configurationSource), principalKey, configurationSource); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasRelationship( [NotNull] EntityType principalEntityType, [NotNull] IReadOnlyList<Property> dependentProperties, ConfigurationSource configurationSource) => HasForeignKey( principalEntityType, GetActualProperties(dependentProperties, configurationSource), null, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasRelationship( [NotNull] EntityType principalEntityType, [NotNull] IReadOnlyList<Property> dependentProperties, [CanBeNull] Key principalKey, ConfigurationSource configurationSource) => HasForeignKey( principalEntityType, GetActualProperties(dependentProperties, configurationSource), principalKey, configurationSource); private InternalForeignKeyBuilder HasForeignKey( EntityType principalEntityType, IReadOnlyList<Property> dependentProperties, Key principalKey, ConfigurationSource configurationSource) { if (dependentProperties == null) { return null; } var newRelationship = HasRelationshipInternal(principalEntityType, principalKey, configurationSource); var relationship = newRelationship.HasForeignKey(dependentProperties, configurationSource); if (relationship == null && newRelationship.Metadata.Builder != null) { HasNoRelationship(newRelationship.Metadata, configurationSource); } newRelationship = relationship; return newRelationship; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasRelationship( [NotNull] EntityType targetEntityType, [CanBeNull] string navigationName, ConfigurationSource configurationSource, bool? targetIsPrincipal = null) => HasRelationship( Check.NotNull(targetEntityType, nameof(targetEntityType)), MemberIdentity.Create(navigationName), null, targetIsPrincipal, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasRelationship( [NotNull] EntityType targetEntityType, [CanBeNull] MemberInfo navigationMember, ConfigurationSource configurationSource, bool? targetIsPrincipal = null) => HasRelationship( Check.NotNull(targetEntityType, nameof(targetEntityType)), MemberIdentity.Create(navigationMember), null, targetIsPrincipal, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasRelationship( [NotNull] EntityType targetEntityType, [CanBeNull] string navigationName, [CanBeNull] string inverseNavigationName, ConfigurationSource configurationSource, bool setTargetAsPrincipal = false) => HasRelationship( Check.NotNull(targetEntityType, nameof(targetEntityType)), MemberIdentity.Create(navigationName), MemberIdentity.Create(inverseNavigationName), setTargetAsPrincipal ? true : (bool?)null, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasRelationship( [NotNull] EntityType targetEntityType, [CanBeNull] MemberInfo navigation, [CanBeNull] MemberInfo inverseNavigation, ConfigurationSource configurationSource, bool setTargetAsPrincipal = false) => HasRelationship( Check.NotNull(targetEntityType, nameof(targetEntityType)), MemberIdentity.Create(navigation), MemberIdentity.Create(inverseNavigation), setTargetAsPrincipal ? true : (bool?)null, configurationSource); private InternalForeignKeyBuilder HasRelationship( EntityType targetEntityType, MemberIdentity? navigationToTarget, MemberIdentity? inverseNavigation, bool? setTargetAsPrincipal, ConfigurationSource configurationSource, bool? required = null) { Check.DebugAssert( navigationToTarget != null || inverseNavigation != null, "navigationToTarget == null and inverseNavigation == null"); Check.DebugAssert( setTargetAsPrincipal != null || required == null, "required should only be set if principal end is known"); var navigationProperty = navigationToTarget?.MemberInfo; if (setTargetAsPrincipal == false || (inverseNavigation == null && navigationProperty?.GetMemberType().IsAssignableFrom( targetEntityType.ClrType) == false)) { // Target is expected to be dependent or only one nav specified and it can't be the nav to principal return targetEntityType.Builder.HasRelationship( Metadata, null, navigationToTarget, !setTargetAsPrincipal, configurationSource, required); } var existingRelationship = InternalForeignKeyBuilder.FindCurrentForeignKeyBuilder( targetEntityType, Metadata, navigationToTarget, inverseNavigation, dependentProperties: null, principalProperties: null); if (existingRelationship != null) { var shouldInvert = false; // The dependent and principal sides could be in the same hierarchy so we need to use the navigations to determine // the expected principal side. // And since both sides are in the same hierarchy different navigations must have different names. if (navigationToTarget != null) { if (navigationToTarget.Value.Name == existingRelationship.Metadata.DependentToPrincipal?.Name) { existingRelationship.Metadata.UpdateDependentToPrincipalConfigurationSource(configurationSource); } else if (setTargetAsPrincipal == true) { shouldInvert = true; } else { existingRelationship.Metadata.UpdatePrincipalToDependentConfigurationSource(configurationSource); } if (navigationToTarget.Value.Name != null) { Metadata.RemoveIgnored(navigationToTarget.Value.Name); } } if (inverseNavigation != null) { if (inverseNavigation.Value.Name == existingRelationship.Metadata.PrincipalToDependent?.Name) { existingRelationship.Metadata.UpdatePrincipalToDependentConfigurationSource(configurationSource); } else if (setTargetAsPrincipal == true) { shouldInvert = true; } else { existingRelationship.Metadata.UpdateDependentToPrincipalConfigurationSource(configurationSource); } if (inverseNavigation.Value.Name != null) { targetEntityType.RemoveIgnored(inverseNavigation.Value.Name); } } existingRelationship.Metadata.UpdateConfigurationSource(configurationSource); if (!shouldInvert) { if (setTargetAsPrincipal == true) { existingRelationship = existingRelationship.HasEntityTypes( existingRelationship.Metadata.PrincipalEntityType, existingRelationship.Metadata.DeclaringEntityType, configurationSource); if (required.HasValue) { existingRelationship = existingRelationship.IsRequired(required.Value, configurationSource); } } return existingRelationship; } // If relationship should be inverted it will be handled below } else { existingRelationship = InternalForeignKeyBuilder.FindCurrentForeignKeyBuilder( Metadata, targetEntityType, inverseNavigation, navigationToTarget, dependentProperties: null, principalProperties: null); if (existingRelationship != null) { // Since the existing relationship didn't match the first case then the dependent and principal sides // are not in the same hierarchy therefore we don't need to check existing navigations if (navigationToTarget != null) { Check.DebugAssert( navigationToTarget.Value.Name == existingRelationship.Metadata.PrincipalToDependent?.Name, $"Expected {navigationToTarget.Value.Name}, found {existingRelationship.Metadata.PrincipalToDependent?.Name}"); existingRelationship.Metadata.UpdatePrincipalToDependentConfigurationSource(configurationSource); if (navigationToTarget.Value.Name != null) { Metadata.RemoveIgnored(navigationToTarget.Value.Name); } } if (inverseNavigation != null) { Check.DebugAssert( inverseNavigation.Value.Name == existingRelationship.Metadata.DependentToPrincipal?.Name, $"Expected {inverseNavigation.Value.Name}, found {existingRelationship.Metadata.DependentToPrincipal?.Name}"); existingRelationship.Metadata.UpdateDependentToPrincipalConfigurationSource(configurationSource); if (inverseNavigation.Value.Name != null) { targetEntityType.RemoveIgnored(inverseNavigation.Value.Name); } } existingRelationship.Metadata.UpdateConfigurationSource(configurationSource); if (setTargetAsPrincipal == null) { return existingRelationship; } } } InternalForeignKeyBuilder relationship; InternalForeignKeyBuilder newRelationship = null; using (var batcher = Metadata.Model.ConventionDispatcher.DelayConventions()) { if (existingRelationship != null) { relationship = existingRelationship; } else { if (setTargetAsPrincipal == true || targetEntityType.DefiningEntityType != Metadata) { newRelationship = CreateForeignKey( targetEntityType.Builder, dependentProperties: null, principalKey: null, propertyBaseName: navigationProperty?.GetSimpleMemberName(), required, configurationSource); } else { var navigation = navigationToTarget; navigationToTarget = inverseNavigation; inverseNavigation = navigation; navigationProperty = navigationToTarget?.MemberInfo; newRelationship = targetEntityType.Builder.CreateForeignKey( this, dependentProperties: null, principalKey: null, propertyBaseName: navigationProperty?.GetSimpleMemberName(), required: null, configurationSource); } relationship = newRelationship; } if (setTargetAsPrincipal == true) { relationship = relationship .HasEntityTypes(targetEntityType.Builder.Metadata, Metadata, configurationSource); if (required.HasValue) { relationship = relationship.IsRequired(required.Value, configurationSource); } } var inverseProperty = inverseNavigation?.MemberInfo; if (inverseNavigation == null) { relationship = navigationProperty != null ? relationship.HasNavigation( navigationProperty, pointsToPrincipal: true, configurationSource) : relationship.HasNavigation( navigationToTarget.Value.Name, pointsToPrincipal: true, configurationSource); } else if (navigationToTarget == null) { relationship = inverseProperty != null ? relationship.HasNavigation( inverseProperty, pointsToPrincipal: false, configurationSource) : relationship.HasNavigation( inverseNavigation.Value.Name, pointsToPrincipal: false, configurationSource); } else { relationship = navigationProperty != null || inverseProperty != null ? relationship.HasNavigations(navigationProperty, inverseProperty, configurationSource) : relationship.HasNavigations(navigationToTarget.Value.Name, inverseNavigation.Value.Name, configurationSource); } if (relationship != null) { relationship = batcher.Run(relationship); } } if (relationship != null && ((navigationToTarget != null && relationship.Metadata.DependentToPrincipal?.Name != navigationToTarget.Value.Name) || (inverseNavigation != null && relationship.Metadata.PrincipalToDependent?.Name != inverseNavigation.Value.Name)) && ((inverseNavigation != null && relationship.Metadata.DependentToPrincipal?.Name != inverseNavigation.Value.Name) || (navigationToTarget != null && relationship.Metadata.PrincipalToDependent?.Name != navigationToTarget.Value.Name))) { relationship = null; } if (relationship == null) { if (newRelationship?.Metadata.Builder != null) { newRelationship.Metadata.DeclaringEntityType.Builder.HasNoRelationship(newRelationship.Metadata, configurationSource); } return null; } return relationship; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasRelationship( [NotNull] EntityType principalEntityType, ConfigurationSource configurationSource, bool? required = null, [NotNull] string propertyBaseName = null) => HasRelationshipInternal(principalEntityType, principalKey: null, configurationSource, required, propertyBaseName); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasRelationship( [NotNull] EntityType principalEntityType, [NotNull] Key principalKey, ConfigurationSource configurationSource, bool? required = null, [NotNull] string propertyBaseName = null) => HasRelationshipInternal(principalEntityType, principalKey, configurationSource, required, propertyBaseName); private InternalForeignKeyBuilder HasRelationshipInternal( EntityType targetEntityType, Key principalKey, ConfigurationSource configurationSource, bool? required = null, string propertyBaseName = null) { InternalForeignKeyBuilder relationship; InternalForeignKeyBuilder newRelationship; using (var batch = Metadata.Model.ConventionDispatcher.DelayConventions()) { relationship = CreateForeignKey( targetEntityType.Builder, null, principalKey, propertyBaseName, required, configurationSource); newRelationship = relationship; if (principalKey != null) { newRelationship = newRelationship.HasEntityTypes(targetEntityType, Metadata, configurationSource) ?.HasPrincipalKey(principalKey.Properties, configurationSource); } newRelationship = newRelationship == null ? null : batch.Run(newRelationship); } if (newRelationship == null) { if (relationship?.Metadata.Builder != null) { relationship.Metadata.DeclaringEntityType.Builder.HasNoRelationship(relationship.Metadata, configurationSource); } return null; } return newRelationship; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasOwnership( [NotNull] string targetEntityTypeName, [NotNull] string navigationName, ConfigurationSource configurationSource) => HasOwnership( new TypeIdentity(targetEntityTypeName), MemberIdentity.Create(navigationName), inverse: null, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasOwnership( [NotNull] Type targetEntityType, [NotNull] string navigationName, ConfigurationSource configurationSource) => HasOwnership( new TypeIdentity(targetEntityType, Metadata.Model), MemberIdentity.Create(navigationName), inverse: null, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasOwnership( [NotNull] Type targetEntityType, [NotNull] MemberInfo navigationMember, ConfigurationSource configurationSource) => HasOwnership( new TypeIdentity(targetEntityType, Metadata.Model), MemberIdentity.Create(navigationMember), inverse: null, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasOwnership( [NotNull] Type targetEntityType, MemberIdentity navigation, ConfigurationSource configurationSource) => HasOwnership( new TypeIdentity(targetEntityType, Metadata.Model), navigation, inverse: null, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasOwnership( in TypeIdentity typeIdentity, MemberIdentity navigation, ConfigurationSource configurationSource) => HasOwnership( typeIdentity, navigation, inverse: null, configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasOwnership( [NotNull] Type targetEntityType, [NotNull] string navigationPropertyName, [CanBeNull] string inversePropertyName, ConfigurationSource configurationSource) => HasOwnership( new TypeIdentity(targetEntityType, Metadata.Model), MemberIdentity.Create(navigationPropertyName), MemberIdentity.Create(inversePropertyName), configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder HasOwnership( [NotNull] Type targetEntityType, [NotNull] MemberInfo navigationMember, [CanBeNull] MemberInfo inverseMember, ConfigurationSource configurationSource) => HasOwnership( new TypeIdentity(targetEntityType, Metadata.Model), MemberIdentity.Create(navigationMember), MemberIdentity.Create(inverseMember), configurationSource); private InternalForeignKeyBuilder HasOwnership( in TypeIdentity targetEntityType, MemberIdentity navigation, MemberIdentity? inverse, ConfigurationSource configurationSource) { InternalEntityTypeBuilder ownedEntityType; InternalForeignKeyBuilder relationship; using (var batch = Metadata.Model.ConventionDispatcher.DelayConventions()) { var existingNavigation = Metadata.FindNavigation(navigation.Name); if (existingNavigation != null) { if (existingNavigation.TargetEntityType.Name == targetEntityType.Name) { var existingOwnedEntityType = existingNavigation.ForeignKey.DeclaringEntityType; // Upgrade configurationSource for existing entity type if (existingOwnedEntityType.HasDefiningNavigation()) { if (targetEntityType.IsNamed) { ModelBuilder.Entity( targetEntityType.Name, existingOwnedEntityType.DefiningNavigationName, existingOwnedEntityType.DefiningEntityType, configurationSource); } else { ModelBuilder.Entity( targetEntityType.Type, existingOwnedEntityType.DefiningNavigationName, existingOwnedEntityType.DefiningEntityType, configurationSource); } } else { if (targetEntityType.IsNamed) { if (targetEntityType.Type != null) { ModelBuilder.SharedTypeEntity( targetEntityType.Name, targetEntityType.Type, configurationSource, shouldBeOwned: true); } else { ModelBuilder.Entity(targetEntityType.Name, configurationSource, shouldBeOwned: true); } } else { ModelBuilder.Entity(targetEntityType.Type, configurationSource, shouldBeOwned: true); } } var ownershipBuilder = existingNavigation.ForeignKey.Builder; ownershipBuilder = ownershipBuilder .HasEntityTypes( Metadata, ownershipBuilder.Metadata.FindNavigationsFromInHierarchy(Metadata).Single().TargetEntityType, configurationSource) ?.IsRequired(true, configurationSource) ?.HasNavigations(inverse, navigation, configurationSource) ?.IsOwnership(true, configurationSource); return ownershipBuilder == null ? null : batch.Run(ownershipBuilder); } if (existingNavigation.ForeignKey.DeclaringEntityType.Builder .HasNoRelationship(existingNavigation.ForeignKey, configurationSource) == null) { return null; } } var principalBuilder = this; var targetTypeName = targetEntityType.Name; var targetType = targetEntityType.Type; if (targetType == null) { var memberType = existingNavigation?.GetIdentifyingMemberInfo()?.GetMemberType(); if (memberType != null) { targetType = memberType.TryGetSequenceType() ?? memberType; } } ownedEntityType = targetEntityType.IsNamed ? ModelBuilder.Metadata.FindEntityType(targetTypeName)?.Builder : ModelBuilder.Metadata.FindEntityType(targetType)?.Builder; if (ownedEntityType == null) { if (Metadata.Model.EntityTypeShouldHaveDefiningNavigation(targetTypeName)) { if (!configurationSource.Overrides(ConfigurationSource.Explicit) && (targetType == null ? Metadata.IsInDefinitionPath(targetTypeName) : Metadata.IsInDefinitionPath(targetType))) { return null; } ownedEntityType = targetType == null ? ModelBuilder.Entity(targetTypeName, navigation.Name, Metadata, configurationSource) : ModelBuilder.Entity(targetType, navigation.Name, Metadata, configurationSource); } else { if (ModelBuilder.IsIgnored(targetTypeName, configurationSource)) { return null; } ModelBuilder.Metadata.RemoveIgnored(targetTypeName); ownedEntityType = targetEntityType.IsNamed ? targetType == null ? ModelBuilder.Entity(targetTypeName, configurationSource, shouldBeOwned: true) : ModelBuilder.SharedTypeEntity(targetTypeName, targetType, configurationSource, shouldBeOwned: true) : ModelBuilder.Entity(targetType, configurationSource, shouldBeOwned: true); } if (ownedEntityType == null) { return null; } } else { var otherOwnership = ownedEntityType.Metadata.FindDeclaredOwnership(); if (otherOwnership != null) { if (!configurationSource.Overrides(ConfigurationSource.Explicit) && (targetEntityType.IsNamed ? Metadata.IsInDefinitionPath(targetTypeName) : Metadata.IsInDefinitionPath(targetType))) { return null; } if (targetEntityType.IsNamed && targetType != null) { if (configurationSource == ConfigurationSource.Explicit) { throw new InvalidOperationException( CoreStrings.ClashingNamedOwnedType( targetTypeName, Metadata.DisplayName(), navigation.Name)); } return null; } var newOtherOwnership = otherOwnership.Builder.AddToDeclaringTypeDefinition(configurationSource); if (newOtherOwnership == null) { return null; } if (otherOwnership.DeclaringEntityType == Metadata) { principalBuilder = newOtherOwnership.Metadata.DeclaringEntityType.Builder; } ownedEntityType = targetType == null ? ModelBuilder.Entity(targetTypeName, navigation.Name, principalBuilder.Metadata, configurationSource) : ModelBuilder.Entity(targetType, navigation.Name, principalBuilder.Metadata, configurationSource); } } relationship = ownedEntityType.HasRelationship( targetEntityType: principalBuilder.Metadata, navigationToTarget: inverse, inverseNavigation: navigation, setTargetAsPrincipal: true, configurationSource, required: true); relationship = batch.Run(relationship.IsOwnership(true, configurationSource)); } if (relationship?.Metadata.Builder == null) { if (ownedEntityType.Metadata.Builder != null && ownedEntityType.Metadata.HasDefiningNavigation()) { ModelBuilder.HasNoEntityType(ownedEntityType.Metadata, configurationSource); } return null; } return relationship; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool RemoveNonOwnershipRelationships([NotNull] ForeignKey ownership, ConfigurationSource configurationSource) { var incompatibleRelationships = Metadata.GetDerivedTypesInclusive() .SelectMany(t => t.GetDeclaredForeignKeys()) .Where( fk => !fk.IsOwnership && fk.PrincipalToDependent != null && !Contains(ownership, fk)) .Concat( Metadata.GetDerivedTypesInclusive() .SelectMany(t => t.GetDeclaredReferencingForeignKeys()) .Where( fk => !fk.IsOwnership && !Contains(fk.DeclaringEntityType.FindOwnership(), fk))) .ToList(); if (incompatibleRelationships.Any(fk => !configurationSource.Overrides(fk.GetConfigurationSource()))) { return false; } foreach (var foreignKey in incompatibleRelationships) { // foreignKey.Builder can be null below if calling HasNoRelationship() below // affects the other foreign key(s) in incompatibleRelationships if (foreignKey.Builder != null) { foreignKey.DeclaringEntityType.Builder.HasNoRelationship(foreignKey, configurationSource); } } return true; } private bool Contains(IForeignKey inheritedFk, IForeignKey derivedFk) => inheritedFk != null && inheritedFk.PrincipalEntityType.IsAssignableFrom(derivedFk.PrincipalEntityType) && PropertyListComparer.Instance.Equals(inheritedFk.Properties, derivedFk.Properties); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder GetTargetEntityTypeBuilder( [NotNull] Type targetClrType, [NotNull] MemberInfo navigationInfo, ConfigurationSource? configurationSource) { var ownership = Metadata.FindOwnership(); // ReSharper disable CheckForReferenceEqualityInstead.1 // ReSharper disable CheckForReferenceEqualityInstead.3 if (ownership != null) { if (targetClrType.Equals(Metadata.ClrType)) { return null; } if (targetClrType.IsAssignableFrom(ownership.PrincipalEntityType.ClrType)) { if (configurationSource != null) { ownership.PrincipalEntityType.UpdateConfigurationSource(configurationSource.Value); } return ownership.PrincipalEntityType.Builder; } } var entityType = Metadata; InternalEntityTypeBuilder targetEntityTypeBuilder = null; if (!ModelBuilder.Metadata.EntityTypeShouldHaveDefiningNavigation(targetClrType)) { var targetEntityType = ModelBuilder.Metadata.FindEntityType(targetClrType); var existingOwnership = targetEntityType?.FindOwnership(); if (existingOwnership != null && entityType.Model.IsOwned(targetClrType) && (existingOwnership.PrincipalEntityType != entityType || existingOwnership.PrincipalToDependent?.Name != navigationInfo.GetSimpleMemberName())) { return configurationSource.HasValue && !targetClrType.Equals(Metadata.ClrType) ? ModelBuilder.Entity( targetClrType, navigationInfo.GetSimpleMemberName(), entityType, configurationSource.Value) : null; } var owned = existingOwnership != null || entityType.Model.IsOwned(targetClrType); targetEntityTypeBuilder = configurationSource.HasValue ? ModelBuilder.Entity(targetClrType, configurationSource.Value, owned) : targetEntityType?.Builder; } else if (!targetClrType.Equals(Metadata.ClrType)) { if (entityType.DefiningEntityType?.ClrType.Equals(targetClrType) == true) { if (configurationSource != null) { entityType.DefiningEntityType.UpdateConfigurationSource(configurationSource.Value); } return entityType.DefiningEntityType.Builder; } targetEntityTypeBuilder = entityType.FindNavigation(navigationInfo.GetSimpleMemberName())?.TargetEntityType.Builder ?? entityType.Model.FindEntityType( targetClrType, navigationInfo.GetSimpleMemberName(), entityType)?.Builder; if (targetEntityTypeBuilder == null && configurationSource.HasValue && !entityType.IsInDefinitionPath(targetClrType) && !entityType.IsInOwnershipPath(targetClrType)) { return ModelBuilder.Entity( targetClrType, navigationInfo.GetSimpleMemberName(), entityType, configurationSource.Value); } if (configurationSource != null) { targetEntityTypeBuilder?.Metadata.UpdateConfigurationSource(configurationSource.Value); } } // ReSharper restore CheckForReferenceEqualityInstead.1 // ReSharper restore CheckForReferenceEqualityInstead.3 return targetEntityTypeBuilder; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder CreateForeignKey( [NotNull] InternalEntityTypeBuilder principalEntityTypeBuilder, [CanBeNull] IReadOnlyList<Property> dependentProperties, [CanBeNull] Key principalKey, [CanBeNull] string propertyBaseName, bool? required, ConfigurationSource configurationSource) { using var batch = ModelBuilder.Metadata.ConventionDispatcher.DelayConventions(); var foreignKey = SetOrAddForeignKey( foreignKey: null, principalEntityTypeBuilder, dependentProperties, principalKey, propertyBaseName, required, configurationSource); if (required.HasValue && foreignKey?.IsRequired == required.Value) { foreignKey.SetIsRequired(required.Value, configurationSource); } return (InternalForeignKeyBuilder)batch.Run(foreignKey)?.Builder; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalForeignKeyBuilder UpdateForeignKey( [NotNull] ForeignKey foreignKey, [CanBeNull] IReadOnlyList<Property> dependentProperties, [CanBeNull] Key principalKey, [CanBeNull] string propertyBaseName, bool? isRequired, ConfigurationSource? configurationSource) { using var batch = ModelBuilder.Metadata.ConventionDispatcher.DelayConventions(); foreignKey = SetOrAddForeignKey( foreignKey, foreignKey.PrincipalEntityType.Builder, dependentProperties, principalKey, propertyBaseName, isRequired, configurationSource); return (InternalForeignKeyBuilder)batch.Run(foreignKey)?.Builder; } private ForeignKey SetOrAddForeignKey( ForeignKey foreignKey, InternalEntityTypeBuilder principalEntityTypeBuilder, IReadOnlyList<Property> dependentProperties, Key principalKey, string propertyBaseName, bool? isRequired, ConfigurationSource? configurationSource) { var principalType = principalEntityTypeBuilder.Metadata; var principalBaseEntityTypeBuilder = principalType.RootType().Builder; if (principalKey == null) { if (principalType.IsKeyless && !configurationSource.Overrides(principalType.GetIsKeylessConfigurationSource())) { return null; } principalKey = principalType.FindPrimaryKey(); if (principalKey != null && dependentProperties != null && (!ForeignKey.AreCompatible( principalKey.Properties, dependentProperties, principalType, Metadata, shouldThrow: false) || (foreignKey == null && Metadata.FindForeignKeysInHierarchy(dependentProperties, principalKey, principalType).Any()))) { principalKey = null; } if (principalKey == null && foreignKey != null && (dependentProperties == null || ForeignKey.AreCompatible( foreignKey.PrincipalKey.Properties, dependentProperties, principalType, Metadata, shouldThrow: false))) { principalKey = foreignKey.PrincipalKey; } } if (dependentProperties != null) { dependentProperties = GetActualProperties(dependentProperties, ConfigurationSource.Convention); if (principalKey == null) { var principalKeyProperties = principalBaseEntityTypeBuilder.TryCreateUniqueProperties( dependentProperties.Count, null, dependentProperties.Select(p => p.ClrType), Enumerable.Repeat("", dependentProperties.Count), isRequired: true, baseName: "TempId").Item2; principalKey = principalBaseEntityTypeBuilder.HasKeyInternal(principalKeyProperties, ConfigurationSource.Convention) .Metadata; } else { Check.DebugAssert( foreignKey != null || Metadata.FindForeignKey(dependentProperties, principalKey, principalType) == null, "FK not found"); } } else { if (principalKey == null) { var principalKeyProperties = principalBaseEntityTypeBuilder.TryCreateUniqueProperties( 1, null, new[] { typeof(int) }, new[] { "TempId" }, isRequired: true, baseName: "").Item2; principalKey = principalBaseEntityTypeBuilder.HasKeyInternal( principalKeyProperties, ConfigurationSource.Convention).Metadata; } if (foreignKey != null) { var oldProperties = foreignKey.Properties; var oldKey = foreignKey.PrincipalKey; var temporaryProperties = CreateUniqueProperties(null, principalKey.Properties, isRequired ?? false, "TempFk"); foreignKey.SetProperties(temporaryProperties, principalKey, configurationSource); foreignKey.DeclaringEntityType.Builder.RemoveUnusedImplicitProperties(oldProperties); if (oldKey != principalKey) { oldKey.DeclaringEntityType.Builder.RemoveKeyIfUnused(oldKey); } propertyBaseName ??= ForeignKeyPropertyDiscoveryConvention.GetPropertyBaseName(foreignKey); } var baseName = string.IsNullOrEmpty(propertyBaseName) ? principalType.ShortName() : propertyBaseName; dependentProperties = CreateUniqueProperties(null, principalKey.Properties, isRequired ?? false, baseName); } if (foreignKey == null) { return Metadata.AddForeignKey( dependentProperties, principalKey, principalType, componentConfigurationSource: null, configurationSource.Value); } var oldFKProperties = foreignKey.Properties; var oldPrincipalKey = foreignKey.PrincipalKey; foreignKey.SetProperties(dependentProperties, principalKey, configurationSource); if (oldFKProperties != dependentProperties) { foreignKey.DeclaringEntityType.Builder.RemoveUnusedImplicitProperties(oldFKProperties); } if (oldPrincipalKey != principalKey) { oldPrincipalKey.DeclaringEntityType.Builder.RemoveKeyIfUnused(oldPrincipalKey); } return foreignKey; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalSkipNavigationBuilder HasSkipNavigation( MemberIdentity navigation, [NotNull] EntityType targetEntityType, MemberIdentity inverseNavigation, ConfigurationSource configurationSource, bool? collections = null, bool? onDependent = null) { var skipNavigationBuilder = HasSkipNavigation( navigation, targetEntityType, configurationSource, collections, onDependent); if (skipNavigationBuilder == null) { return null; } var inverseSkipNavigationBuilder = targetEntityType.Builder.HasSkipNavigation( inverseNavigation, Metadata, configurationSource, collections, onDependent); if (inverseSkipNavigationBuilder == null) { HasNoSkipNavigation(skipNavigationBuilder.Metadata, configurationSource); return null; } return skipNavigationBuilder.HasInverse(inverseSkipNavigationBuilder.Metadata, configurationSource); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalSkipNavigationBuilder HasSkipNavigation( MemberIdentity navigationProperty, [NotNull] EntityType targetEntityType, ConfigurationSource? configurationSource, bool? collection = null, bool? onDependent = null) { List<SkipNavigation> navigationsToDetach = null; List<(InternalSkipNavigationBuilder Navigation, InternalSkipNavigationBuilder Inverse)> detachedNavigations = null; var navigationName = navigationProperty.Name; var memberInfo = navigationProperty.MemberInfo; var existingNavigation = Metadata.FindSkipNavigation(navigationName); if (existingNavigation != null) { Check.DebugAssert( memberInfo == null || memberInfo.IsSameAs(existingNavigation.GetIdentifyingMemberInfo()), "Expected memberInfo to be the same on the existing navigation"); Check.DebugAssert( collection == null || collection == existingNavigation.IsCollection, "Expected existing navigation to have the same cardinality"); Check.DebugAssert( onDependent == null || onDependent == existingNavigation.IsOnDependent, "Expected existing navigation to be on the same side"); if (existingNavigation.DeclaringEntityType != Metadata) { if (!IsIgnored(navigationName, configurationSource)) { Metadata.RemoveIgnored(navigationName); } } if (configurationSource.HasValue) { existingNavigation.UpdateConfigurationSource(configurationSource.Value); } return existingNavigation.Builder; } if (!configurationSource.HasValue || IsIgnored(navigationName, configurationSource)) { return null; } foreach (var conflictingMember in Metadata.FindPropertiesInHierarchy(navigationName).Cast<PropertyBase>() .Concat(Metadata.FindNavigationsInHierarchy(navigationName)) .Concat(Metadata.FindServicePropertiesInHierarchy(navigationName))) { if (!configurationSource.Overrides(conflictingMember.GetConfigurationSource())) { return null; } } foreach (var derivedType in Metadata.GetDerivedTypes()) { var conflictingNavigation = derivedType.FindDeclaredSkipNavigation(navigationName); if (conflictingNavigation != null) { if (navigationsToDetach == null) { navigationsToDetach = new List<SkipNavigation>(); } navigationsToDetach.Add(conflictingNavigation); } } if (collection == null && navigationProperty.MemberInfo != null) { var navigationType = navigationProperty.MemberInfo.GetMemberType(); var navigationTargetClrType = navigationType.TryGetSequenceType(); collection = navigationTargetClrType != null && navigationType != targetEntityType.ClrType && navigationTargetClrType.IsAssignableFrom(targetEntityType.ClrType); } InternalSkipNavigationBuilder builder; using (ModelBuilder.Metadata.ConventionDispatcher.DelayConventions()) { Metadata.RemoveIgnored(navigationName); foreach (var conflictingProperty in Metadata.FindPropertiesInHierarchy(navigationName)) { if (conflictingProperty.GetConfigurationSource() != ConfigurationSource.Explicit) { conflictingProperty.DeclaringEntityType.RemoveProperty(conflictingProperty); } } foreach (var conflictingServiceProperty in Metadata.FindServicePropertiesInHierarchy(navigationName)) { if (conflictingServiceProperty.GetConfigurationSource() != ConfigurationSource.Explicit) { conflictingServiceProperty.DeclaringEntityType.RemoveServiceProperty(conflictingServiceProperty); } } foreach (var conflictingNavigation in Metadata.FindNavigationsInHierarchy(navigationName)) { if (conflictingNavigation.GetConfigurationSource() == ConfigurationSource.Explicit) { continue; } var conflictingForeignKey = conflictingNavigation.ForeignKey; if (conflictingForeignKey.GetConfigurationSource() == ConfigurationSource.Convention) { conflictingForeignKey.DeclaringEntityType.Builder.HasNoRelationship( conflictingForeignKey, ConfigurationSource.Convention); } else if (conflictingForeignKey.Builder.HasNavigation( (string)null, conflictingNavigation.IsOnDependent, configurationSource.Value) == null) { return null; } } if (navigationsToDetach != null) { detachedNavigations = new List<(InternalSkipNavigationBuilder, InternalSkipNavigationBuilder)>(); foreach (var navigationToDetach in navigationsToDetach) { var inverse = navigationToDetach.Inverse; detachedNavigations.Add((DetachSkipNavigation(navigationToDetach), DetachSkipNavigation(inverse))); } } builder = Metadata.AddSkipNavigation( navigationName, navigationProperty.MemberInfo, targetEntityType, collection ?? true, onDependent ?? false, configurationSource.Value).Builder; if (detachedNavigations != null) { foreach (var detachedSkipNavigationTuple in detachedNavigations) { detachedSkipNavigationTuple.Navigation.Attach(this, inverseBuilder: detachedSkipNavigationTuple.Inverse); } } } return builder.Metadata.Builder == null ? Metadata.FindSkipNavigation(navigationName)?.Builder : builder; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder HasNoSkipNavigation( [NotNull] SkipNavigation skipNavigation, ConfigurationSource configurationSource) { if (!CanRemoveSkipNavigation(skipNavigation, configurationSource)) { return null; } if (skipNavigation.Inverse != null) { var removed = skipNavigation.Inverse.Builder.HasInverse(null, configurationSource); Check.DebugAssert(removed != null, "Expected inverse to be removed"); } Metadata.RemoveSkipNavigation(skipNavigation); return this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanRemoveSkipNavigation([NotNull] SkipNavigation skipNavigation, ConfigurationSource configurationSource) => configurationSource.Overrides(skipNavigation.GetConfigurationSource()); private static InternalSkipNavigationBuilder DetachSkipNavigation(SkipNavigation skipNavigationToDetach) { var builder = skipNavigationToDetach?.Builder; if (builder == null) { return null; } skipNavigationToDetach.DeclaringEntityType.Builder.HasNoSkipNavigation(skipNavigationToDetach, ConfigurationSource.Explicit); return builder; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool ShouldReuniquifyTemporaryProperties([NotNull] ForeignKey foreignKey) => TryCreateUniqueProperties( foreignKey.PrincipalKey.Properties.Count, foreignKey.Properties, foreignKey.PrincipalKey.Properties.Select(p => p.ClrType), foreignKey.PrincipalKey.Properties.Select(p => p.Name), foreignKey.IsRequired && foreignKey.GetIsRequiredConfigurationSource().Overrides(ConfigurationSource.Convention), foreignKey.DependentToPrincipal?.Name ?? foreignKey.ReferencingSkipNavigations?.FirstOrDefault()?.Inverse?.Name ?? foreignKey.PrincipalEntityType.ShortName()) .Item1; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalPropertyBuilder CreateUniqueProperty( [NotNull] Type propertyType, [NotNull] string propertyName, bool required) => CreateUniqueProperties( new[] { propertyType }, new[] { propertyName }, required).First().Builder; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IReadOnlyList<Property> CreateUniqueProperties( [NotNull] IReadOnlyList<Type> propertyTypes, [NotNull] IReadOnlyList<string> propertyNames, bool isRequired) => TryCreateUniqueProperties( propertyNames.Count, null, propertyTypes, propertyNames, isRequired, "").Item2; private IReadOnlyList<Property> CreateUniqueProperties( IReadOnlyList<Property> currentProperties, IReadOnlyList<Property> principalProperties, bool isRequired, string baseName) => TryCreateUniqueProperties( principalProperties.Count, currentProperties, principalProperties.Select(p => p.ClrType), principalProperties.Select(p => p.Name), isRequired, baseName).Item2; private (bool, IReadOnlyList<Property>) TryCreateUniqueProperties( int propertyCount, IReadOnlyList<Property> currentProperties, IEnumerable<Type> principalPropertyTypes, IEnumerable<string> principalPropertyNames, bool isRequired, string baseName) { var newProperties = currentProperties == null ? new Property[propertyCount] : null; var clrProperties = Metadata.GetRuntimeProperties(); var clrFields = Metadata.GetRuntimeFields(); var canReuniquify = false; using (var principalPropertyNamesEnumerator = principalPropertyNames.GetEnumerator()) { using var principalPropertyTypesEnumerator = principalPropertyTypes.GetEnumerator(); for (var i = 0; i < propertyCount && principalPropertyNamesEnumerator.MoveNext() && principalPropertyTypesEnumerator.MoveNext(); i++) { var keyPropertyName = principalPropertyNamesEnumerator.Current; var keyPropertyType = principalPropertyTypesEnumerator.Current; var keyModifiedBaseName = keyPropertyName.StartsWith(baseName, StringComparison.OrdinalIgnoreCase) ? keyPropertyName : baseName + keyPropertyName; string propertyName; var clrType = keyPropertyType.MakeNullable(!isRequired); var index = -1; while (true) { propertyName = keyModifiedBaseName + (++index > 0 ? index.ToString(CultureInfo.InvariantCulture) : ""); if (!Metadata.FindPropertiesInHierarchy(propertyName).Any() && clrProperties?.ContainsKey(propertyName) != true && clrFields?.ContainsKey(propertyName) != true && !IsIgnored(propertyName, ConfigurationSource.Convention)) { if (currentProperties == null) { var propertyBuilder = Property( clrType, propertyName, typeConfigurationSource: null, configurationSource: ConfigurationSource.Convention); if (clrType.IsNullableType()) { propertyBuilder.IsRequired(isRequired, ConfigurationSource.Convention); } newProperties[i] = propertyBuilder.Metadata; } else { canReuniquify = true; } break; } var currentProperty = currentProperties?.SingleOrDefault(p => p.Name == propertyName); if (currentProperty != null) { if (((IConventionProperty)currentProperty).IsImplicitlyCreated() && currentProperty.ClrType != clrType && isRequired) { canReuniquify = true; } break; } } } } return (canReuniquify, newProperties); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IReadOnlyList<Property> GetOrCreateProperties( [CanBeNull] IReadOnlyList<string> propertyNames, ConfigurationSource? configurationSource, [CanBeNull] IReadOnlyList<Property> referencedProperties = null, bool required = false, bool useDefaultType = false) { if (propertyNames == null) { return null; } if (referencedProperties != null && referencedProperties.Count != propertyNames.Count) { referencedProperties = null; } var propertyList = new List<Property>(); for (var i = 0; i < propertyNames.Count; i++) { var propertyName = propertyNames[i]; var property = Metadata.FindProperty(propertyName); if (property == null) { var type = referencedProperties == null ? useDefaultType ? typeof(int) : null : referencedProperties[i].ClrType; if (!configurationSource.HasValue) { return null; } var propertyBuilder = Property( required ? type : type?.MakeNullable(), propertyName, typeConfigurationSource: null, configurationSource.Value); if (propertyBuilder == null) { return null; } property = propertyBuilder.Metadata; } else if (configurationSource.HasValue) { if (ConfigurationSource.Convention.Overrides(property.GetTypeConfigurationSource()) && (property.IsShadowProperty() || property.IsIndexerProperty()) && (!property.IsNullable || (required && property.GetIsNullableConfigurationSource() == null)) && property.ClrType.IsNullableType()) { property = property.DeclaringEntityType.Builder.Property( property.ClrType.MakeNullable(false), property.Name, configurationSource.Value) .Metadata; } else { property = property.DeclaringEntityType.Builder.Property(property.Name, configurationSource.Value).Metadata; } } propertyList.Add(property); } return propertyList; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IReadOnlyList<Property> GetOrCreateProperties( [CanBeNull] IEnumerable<MemberInfo> clrMembers, ConfigurationSource? configurationSource) { if (clrMembers == null) { return null; } var list = new List<Property>(); foreach (var propertyInfo in clrMembers) { var propertyBuilder = Property(propertyInfo, configurationSource); if (propertyBuilder == null) { return null; } list.Add(propertyBuilder.Metadata); } return list; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual IReadOnlyList<Property> GetActualProperties( [CanBeNull] IReadOnlyList<Property> properties, ConfigurationSource? configurationSource) { if (properties == null) { return null; } var actualProperties = new Property[properties.Count]; for (var i = 0; i < actualProperties.Length; i++) { var property = properties[i]; var typeConfigurationSource = property.GetTypeConfigurationSource(); var builder = property.Builder != null && property.DeclaringEntityType.IsAssignableFrom(Metadata) ? property.Builder : Property( typeConfigurationSource.Overrides(ConfigurationSource.DataAnnotation) ? property.ClrType : null, property.Name, property.GetIdentifyingMemberInfo(), typeConfigurationSource.Overrides(ConfigurationSource.DataAnnotation) ? typeConfigurationSource : null, configurationSource); if (builder == null) { return null; } actualProperties[i] = builder.Metadata; } return actualProperties; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder HasChangeTrackingStrategy( ChangeTrackingStrategy? changeTrackingStrategy, ConfigurationSource configurationSource) { if (CanSetChangeTrackingStrategy(changeTrackingStrategy, configurationSource)) { Metadata.SetChangeTrackingStrategy(changeTrackingStrategy, configurationSource); return this; } return null; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanSetChangeTrackingStrategy( ChangeTrackingStrategy? changeTrackingStrategy, ConfigurationSource configurationSource) => configurationSource.Overrides(Metadata.GetChangeTrackingStrategyConfigurationSource()) || Metadata.GetChangeTrackingStrategy() == changeTrackingStrategy; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder UsePropertyAccessMode( PropertyAccessMode? propertyAccessMode, ConfigurationSource configurationSource) { if (CanSetPropertyAccessMode(propertyAccessMode, configurationSource)) { Metadata.SetPropertyAccessMode(propertyAccessMode, configurationSource); return this; } return null; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanSetPropertyAccessMode(PropertyAccessMode? propertyAccessMode, ConfigurationSource configurationSource) => configurationSource.Overrides(Metadata.GetPropertyAccessModeConfigurationSource()) || Metadata.GetPropertyAccessMode() == propertyAccessMode; /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual DiscriminatorBuilder HasDiscriminator(ConfigurationSource configurationSource) => DiscriminatorBuilder( GetOrCreateDiscriminatorProperty(type: null, name: null, ConfigurationSource.Convention), configurationSource); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual DiscriminatorBuilder HasDiscriminator( [CanBeNull] string name, [CanBeNull] Type type, ConfigurationSource configurationSource) { Check.DebugAssert(name != null || type != null, $"Either {nameof(name)} or {nameof(type)} should be non-null"); return CanSetDiscriminator(name, type, configurationSource) ? DiscriminatorBuilder( GetOrCreateDiscriminatorProperty(type, name, configurationSource), configurationSource) : null; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual DiscriminatorBuilder HasDiscriminator([NotNull] MemberInfo memberInfo, ConfigurationSource configurationSource) => CanSetDiscriminator( Check.NotNull(memberInfo, nameof(memberInfo)).GetSimpleMemberName(), memberInfo.GetMemberType(), configurationSource) ? DiscriminatorBuilder( Metadata.RootType().Builder.Property( memberInfo, configurationSource), configurationSource) : null; private static readonly string _defaultDiscriminatorName = "Discriminator"; private static readonly Type _defaultDiscriminatorType = typeof(string); private InternalPropertyBuilder GetOrCreateDiscriminatorProperty(Type type, string name, ConfigurationSource configurationSource) { var discriminatorProperty = ((IEntityType)Metadata).GetDiscriminatorProperty(); if ((name != null && discriminatorProperty?.Name != name) || (type != null && discriminatorProperty?.ClrType != type)) { discriminatorProperty = null; } return Metadata.RootType().Builder.Property( type ?? discriminatorProperty?.ClrType ?? _defaultDiscriminatorType, name ?? discriminatorProperty?.Name ?? _defaultDiscriminatorName, typeConfigurationSource: type != null ? configurationSource : (ConfigurationSource?)null, configurationSource) ?.AfterSave(PropertySaveBehavior.Throw, ConfigurationSource.Convention); } private DiscriminatorBuilder DiscriminatorBuilder( [CanBeNull] InternalPropertyBuilder discriminatorPropertyBuilder, ConfigurationSource configurationSource) { if (discriminatorPropertyBuilder == null) { return null; } var rootTypeBuilder = Metadata.RootType().Builder; var discriminatorProperty = discriminatorPropertyBuilder.Metadata; // Make sure the property is on the root type discriminatorPropertyBuilder = rootTypeBuilder.Property( discriminatorProperty.ClrType, discriminatorProperty.Name, null, ConfigurationSource.Convention); RemoveUnusedDiscriminatorProperty(discriminatorProperty, configurationSource); rootTypeBuilder.Metadata.SetDiscriminatorProperty(discriminatorProperty, configurationSource); discriminatorPropertyBuilder.IsRequired(true, ConfigurationSource.Convention); discriminatorPropertyBuilder.HasValueGenerator(DiscriminatorValueGenerator.Factory, ConfigurationSource.Convention); return new DiscriminatorBuilder(Metadata); } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual InternalEntityTypeBuilder HasNoDiscriminator(ConfigurationSource configurationSource) { if (Metadata[CoreAnnotationNames.DiscriminatorProperty] != null && !configurationSource.Overrides(Metadata.GetDiscriminatorPropertyConfigurationSource())) { return null; } if (Metadata.BaseType == null) { RemoveUnusedDiscriminatorProperty(null, configurationSource); } Metadata.SetDiscriminatorProperty(null, configurationSource); if (configurationSource == ConfigurationSource.Explicit) { Metadata.SetDiscriminatorMappingComplete(null); } else if (CanSetAnnotation(CoreAnnotationNames.DiscriminatorMappingComplete, null, configurationSource)) { Metadata.SetDiscriminatorMappingComplete(null, configurationSource == ConfigurationSource.DataAnnotation); } return this; } private void RemoveUnusedDiscriminatorProperty(Property newDiscriminatorProperty, ConfigurationSource configurationSource) { var oldDiscriminatorProperty = ((IEntityType)Metadata).GetDiscriminatorProperty() as Property; if (oldDiscriminatorProperty?.Builder != null && oldDiscriminatorProperty != newDiscriminatorProperty) { oldDiscriminatorProperty.DeclaringEntityType.Builder.RemoveUnusedImplicitProperties( new[] { oldDiscriminatorProperty }); if (oldDiscriminatorProperty.Builder != null) { oldDiscriminatorProperty.Builder.IsRequired(null, configurationSource); oldDiscriminatorProperty.Builder.HasValueGenerator((Type)null, configurationSource); } } } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public virtual bool CanSetDiscriminator([CanBeNull] string name, [CanBeNull] Type type, ConfigurationSource configurationSource) => name == null && type == null ? CanRemoveDiscriminator(configurationSource) : CanSetDiscriminator(((IEntityType)Metadata).GetDiscriminatorProperty(), name, type, configurationSource); private bool CanSetDiscriminator( IProperty discriminatorProperty, string name, Type discriminatorType, ConfigurationSource configurationSource) => ((name == null && discriminatorType == null) || ((name == null || discriminatorProperty?.Name == name) && (discriminatorType == null || discriminatorProperty?.ClrType == discriminatorType)) || configurationSource.Overrides(Metadata.GetDiscriminatorPropertyConfigurationSource())) && (discriminatorProperty != null || Metadata.RootType().Builder.CanAddDiscriminatorProperty( discriminatorType ?? _defaultDiscriminatorType, name ?? _defaultDiscriminatorName, typeConfigurationSource: discriminatorType != null ? configurationSource : (ConfigurationSource?)null)); private bool CanRemoveDiscriminator(ConfigurationSource configurationSource) => CanSetAnnotation(CoreAnnotationNames.DiscriminatorProperty, null, configurationSource); private bool CanAddDiscriminatorProperty( [NotNull] Type propertyType, [NotNull] string name, ConfigurationSource? typeConfigurationSource) { var conflictingProperty = Metadata.FindPropertiesInHierarchy(name).FirstOrDefault(); if (conflictingProperty != null && (conflictingProperty.IsShadowProperty() || conflictingProperty.IsIndexerProperty()) && conflictingProperty.ClrType != propertyType && typeConfigurationSource != null && !typeConfigurationSource.Overrides(conflictingProperty.GetTypeConfigurationSource())) { return false; } if (Metadata.ClrType == null) { return true; } var memberInfo = Metadata.ClrType.GetMembersInHierarchy(name).FirstOrDefault(); if (memberInfo != null && propertyType != memberInfo.GetMemberType() && typeConfigurationSource != null) { return false; } return true; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> IConventionEntityType IConventionEntityTypeBuilder.Metadata { [DebuggerStepThrough] get => Metadata; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.HasBaseType(IConventionEntityType baseEntityType, bool fromDataAnnotation) => HasBaseType( (EntityType)baseEntityType, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanSetBaseType(IConventionEntityType baseEntityType, bool fromDataAnnotation) => CanSetBaseType( (EntityType)baseEntityType, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionPropertyBuilder IConventionEntityTypeBuilder.Property( Type propertyType, string propertyName, bool setTypeConfigurationSource, bool fromDataAnnotation) => Property( propertyType, propertyName, setTypeConfigurationSource ? fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention : (ConfigurationSource?)null, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionPropertyBuilder IConventionEntityTypeBuilder.Property(MemberInfo memberInfo, bool fromDataAnnotation) => Property(memberInfo, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IReadOnlyList<IConventionProperty> IConventionEntityTypeBuilder.GetOrCreateProperties( IReadOnlyList<string> propertyNames, bool fromDataAnnotation) => GetOrCreateProperties( propertyNames, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IReadOnlyList<IConventionProperty> IConventionEntityTypeBuilder.GetOrCreateProperties( IEnumerable<MemberInfo> memberInfos, bool fromDataAnnotation) => GetOrCreateProperties(memberInfos, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.RemoveUnusedImplicitProperties( IReadOnlyList<IConventionProperty> properties) => RemoveUnusedImplicitProperties(properties); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionServicePropertyBuilder IConventionEntityTypeBuilder.ServiceProperty(MemberInfo memberInfo, bool fromDataAnnotation) => ServiceProperty(memberInfo, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> bool IConventionEntityTypeBuilder.IsIgnored(string name, bool fromDataAnnotation) => IsIgnored(name, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.Ignore(string name, bool fromDataAnnotation) => Ignore(name, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanIgnore(string name, bool fromDataAnnotation) => CanIgnore(name, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionKeyBuilder IConventionEntityTypeBuilder.PrimaryKey( IReadOnlyList<IConventionProperty> properties, bool fromDataAnnotation) => PrimaryKey( properties as IReadOnlyList<Property> ?? properties?.Cast<Property>().ToList(), fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanSetPrimaryKey(IReadOnlyList<IConventionProperty> properties, bool fromDataAnnotation) => CanSetPrimaryKey( properties as IReadOnlyList<Property> ?? properties?.Cast<Property>().ToList(), fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionKeyBuilder IConventionEntityTypeBuilder.HasKey(IReadOnlyList<IConventionProperty> properties, bool fromDataAnnotation) => HasKey( properties as IReadOnlyList<Property> ?? properties.Cast<Property>().ToList(), fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.HasNoKey(bool fromDataAnnotation) => HasNoKey(fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.HasNoKey( IReadOnlyList<IConventionProperty> properties, bool fromDataAnnotation) { Check.NotEmpty(properties, nameof(properties)); var key = Metadata.FindDeclaredKey(properties); return key != null ? HasNoKey(key, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention) : this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanRemoveKey([NotNull] IConventionKey key, bool fromDataAnnotation) => CanRemoveKey((Key)key, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.HasNoKey(IConventionKey key, bool fromDataAnnotation) => HasNoKey((Key)key, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanRemoveKey(bool fromDataAnnotation) => CanRemoveKey(fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionIndexBuilder IConventionEntityTypeBuilder.HasIndex( IReadOnlyList<string> propertyNames, bool fromDataAnnotation) => HasIndex( propertyNames, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionIndexBuilder IConventionEntityTypeBuilder.HasIndex( IReadOnlyList<string> propertyNames, string name, bool fromDataAnnotation) => HasIndex( propertyNames, name, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionIndexBuilder IConventionEntityTypeBuilder.HasIndex( IReadOnlyList<IConventionProperty> properties, bool fromDataAnnotation) => HasIndex( properties as IReadOnlyList<Property> ?? properties.Cast<Property>().ToList(), fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> IConventionIndexBuilder IConventionEntityTypeBuilder.HasIndex( IReadOnlyList<IConventionProperty> properties, string name, bool fromDataAnnotation) => HasIndex( properties as IReadOnlyList<Property> ?? properties.Cast<Property>().ToList(), name, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.HasNoIndex( IReadOnlyList<IConventionProperty> properties, bool fromDataAnnotation) { Check.NotEmpty(properties, nameof(properties)); var index = Metadata.FindDeclaredIndex(properties); return index != null ? HasNoIndex(index, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention) : this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.HasNoIndex(IConventionIndex index, bool fromDataAnnotation) => HasNoIndex((Index)index, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanRemoveIndex([NotNull] IConventionIndex index, bool fromDataAnnotation) => CanRemoveIndex((Index)index, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionForeignKeyBuilder IConventionEntityTypeBuilder.HasRelationship( IConventionEntityType targetEntityType, bool fromDataAnnotation) => HasRelationship( (EntityType)targetEntityType, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionForeignKeyBuilder IConventionEntityTypeBuilder.HasRelationship( IConventionEntityType principalEntityType, IReadOnlyList<IConventionProperty> dependentProperties, bool fromDataAnnotation) => HasRelationship( (EntityType)principalEntityType, dependentProperties as IReadOnlyList<Property> ?? dependentProperties.Cast<Property>().ToList(), fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionForeignKeyBuilder IConventionEntityTypeBuilder.HasRelationship( IConventionEntityType principalEntityType, IConventionKey principalKey, bool fromDataAnnotation) => HasRelationship( (EntityType)principalEntityType, (Key)principalKey, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionForeignKeyBuilder IConventionEntityTypeBuilder.HasRelationship( IConventionEntityType principalEntityType, IReadOnlyList<IConventionProperty> dependentProperties, IConventionKey principalKey, bool fromDataAnnotation) => HasRelationship( (EntityType)principalEntityType, dependentProperties as IReadOnlyList<Property> ?? dependentProperties.Cast<Property>().ToList(), (Key)principalKey, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionForeignKeyBuilder IConventionEntityTypeBuilder.HasRelationship( IConventionEntityType targetEntityType, string navigationName, bool setTargetAsPrincipal, bool fromDataAnnotation) => HasRelationship( (EntityType)targetEntityType, navigationName, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention, setTargetAsPrincipal ? true : (bool?)null); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionForeignKeyBuilder IConventionEntityTypeBuilder.HasRelationship( IConventionEntityType targetEntityType, MemberInfo navigation, bool setTargetAsPrincipal, bool fromDataAnnotation) => HasRelationship( (EntityType)targetEntityType, navigation, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention, setTargetAsPrincipal ? true : (bool?)null); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionForeignKeyBuilder IConventionEntityTypeBuilder.HasRelationship( IConventionEntityType targetEntityType, string navigationName, string inverseNavigationName, bool setTargetAsPrincipal, bool fromDataAnnotation) => HasRelationship( (EntityType)targetEntityType, navigationName, inverseNavigationName, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention, setTargetAsPrincipal); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionForeignKeyBuilder IConventionEntityTypeBuilder.HasRelationship( IConventionEntityType targetEntityType, MemberInfo navigation, MemberInfo inverseNavigation, bool setTargetAsPrincipal, bool fromDataAnnotation) => HasRelationship( (EntityType)targetEntityType, navigation, inverseNavigation, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention, setTargetAsPrincipal); /// <inheritdoc /> [DebuggerStepThrough] IConventionSkipNavigationBuilder IConventionEntityTypeBuilder.HasSkipNavigation( MemberInfo navigation, IConventionEntityType targetEntityType, MemberInfo inverseNavigation, bool? collections, bool? onDependent, bool fromDataAnnotation) => HasSkipNavigation( MemberIdentity.Create(navigation), (EntityType)targetEntityType, MemberIdentity.Create(inverseNavigation), fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention, collections, onDependent); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionForeignKeyBuilder IConventionEntityTypeBuilder.HasOwnership( Type targetEntityType, string navigationName, bool fromDataAnnotation) => HasOwnership( targetEntityType, navigationName, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionForeignKeyBuilder IConventionEntityTypeBuilder.HasOwnership( Type targetEntityType, MemberInfo navigation, bool fromDataAnnotation) => HasOwnership( targetEntityType, navigation, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionForeignKeyBuilder IConventionEntityTypeBuilder.HasOwnership( Type targetEntityType, string navigationName, string inversePropertyName, bool fromDataAnnotation) => HasOwnership( targetEntityType, navigationName, inversePropertyName, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionForeignKeyBuilder IConventionEntityTypeBuilder.HasOwnership( Type targetEntityType, MemberInfo navigation, MemberInfo inverseProperty, bool fromDataAnnotation) => HasOwnership( targetEntityType, navigation, inverseProperty, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.HasNoRelationship( IReadOnlyList<IConventionProperty> properties, IConventionKey principalKey, IConventionEntityType principalEntityType, bool fromDataAnnotation) { Check.NotEmpty(properties, nameof(properties)); Check.NotNull(principalKey, nameof(principalKey)); Check.NotNull(principalEntityType, nameof(principalEntityType)); var foreignKey = Metadata.FindDeclaredForeignKey(properties, principalKey, principalEntityType); return foreignKey != null ? HasNoRelationship(foreignKey, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention) : this; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.HasNoRelationship( IConventionForeignKey foreignKey, bool fromDataAnnotation) => HasNoRelationship( (ForeignKey)foreignKey, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanRemoveRelationship([NotNull] IConventionForeignKey foreignKey, bool fromDataAnnotation) => CanRemoveForeignKey( (ForeignKey)foreignKey, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanHaveNavigation(string navigationName, bool fromDataAnnotation) => CanHaveNavigation( navigationName, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanHaveSkipNavigation(string skipNavigationName, bool fromDataAnnotation) => CanHaveSkipNavigation( skipNavigationName, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <inheritdoc /> [DebuggerStepThrough] IConventionSkipNavigationBuilder IConventionEntityTypeBuilder.HasSkipNavigation( MemberInfo navigation, IConventionEntityType targetEntityType, bool? collection, bool? onDependent, bool fromDataAnnotation) => HasSkipNavigation( MemberIdentity.Create(navigation), (EntityType)targetEntityType, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention, collection, onDependent); /// <inheritdoc /> [DebuggerStepThrough] IConventionSkipNavigationBuilder IConventionEntityTypeBuilder.HasSkipNavigation( string navigationName, IConventionEntityType targetEntityType, bool? collection, bool? onDependent, bool fromDataAnnotation) => HasSkipNavigation( MemberIdentity.Create(navigationName), (EntityType)targetEntityType, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention, collection, onDependent); /// <inheritdoc /> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.HasNoSkipNavigation( ISkipNavigation skipNavigation, bool fromDataAnnotation) => HasNoSkipNavigation( (SkipNavigation)skipNavigation, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <inheritdoc /> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanRemoveSkipNavigation(ISkipNavigation skipNavigation, bool fromDataAnnotation) => CanRemoveSkipNavigation( (SkipNavigation)skipNavigation, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.HasQueryFilter(LambdaExpression filter, bool fromDataAnnotation) => HasQueryFilter(filter, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanSetQueryFilter(LambdaExpression filter, bool fromDataAnnotation) => CanSetQueryFilter(filter, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] [Obsolete] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.HasDefiningQuery(LambdaExpression query, bool fromDataAnnotation) => HasDefiningQuery(query, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] [Obsolete] bool IConventionEntityTypeBuilder.CanSetDefiningQuery(LambdaExpression query, bool fromDataAnnotation) => CanSetDefiningQuery(query, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.HasChangeTrackingStrategy( ChangeTrackingStrategy? changeTrackingStrategy, bool fromDataAnnotation) => HasChangeTrackingStrategy( changeTrackingStrategy, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanSetChangeTrackingStrategy( ChangeTrackingStrategy? changeTrackingStrategy, bool fromDataAnnotation) => CanSetChangeTrackingStrategy( changeTrackingStrategy, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.UsePropertyAccessMode( PropertyAccessMode? propertyAccessMode, bool fromDataAnnotation) => UsePropertyAccessMode( propertyAccessMode, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanSetPropertyAccessMode(PropertyAccessMode? propertyAccessMode, bool fromDataAnnotation) => CanSetPropertyAccessMode( propertyAccessMode, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionDiscriminatorBuilder IConventionEntityTypeBuilder.HasDiscriminator(bool fromDataAnnotation) => HasDiscriminator( fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionDiscriminatorBuilder IConventionEntityTypeBuilder.HasDiscriminator(Type type, bool fromDataAnnotation) => HasDiscriminator( name: null, Check.NotNull(type, nameof(type)), fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionDiscriminatorBuilder IConventionEntityTypeBuilder.HasDiscriminator(string name, bool fromDataAnnotation) => HasDiscriminator( Check.NotEmpty(name, nameof(name)), type: null, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionDiscriminatorBuilder IConventionEntityTypeBuilder.HasDiscriminator(string name, Type type, bool fromDataAnnotation) => HasDiscriminator( Check.NotEmpty(name, nameof(name)), Check.NotNull(type, nameof(type)), fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionDiscriminatorBuilder IConventionEntityTypeBuilder.HasDiscriminator(MemberInfo memberInfo, bool fromDataAnnotation) => HasDiscriminator( memberInfo, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] IConventionEntityTypeBuilder IConventionEntityTypeBuilder.HasNoDiscriminator(bool fromDataAnnotation) => HasNoDiscriminator(fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanSetDiscriminator(string name, bool fromDataAnnotation) => CanSetDiscriminator( name, type: null, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanSetDiscriminator(Type type, bool fromDataAnnotation) => CanSetDiscriminator( name: null, type, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanSetDiscriminator(string name, Type type, bool fromDataAnnotation) => CanSetDiscriminator( name, type, fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanSetDiscriminator([NotNull] MemberInfo memberInfo, bool fromDataAnnotation) => CanSetDiscriminator( Check.NotNull(memberInfo, nameof(memberInfo)).GetSimpleMemberName(), memberInfo.GetMemberType(), fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> [DebuggerStepThrough] bool IConventionEntityTypeBuilder.CanRemoveDiscriminator(bool fromDataAnnotation) => CanRemoveDiscriminator(fromDataAnnotation ? ConfigurationSource.DataAnnotation : ConfigurationSource.Convention); /// <inheritdoc /> [DebuggerStepThrough] IConventionPropertyBuilder IConventionEntityTypeBuilder.CreateUniqueProperty( Type propertyType, string basePropertyName, bool required) => CreateUniqueProperty(propertyType, basePropertyName, required); } }
52.021657
140
0.595649
[ "Apache-2.0" ]
0b01/efcore
src/EFCore/Metadata/Internal/InternalEntityTypeBuilder.cs
276,235
C#
using Arcs; using Ship; using Tokens; using Upgrade; namespace Ship { namespace SecondEdition.EWing { public class CorranHorn : EWing { public CorranHorn() : base() { PilotInfo = new PilotCardInfo( "Corran Horn", 5, 59, isLimited: true, abilityType: typeof(Abilities.SecondEdition.CorranHornAbility), extraUpgradeIcon: UpgradeType.Talent, seImageNumber: 50 ); ModelInfo.SkinName = "Green"; } } } } namespace Abilities.SecondEdition { //At initiative 0, you may perform a bonus primary attack against an enemy ship in your bullseye firing arc. //If you do, at the start of the next Planning Phase, gain 1 disarm token. public class CorranHornAbility : CorranHornBaseAbility { public CorranHornAbility() { TriggerType = TriggerTypes.OnEngagementInitiativeChanged; Description = "You may perform a bonus bullseye primary attack\nGain 1 disarm token next round"; ExtraAttackFilter = IsBullsEyePrimary; } public override void ActivateAbility() { Phases.Events.OnEngagementInitiativeChanged += RegisterCorranHornAbility; } public override void DeactivateAbility() { Phases.Events.OnEngagementInitiativeChanged -= RegisterCorranHornAbility; } protected override void RegisterCorranHornAbility() { if (!HostShip.Tokens.HasToken(typeof(WeaponsDisabledToken)) && Phases.CurrentSubPhase.RequiredInitiative == 0) { RegisterAbilityTrigger(TriggerType, UseCorranHornAbility); } } private bool IsBullsEyePrimary(GenericShip defender, IShipWeapon weapon, bool isSilent) { bool result = false; if (weapon.WeaponType == WeaponTypes.PrimaryWeapon && HostShip.SectorsInfo.IsShipInSector(defender, ArcType.Bullseye)) { result = true; } else { if (weapon.WeaponType != WeaponTypes.PrimaryWeapon) { if (!isSilent) Messages.ShowError("This attack must be performed with the primary weapon"); } else { if (!isSilent) Messages.ShowError("This attack must be performed against a target in the ship's Bullseye arc"); } } return result; } } }
32.707317
131
0.566741
[ "MIT" ]
97saundersj/FlyCasual
Assets/Scripts/Model/Content/SecondEdition/Pilots/EWing/CorranHorn.cs
2,684
C#
using System; using System.Collections.Generic; using System.IO; using System.Text; using System.Text.RegularExpressions; public class ReplaceSubstringInATextFile { public const string OldStr = "start"; public const string NewStr = "finish"; internal static void Main() { string inputName = "input.txt"; string outputName = "output.txt"; if (!File.Exists(inputName)) { string createText = "start" + Environment.NewLine + "start" + Environment.NewLine + "start" + Environment.NewLine + "start" + Environment.NewLine; File.WriteAllText(inputName, createText); } using (TextWriter myWriter = new StreamWriter(outputName)) { using (TextReader myReader = new StreamReader(inputName)) { string readLine = myReader.ReadLine(); while (readLine != null) { readLine = readLine.Replace(OldStr, NewStr); myWriter.WriteLine(readLine); readLine = myReader.ReadLine(); } } } ////Regex wordRgx = new Regex(oldStr, RegexOptions.IgnoreCase); ////using (StreamReader sr = new StreamReader(inputName)) ////{ //// using (StreamWriter sw = new StreamWriter(outputName)) //// { //// string line; //// while ((line = sr.ReadLine()) != null) //// { //// sw.WriteLine(wordRgx.Replace(line, newStr)); //// } //// } ////} } }
30.087719
71
0.500875
[ "MIT" ]
iKostov86/CSharp
Homeworks/C# - part 2/TextFiles/07.ReplaceSubstringInATextFile/ReplaceSubstringInATextFile.cs
1,717
C#
// Source: Microsoft KB Article KB317540 /* SUMMARY The native code application programming interfaces (APIs) that allow you to interact with the Global Assembly Cache (GAC) are not documented in the .NET Framework Software Development Kit (SDK) documentation. MORE INFORMATION CAUTION: Do not use these APIs in your application to perform assembly binds or to test for the presence of assemblies or other run time, development, or design-time operations. Only administrative tools and setup programs must use these APIs. If you use the GAC, this directly exposes your application to assembly binding fragility or may cause your application to work improperly on future versions of the .NET Framework. The GAC stores assemblies that are shared across all applications on a computer. The actual storage location and structure of the GAC is not documented and is subject to change in future versions of the .NET Framework and the Microsoft Windows operating global::System. The only supported method to access assemblies in the GAC is through the APIs that are documented in this article. Most applications do not have to use these APIs because the assembly binding is performed automatically by the common language runtime. Only custom setup programs or management tools must use these APIs. Microsoft Windows Installer has native support for installing assemblies to the GAC. For more information about assemblies and the GAC, see the .NET Framework SDK. Use the GAC API in the following scenarios: When you install an assembly to the GAC. When you remove an assembly from the GAC. When you export an assembly from the GAC. When you enumerate assemblies that are available in the GAC. NOTE: CoInitialize(Ex) must be called before you use any of the functions and interfaces that are described in this specification. */ using System; using System.Globalization; using System.Reflection; using System.Runtime.InteropServices; using System.Runtime.InteropServices.ComTypes; using System.Security; using System.Text; using JetBrains.Annotations; namespace essentialMix.Helpers; /// <summary> /// <see cref="IAssemblyName.GetDisplayName"/> /// </summary> [Flags] public enum AsmDisplayFlags { Version = 0x1, Culture = 0x2, PublicKeyToken = 0x4, PublicKey = 0x8, Custom = 0x10, Processorarchitecture = 0x20, Languageid = 0x40 } [Flags] public enum AsmCmpFlags { Name = 0x1, MajorVersion = 0x2, MinorVersion = 0x4, BuildNumber = 0x8, RevisionNumber = 0x10, PublicKeyToken = 0x20, Culture = 0x40, Custom = 0x80, All = Name | MajorVersion | MinorVersion | RevisionNumber | BuildNumber | PublicKeyToken | Culture | Custom, Default = 0x100 } /// <summary> /// The ASM_NAME enumeration property ID describes the valid names of the name-value pairs in an assembly name. /// See the .NET Framework SDK for a description of these properties. /// </summary> public enum AsmName { AsmNamePublicKey = 0, AsmNamePublicKeyToken, AsmNameHashValue, AsmNameName, AsmNameMajorVersion, AsmNameMinorVersion, AsmNameBuildNumber, AsmNameRevisionNumber, AsmNameCulture, AsmNameProcessorIDArray, AsmNameOsinfoArray, AsmNameHashAlgid, AsmNameAlias, AsmNameCodebaseUrl, AsmNameCodebaseLastmod, AsmNameNullPublicKey, AsmNameNullPublicKeyToken, AsmNameCustom, AsmNameNullCustom, AsmNameMvid, AsmNameMaxParams } /// <summary> /// <see cref="IAssemblyCache.UninstallAssembly"/> /// </summary> public enum IassemblycacheUninstallDisposition { IassemblycacheUninstallDispositionUninstalled = 1, IassemblycacheUninstallDispositionStillInUse = 2, IassemblycacheUninstallDispositionAlreadyUninstalled = 3, IassemblycacheUninstallDispositionDeletePending = 4, IassemblycacheUninstallDispositionHasInstallReferences = 5, IassemblycacheUninstallDispositionReferenceNotFound = 6 } /// <summary> /// <see cref="IAssemblyCache.QueryAssemblyInfo"/> /// </summary> public enum QueryAsmInfoFlag { QueryasminfoFlagValidate = 1, QueryasminfoFlagGetsize = 2 } public enum IassemblycacheInstallFlag { IassemblycacheInstallFlagRefresh = 1, IassemblycacheInstallFlagForceRefresh = 2 } /// <summary> /// The CREATE_ASM_NAME_OBJ_FLAGS enumeration contains the following values: /// CANOF_PARSE_DISPLAY_NAME - If this flag is specified, the szAssemblyName parameter is a full assembly name and is parsed to /// the individual properties. If the flag is not specified, szAssemblyName is the "Name" portion of the assembly name. /// CANOF_SET_DEFAULT_VALUES - If this flag is specified, certain properties, such as processor architecture, are set to /// their default values. /// <see cref="AssemblyCache.CreateAssemblyNameObject"/> /// </summary> public enum CreateAsmNameObjFlags { CanofParseDisplayName = 0x1, CanofSetDefaultValues = 0x2 } /// <summary> /// The ASM_CACHE_FLAGS enumeration contains the following values: /// ASM_CACHE_ZAP - Enumerates the cache of precompiled assemblies by using Ngen.exe. /// ASM_CACHE_GAC - Enumerates the GAC. /// ASM_CACHE_DOWNLOAD - Enumerates the assemblies that have been downloaded on-demand or that have been shadow-copied. /// </summary> [Flags] public enum AsmCacheFlags { AsmCacheZap = 0x1, AsmCacheGac = 0x2, AsmCacheDownload = 0x4 } /// <summary> /// The FUSION_INSTALL_REFERENCE structure represents a reference that is made when an application has installed an /// assembly in the GAC. /// The fields of the structure are defined as follows: /// cbSize - The size of the structure in bytes. /// dwFlags - Reserved, must be zero. /// guidScheme - The entity that adds the reference. /// szIdentifier - A unique string that identifies the application that installed the assembly. /// szNonCannonicalData - A string that is only understood by the entity that adds the reference. /// The GAC only stores this string. /// Possible values for the guidScheme field can be one of the following: /// FUSION_REFCOUNT_MSI_GUID - The assembly is referenced by an application that has been installed by using /// Windows Installer. The szIdentifier field is set to MSI, and szNonCannonicalData is set to Windows Installer. /// This scheme must only be used by Windows Installer itself. /// FUSION_REFCOUNT_UNINSTALL_SUBKEY_GUID - The assembly is referenced by an application that appears in Add/Remove /// Programs. The szIdentifier field is the token that is used to register the application with Add/Remove programs. /// FUSION_REFCOUNT_FILEPATH_GUID - The assembly is referenced by an application that is represented by a file in /// the file global::System. The szIdentifier field is the path to this file. /// FUSION_REFCOUNT_OPAQUE_STRING_GUID - The assembly is referenced by an application that is only represented /// by an opaque string. The szIdentifier is this opaque string. The GAC does not perform existence checking /// for opaque references when you remove this. /// </summary> [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct FusionInstallReference { public uint cbSize; public uint dwFlags; public Guid guidScheme; public string szIdentifier; public string szNonCannonicalData; } /// <summary> /// The ASSEMBLY_INFO structure represents information about an assembly in the assembly cache. /// The fields of the structure are defined as follows: /// cbAssemblyInfo - Size of the structure in bytes. Permits additions to the structure in future version of the .NET Framework. /// dwAssemblyFlags - Indicates one or more of the ASSEMBLYINFO_FLAG_* bits. /// uliAssemblySizeInKB - The size of the files that make up the assembly in kilobytes (KB). /// pszCurrentAssemblyPathBuf - A pointer to a string buffer that holds the current path of the directory that contains the /// files that make up the assembly. The path must end with a zero. /// cchBuf - Size of the buffer that the pszCurrentAssemblyPathBug field points to. /// dwAssemblyFlags can have one of the following values: /// ASSEMBLYINFO_FLAG__INSTALLED - Indicates that the assembly is actually installed. Always set in current version of the /// .NET Framework. /// ASSEMBLYINFO_FLAG__PAYLOADRESIDENT - Never set in the current version of the .NET Framework. /// </summary> [StructLayout(LayoutKind.Sequential, CharSet=CharSet.Unicode)] public struct AssemblyInfo { public uint cbAssemblyInfo; public uint dwAssemblyFlags; public ulong uliAssemblySizeInKB; public string pszCurrentAssemblyPathBuf; public uint cchBuf; } public class AssemblyCache { /// <summary> /// The key entry point for reading the assembly cache. /// </summary> /// <param name="ppAsmCache">Pointer to return IAssemblyCache</param> /// <param name="dwReserved">must be 0</param> [SecurityCritical] [DllImport("fusion.dll", SetLastError=true, PreserveSig=false)] public static extern void CreateAssemblyCache(out IAssemblyCache ppAsmCache, uint dwReserved); /// <summary> /// An instance of IAssemblyName is obtained by calling the CreateAssemblyNameObject API. /// </summary> /// <param name="ppAssemblyNameObj">Pointer to a memory location that receives the IAssemblyName pointer that is created.</param> /// <param name="szAssemblyName">A string representation of the assembly name or of a full assembly reference that is /// determined by dwFlags. The string representation can be null.</param> /// <param name="dwFlags">Zero or more of the bits that are defined in the CREATE_ASM_NAME_OBJ_FLAGS enumeration.</param> /// <param name="pvReserved"> Must be null.</param> [SecurityCritical] [DllImport("fusion.dll", SetLastError=true, CharSet=CharSet.Unicode, PreserveSig=false)] public static extern void CreateAssemblyNameObject(out IAssemblyName ppAssemblyNameObj, string szAssemblyName, uint dwFlags, IntPtr pvReserved); /// <summary> /// To obtain an instance of the CreateAssemblyEnum API, call the CreateAssemblyNameObject API. /// </summary> /// <param name="pEnum">Pointer to a memory location that contains the IAssemblyEnum pointer.</param> /// <param name="pUnkReserved">Must be null.</param> /// <param name="pName">An assembly name that is used to filter the enumeration. Can be null to enumerate all assemblies in the GAC.</param> /// <param name="dwFlags">Exactly one bit from the ASM_CACHE_FLAGS enumeration.</param> /// <param name="pvReserved">Must be NULL.</param> [SecurityCritical] [DllImport("fusion.dll", SetLastError=true, PreserveSig=false)] public static extern void CreateAssemblyEnum(out IAssemblyEnum pEnum, IntPtr pUnkReserved, IAssemblyName pName, AsmCacheFlags dwFlags, IntPtr pvReserved); /// <summary> /// To obtain an instance of the CreateInstallReferenceEnum API, call the CreateInstallReferenceEnum API. /// </summary> /// <param name="ppRefEnum">A pointer to a memory location that receives the IInstallReferenceEnum pointer.</param> /// <param name="pName">The assembly name for which the references are enumerated.</param> /// <param name="dwFlags"> Must be zero.</param> /// <param name="pvReserved">Must be null.</param> [SecurityCritical] [DllImport("fusion.dll", SetLastError=true, PreserveSig=false)] public static extern void CreateInstallReferenceEnum(out IInstallReferenceEnum ppRefEnum, IAssemblyName pName, uint dwFlags, IntPtr pvReserved); /// <summary> /// The GetCachePath API returns the storage location of the GAC. /// </summary> /// <param name="dwCacheFlags">Exactly one of the bits defined in the ASM_CACHE_FLAGS enumeration.</param> /// <param name="pwzCachePath">Pointer to a buffer that is to receive the path of the GAC as a Unicode string.</param> /// <param name="pcchPath">Length of the pwszCachePath buffer, in Unicode characters.</param> [SecurityCritical] [DllImport("fusion.dll", SetLastError=true, CharSet=CharSet.Unicode, PreserveSig=false)] public static extern void GetCachePath(AsmCacheFlags dwCacheFlags, [MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwzCachePath, ref uint pcchPath); /// <summary> /// GUID value for element guidScheme in the struct FUSION_INSTALL_REFERENCE /// The assembly is referenced by an application that has been installed by using Windows Installer. /// The szIdentifier field is set to MSI, and szNonCannonicalData is set to Windows Installer. /// This scheme must only be used by Windows Installer itself. /// </summary> public static Guid FusionRefcountUninstallSubkeyGuid => new Guid("8cedc215-ac4b-488b-93c0-a50a49cb2fb8"); /// <summary> /// GUID value for element guidScheme in the struct FUSION_INSTALL_REFERENCE /// /// </summary> public static Guid FusionRefcountFilepathGuid => new Guid("b02f9d65-fb77-4f7a-afa5-b391309f11c9"); /// <summary> /// GUID value for element guidScheme in the struct FUSION_INSTALL_REFERENCE /// /// </summary> public static Guid FusionRefcountOpaqueStringGuid => new Guid("2ec93463-b0c3-45e1-8364-327e96aea856"); /// <summary> /// GUID value for element guidScheme in the struct FUSION_INSTALL_REFERENCE /// /// </summary> public static Guid FusionRefcountMsiGuid => new Guid("25df0fc1-7f97-4070-add7-4b13bbfd7cb8"); /// <summary> /// Use this method as a start for the GAC API /// </summary> /// <returns>IAssemblyCache COM interface</returns> public static IAssemblyCache CreateAssemblyCache() { CreateAssemblyCache(out IAssemblyCache ac, 0); return ac; } public static IAssemblyName CreateAssemblyName(string name) { CreateAssemblyNameObject(out IAssemblyName an, name, 2, (IntPtr)0); return an; } [NotNull] public static string GetDisplayName([NotNull] IAssemblyName name, AsmDisplayFlags which) { uint bufferSize = 255; StringBuilder buffer = new StringBuilder((int) bufferSize); name.GetDisplayName(buffer, ref bufferSize, which); return buffer.ToString(); } [NotNull] public static string GetName([NotNull] IAssemblyName name) { uint bufferSize = 255; StringBuilder buffer = new StringBuilder((int) bufferSize); name.GetName(ref bufferSize, buffer); return buffer.ToString(); } [NotNull] public static AssemblyName GetAssemblyName([NotNull] IAssemblyName nameRef) { AssemblyName name = new AssemblyName { Name = GetName(nameRef), Version = GetVersion(nameRef), CultureInfo = GetCulture(nameRef) }; name.SetPublicKeyToken(GetPublicKeyToken(nameRef)); return name; } [NotNull] public static System.Version GetVersion([NotNull] IAssemblyName name) { name.GetVersion(out uint major, out uint minor); return new System.Version((int)major >> 16, (int)major & 0xFFFF, (int)minor >> 16, (int)minor & 0xFFFF); } [NotNull] public static byte[] GetPublicKeyToken([NotNull] IAssemblyName name) { byte[] result = new byte[8]; uint bufferSize = 8; IntPtr buffer = Marshal.AllocHGlobal((int) bufferSize); name.GetProperty(AsmName.AsmNamePublicKeyToken, buffer, ref bufferSize); for (int i = 0; i < 8; i++) result[i] = Marshal.ReadByte(buffer, i); Marshal.FreeHGlobal(buffer); return result; } [NotNull] public static byte[] GetPublicKey([NotNull] IAssemblyName name) { uint bufferSize = 512; IntPtr buffer = Marshal.AllocHGlobal((int) bufferSize); name.GetProperty(AsmName.AsmNamePublicKey, buffer, ref bufferSize); byte[] result = new byte[bufferSize]; for (int i = 0; i < bufferSize; i++) result[i] = Marshal.ReadByte(buffer, i); Marshal.FreeHGlobal(buffer); return result; } [NotNull] public static CultureInfo GetCulture([NotNull] IAssemblyName name) { uint bufferSize = 255; IntPtr buffer = Marshal.AllocHGlobal((int) bufferSize); name.GetProperty(AsmName.AsmNameCulture, buffer, ref bufferSize); string result = Marshal.PtrToStringAuto(buffer); Marshal.FreeHGlobal(buffer); return result == null ? CultureInfoHelper.Default : new CultureInfo(result); } public static IAssemblyEnum CreateGacEnum() { CreateAssemblyEnum(out IAssemblyEnum ae, (IntPtr)0, null, AsmCacheFlags.AsmCacheGac, (IntPtr)0); return ae; } /// <summary> /// Get the next assembly name in the current enumerator or fail /// </summary> /// <param name="enumerator"></param> /// <param name="name"></param> /// <returns>0 if the enumeration is not at its end</returns> public static int GetNextAssembly([NotNull] IAssemblyEnum enumerator, out IAssemblyName name) { return enumerator.GetNextAssembly((IntPtr)0, out name, 0); } [NotNull] public static string GetGACPath() { uint bufferSize = 255; StringBuilder buffer = new StringBuilder((int) bufferSize); GetCachePath(AsmCacheFlags.AsmCacheGac, buffer, ref bufferSize); return buffer.ToString(); } [NotNull] public static string GetZapPath() { uint bufferSize = 255; StringBuilder buffer = new StringBuilder((int) bufferSize); GetCachePath(AsmCacheFlags.AsmCacheZap, buffer, ref bufferSize); return buffer.ToString(); } [NotNull] public static string GetDownloadPath() { uint bufferSize = 255; StringBuilder buffer = new StringBuilder((int) bufferSize); GetCachePath(AsmCacheFlags.AsmCacheDownload, buffer, ref bufferSize); return buffer.ToString(); } } /// <summary> /// The IAssemblyCache interface is the top-level interface that provides access to the GAC. /// </summary> [ComImport, Guid("e707dcde-d1cd-11d2-bab9-00c04f8eceae"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IAssemblyCache { /// <summary> /// The IAssemblyCache::UninstallAssembly method removes a reference to an assembly from the GAC. /// If other applications hold no other references to the assembly, the files that make up the assembly are removed from the GAC. /// </summary> /// <param name="dwFlags">No flags defined. Must be zero.</param> /// <param name="pszAssemblyName">The name of the assembly. A zero-ended Unicode string.</param> /// <param name="pRefData">A pointer to a FUSION_INSTALL_REFERENCE structure. Although this is not recommended, /// this parameter can be null. The assembly is installed without an application reference, or all existing application /// references are gone.</param> /// <param name="pulDisposition">Pointer to an integer that indicates the action that is performed by the function.</param> /// <returns>The return values are defined as follows: /// S_OK - The assembly has been uninstalled. /// S_FALSE - The operation succeeded, but the assembly was not removed from the GAC. /// The reason is described in pulDisposition.</returns> /// <remarks> /// NOTE: If pulDisposition is not null, pulDisposition contains one of the following values: /// IASSEMBLYCACHE_UNINSTALL_DISPOSITION_UNINSTALLED - The assembly files have been removed from the GAC. /// IASSEMBLYCACHE_UNINSTALL_DISPOSITION_STILL_IN_USE - An application is using the assembly. /// This value is returned on Microsoft Windows 95 and Microsoft Windows 98. /// IASSEMBLYCACHE_UNINSTALL_DISPOSITION_ALREADY_UNINSTALLED - The assembly does not exist in the GAC. /// IASSEMBLYCACHE_UNINSTALL_DISPOSITION_DELETE_PENDING - Not used. /// IASSEMBLYCACHE_UNINSTALL_DISPOSITION_HAS_INSTALL_REFERENCES - The assembly has not been removed from the GAC because /// another application reference exists. /// IASSEMBLYCACHE_UNINSTALL_DISPOSITION_REFERENCE_NOT_FOUND - The reference that is specified in pRefData is not found /// in the GAC. /// </remarks> [PreserveSig] int UninstallAssembly( uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, [MarshalAs(UnmanagedType.LPArray)] FusionInstallReference[] pRefData, out uint pulDisposition); /// <summary> /// The IAssemblyCache::QueryAssemblyInfo method retrieves information about an assembly from the GAC. /// </summary> /// <param name="dwFlags">One of QUERYASMINFO_FLAG_VALIDATE or QUERYASMINFO_FLAG_GETSIZE: /// *_VALIDATE - Performs validation of the files in the GAC against the assembly manifest, including hash verification /// and strong name signature verification. /// *_GETSIZE - Returns the size of all files in the assembly (disk footprint). If this is not specified, the /// ASSEMBLY_INFO::uliAssemblySizeInKB field is not modified.</param> /// <param name="pszAssemblyName"></param> /// <param name="pAsmInfo"></param> /// <returns></returns> [PreserveSig] int QueryAssemblyInfo( uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName, ref AssemblyInfo pAsmInfo); /// <summary> /// Undocumented /// </summary> /// <param name="dwFlags"></param> /// <param name="pvReserved"></param> /// <param name="ppAsmItem"></param> /// <param name="pszAssemblyName"></param> /// <returns></returns> [PreserveSig] int CreateAssemblyCacheItem( uint dwFlags, IntPtr pvReserved, out IAssemblyCacheItem ppAsmItem, [MarshalAs(UnmanagedType.LPWStr)] string pszAssemblyName); /// <summary> /// Undocumented /// </summary> /// <param name="ppAsmScavenger"></param> /// <returns></returns> [PreserveSig] int CreateAssemblyScavenger( [MarshalAs(UnmanagedType.IUnknown)] out object ppAsmScavenger); /// <summary> /// The IAssemblyCache::InstallAssembly method adds a new assembly to the GAC. The assembly must be persisted in the file /// system and is copied to the GAC. /// </summary> /// <param name="dwFlags">At most, one of the bits of the IASSEMBLYCACHE_INSTALL_FLAG_* values can be specified: /// *_REFRESH - If the assembly is already installed in the GAC and the file version numbers of the assembly being /// installed are the same or later, the files are replaced. /// *_FORCE_REFRESH - The files of an existing assembly are overwritten regardless of their version number.</param> /// <param name="pszManifestFilePath"> A string pointing to the dynamic-linked library (DLL) that contains the assembly manifest. /// Other assembly files must reside in the same directory as the DLL that contains the assembly manifest.</param> /// <param name="pRefData">A pointer to a FUSION_INSTALL_REFERENCE that indicates the application on whose behalf the /// assembly is being installed. Although this is not recommended, this parameter can be null, but this leaves the assembly /// without any application reference.</param> /// <returns></returns> [PreserveSig] int InstallAssembly( uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszManifestFilePath, [MarshalAs(UnmanagedType.LPArray)] FusionInstallReference[] pRefData); } /// <summary> /// The IAssemblyName interface represents an assembly name. An assembly name includes a predetermined set of name-value pairs. /// The assembly name is described in detail in the .NET Framework SDK. /// </summary> [ComImport, Guid("CD193BC0-B4BC-11d2-9833-00C04FC31D2E"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IAssemblyName { /// <summary> /// The IAssemblyName::SetProperty method adds a name-value pair to the assembly name, or, if a name-value pair /// with the same name already exists, modifies or deletes the value of a name-value pair. /// </summary> /// <param name="propertyId">The ID that represents the name part of the name-value pair that is to be /// added or to be modified. Valid property IDs are defined in the ASM_NAME enumeration.</param> /// <param name="pvProperty">A pointer to a buffer that contains the value of the property.</param> /// <param name="cbProperty">The length of the pvProperty buffer in bytes. If cbProperty is zero, the name-value pair /// is removed from the assembly name.</param> /// <returns></returns> [PreserveSig] int SetProperty( AsmName propertyId, IntPtr pvProperty, uint cbProperty); /// <summary> /// The IAssemblyName::GetProperty method retrieves the value of a name-value pair in the assembly name that specifies the name. /// </summary> /// <param name="propertyId">The ID that represents the name of the name-value pair whose value is to be retrieved. /// Specified property IDs are defined in the ASM_NAME enumeration.</param> /// <param name="pvProperty">A pointer to a buffer that is to contain the value of the property.</param> /// <param name="pcbProperty">The length of the pvProperty buffer, in bytes.</param> /// <returns></returns> [PreserveSig] int GetProperty( AsmName propertyId, IntPtr pvProperty, ref uint pcbProperty); /// *_VERSION - Includes the version number as part of the display name. /// *_CULTURE - Includes the culture. /// *_PUBLIC_KEY_TOKEN - Includes the public key token. /// *_PUBLIC_KEY - Includes the public key. /// *_CUSTOM - Includes the custom part of the assembly name. /// *_PROCESSORARCHITECTURE - Includes the processor architecture. /// *_LANGUAGEID - Includes the language ID. /// <remarks>http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcondefaultmarshalingforstrings.asp</remarks> [PreserveSig] int GetDisplayName( [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder szDisplayName, ref uint pccDisplayName, AsmDisplayFlags dwDisplayFlags); /// <summary> /// Undocumented /// </summary> /// <param name="refIid"></param> /// <param name="pUnkSink"></param> /// <param name="pUnkContext"></param> /// <param name="szCodeBase"></param> /// <param name="llFlags"></param> /// <param name="pvReserved"></param> /// <param name="cbReserved"></param> /// <param name="ppv"></param> /// <returns></returns> [PreserveSig] int BindToObject( ref Guid refIid, [MarshalAs(UnmanagedType.IUnknown)] object pUnkSink, [MarshalAs(UnmanagedType.IUnknown)] object pUnkContext, [MarshalAs(UnmanagedType.LPWStr)] string szCodeBase, long llFlags, IntPtr pvReserved, uint cbReserved, out IntPtr ppv); /// <summary> /// The IAssemblyName::GetName method returns the name part of the assembly name. /// </summary> /// <param name="lpcwBuffer">Size of the pwszName buffer (on input). Length of the name (on return).</param> /// <param name="pwzName">Pointer to the buffer that is to contain the name part of the assembly name.</param> /// <returns></returns> /// <remarks>http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpcondefaultmarshalingforstrings.asp</remarks> [PreserveSig] int GetName( ref uint lpcwBuffer, [Out, MarshalAs(UnmanagedType.LPWStr)] StringBuilder pwzName); /// <summary> /// The IAssemblyName::GetVersion method returns the version part of the assembly name. /// </summary> /// <param name="pdwVersionHi">Pointer to a DWORD that contains the upper 32 bits of the version number.</param> /// <param name="pdwVersionLow">Pointer to a DWORD that contain the lower 32 bits of the version number.</param> /// <returns></returns> [PreserveSig] int GetVersion( out uint pdwVersionHi, out uint pdwVersionLow); /// <summary> /// The IAssemblyName::IsEqual method compares the assembly name to another assembly names. /// </summary> /// <param name="pName">The assembly name to compare to.</param> /// <param name="dwCmpFlags">Indicates which part of the assembly name to use in the comparison. /// Values are one or more of the bits defined in the ASM_CMP_FLAGS enumeration.</param> /// <returns></returns> [PreserveSig] int IsEqual( IAssemblyName pName, AsmCmpFlags dwCmpFlags); /// <summary> /// The IAssemblyName::Clone method creates a copy of an assembly name. /// </summary> /// <param name="pName"></param> /// <returns></returns> [PreserveSig] int Clone( out IAssemblyName pName); } /// <summary> /// The IAssemblyEnum interface enumerates the assemblies in the GAC. /// </summary> [ComImport, Guid("21b8916c-f28e-11d2-a473-00c04f8ef448"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IAssemblyEnum { /// <summary> /// The IAssemblyEnum::GetNextAssembly method enumerates the assemblies in the GAC. /// </summary> /// <param name="pvReserved">Must be null.</param> /// <param name="ppName">Pointer to a memory location that is to receive the interface pointer to the assembly /// name of the next assembly that is enumerated.</param> /// <param name="dwFlags">Must be zero.</param> /// <returns></returns> [PreserveSig] int GetNextAssembly( IntPtr pvReserved, out IAssemblyName ppName, uint dwFlags); /// <summary> /// Undocumented. Best guess: reset the enumeration to the first assembly. /// </summary> /// <returns></returns> [PreserveSig] int Reset(); /// <summary> /// Undocumented. Create a copy of the assembly enum that is independently enumerable. /// </summary> /// <param name="ppEnum"></param> /// <returns></returns> [PreserveSig] int Clone( out IAssemblyEnum ppEnum); } /// <summary> /// The IInstallReferenceItem interface represents a reference that has been set on an assembly in the GAC. /// Instances of IInstallReferenceIteam are returned by the IInstallReferenceEnum interface. /// </summary> [ComImport, Guid("582dac66-e678-449f-aba6-6faaec8a9394"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInstallReferenceItem { /// <summary> /// The IInstallReferenceItem::GetReference method returns a FUSION_INSTALL_REFERENCE structure. /// </summary> /// <param name="ppRefData">A pointer to a FUSION_INSTALL_REFERENCE structure. The memory is allocated by the GetReference /// method and is freed when IInstallReferenceItem is released. Callers must not hold a reference to this buffer after the /// IInstallReferenceItem object is released.</param> /// <param name="dwFlags">Must be zero.</param> /// <param name="pvReserved">Must be null.</param> /// <returns></returns> [PreserveSig] int GetReference( [MarshalAs(UnmanagedType.LPArray)] out FusionInstallReference[] ppRefData, uint dwFlags, IntPtr pvReserved); } /// <summary> /// The IInstallReferenceEnum interface enumerates all references that are set on an assembly in the GAC. /// NOTE: References that belong to the assembly are locked for changes while those references are being enumerated. /// </summary> [ComImport, Guid("56b1a988-7c0c-4aa2-8639-c3eb5a90226f"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInstallReferenceEnum { /// <summary> /// IInstallReferenceEnum::GetNextInstallReferenceItem returns the next reference information for an assembly. /// </summary> /// <param name="ppRefItem">Pointer to a memory location that receives the IInstallReferenceItem pointer.</param> /// <param name="dwFlags">Must be zero.</param> /// <param name="pvReserved">Must be null.</param> /// <returns></returns> [PreserveSig] int GetNextInstallReferenceItem( out IInstallReferenceItem ppRefItem, uint dwFlags, IntPtr pvReserved); } /// <summary> /// Undocumented. Probably only for internal use. /// <see cref="IAssemblyCache.CreateAssemblyCacheItem"/> /// </summary> [ComImport, Guid("9E3AAEB4-D1CD-11D2-BAB9-00C04F8ECEAE"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IAssemblyCacheItem { /// <summary> /// Undocumented. /// </summary> /// <param name="dwFlags"></param> /// <param name="pszStreamName"></param> /// <param name="dwFormat"></param> /// <param name="dwFormatFlags"></param> /// <param name="ppIStream"></param> /// <param name="puliMaxSize"></param> void CreateStream( uint dwFlags, [MarshalAs(UnmanagedType.LPWStr)] string pszStreamName, uint dwFormat, uint dwFormatFlags, out IStream ppIStream, ref long puliMaxSize); /// <summary> /// Undocumented. /// </summary> /// <param name="dwFlags"></param> /// <param name="pulDisposition"></param> void Commit( uint dwFlags, out long pulDisposition); /// <summary> /// Undocumented. /// </summary> void AbortItem(); }
39.878788
157
0.749652
[ "MIT" ]
asm2025/essentialMix
Standard/essentialMix/Helpers/GACHelper.cs
31,584
C#
using System; using System.Collections.Generic; using System.Text; namespace Raiding.Models { public class Paladin : BaseHero { private const int power = 100; public Paladin(string name) : base(name) { this.Power = power; } public override string CastAbility() => $"{this.GetType().Name} - {this.Name} healed for {this.Power}"; } }
22.052632
74
0.579952
[ "MIT" ]
ivaylo-R/CSharp-OOP-Exercises
Polymorphism - Exercise/Raiding/Models/Paladin.cs
421
C#
/* * TaskServicer.cs * * @Author Magnus Hjorth * * File Description: This class holds static methods needed to create and destroy windows tasks, * allowing the program to be automatically started with admin rights on startup. */ using Microsoft.Win32.TaskScheduler; using System.IO; using System.Windows.Forms; namespace Builder_Companion { public static class TaskServicer { private const string taskDef = "BUILDER_COMPANION"; /// <summary> /// Creates a Windows Task which will start up this application with admin rights at every startup. /// </summary> public static void CreateTaskService() { TaskService ts = new TaskService(); TaskDefinition td = ts.NewTask(); td.Principal.RunLevel = TaskRunLevel.Highest; td.Triggers.AddNew(TaskTriggerType.Logon); //td.Triggers.AddNew(TaskTriggerType.Once); string program_path = Path.Combine(Application.ExecutablePath); td.Actions.Add(new ExecAction(program_path, null)); ts.RootFolder.RegisterTaskDefinition(taskDef, td); } /// <summary> /// Deletes the Windows Task for this application if any. /// </summary> public static void DeleteTaskService() { EnumAllTasks(); } private static void EnumAllTasks() { EnumFolderTasks(TaskService.Instance.RootFolder); } private static void EnumFolderTasks(TaskFolder fld) { foreach (Task task in fld.Tasks) DeleteTask(task); foreach (TaskFolder sfld in fld.SubFolders) EnumFolderTasks(sfld); } private static void DeleteTask(Task t) { // Only delete if our task if (t.Name.Equals(taskDef)) { TaskService ts = t.TaskService; ts.RootFolder.DeleteTask(t.Name); } } } }
30.521739
154
0.5717
[ "MIT" ]
mgnush/Builder-Companion
TaskServicer.cs
2,108
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Numerics; using osu.Game.Rulesets.Difficulty.Preprocessing; using osu.Game.Rulesets.Objects; using osu.Game.Rulesets.Osu.Objects; namespace osu.Game.Rulesets.Osu.Difficulty.Preprocessing { public class OsuDifficultyHitObject : DifficultyHitObject { private const int normalized_radius = 50; // Change radius to 50 to make 100 the diameter. Easier for mental maths. private const int min_delta_time = 25; private const float maximum_slider_radius = normalized_radius * 2.4f; private const float assumed_slider_radius = normalized_radius * 1.65f; protected new OsuHitObject BaseObject => (OsuHitObject)base.BaseObject; /// <summary> /// Normalized distance from the end position of the previous <see cref="OsuDifficultyHitObject"/> to the start position of this <see cref="OsuDifficultyHitObject"/>. /// </summary> public double JumpDistance { get; private set; } /// <summary> /// Minimum distance from the end position of the previous <see cref="OsuDifficultyHitObject"/> to the start position of this <see cref="OsuDifficultyHitObject"/>. /// </summary> public double MovementDistance { get; private set; } /// <summary> /// Normalized distance between the start and end position of the previous <see cref="OsuDifficultyHitObject"/>. /// </summary> public double TravelDistance { get; private set; } /// <summary> /// Angle the player has to take to hit this <see cref="OsuDifficultyHitObject"/>. /// Calculated as the angle between the circles (current-2, current-1, current). /// </summary> public double? Angle { get; private set; } /// <summary> /// Milliseconds elapsed since the end time of the previous <see cref="OsuDifficultyHitObject"/>, with a minimum of 25ms. /// </summary> public double MovementTime { get; private set; } /// <summary> /// Milliseconds elapsed since the start time of the previous <see cref="OsuDifficultyHitObject"/> to the end time of the same previous <see cref="OsuDifficultyHitObject"/>, with a minimum of 25ms. /// </summary> public double TravelTime { get; private set; } /// <summary> /// Milliseconds elapsed since the start time of the previous <see cref="OsuDifficultyHitObject"/>, with a minimum of 25ms. /// </summary> public readonly double StrainTime; private readonly OsuHitObject lastLastObject; private readonly OsuHitObject lastObject; public OsuDifficultyHitObject(HitObject hitObject, HitObject lastLastObject, HitObject lastObject, double clockRate) : base(hitObject, lastObject, clockRate) { this.lastLastObject = (OsuHitObject)lastLastObject; this.lastObject = (OsuHitObject)lastObject; // Capped to 25ms to prevent difficulty calculation breaking from simultaneous objects. StrainTime = Math.Max(DeltaTime, min_delta_time); setDistances(clockRate); } private void setDistances(double clockRate) { // We don't need to calculate either angle or distance when one of the last->curr objects is a spinner if (BaseObject is Spinner || lastObject is Spinner) return; // We will scale distances by this factor, so we can assume a uniform CircleSize among beatmaps. float scalingFactor = normalized_radius / (float)BaseObject.Radius; if (BaseObject.Radius < 30) { float smallCircleBonus = Math.Min(30 - (float)BaseObject.Radius, 5) / 50; scalingFactor *= 1 + smallCircleBonus; } Vector2 lastCursorPosition = getEndCursorPosition(lastObject); JumpDistance = (BaseObject.StackedPosition * scalingFactor - lastCursorPosition * scalingFactor).Length(); if (lastObject is Slider lastSlider) { computeSliderCursorPosition(lastSlider); TravelDistance = lastSlider.LazyTravelDistance; TravelTime = Math.Max(lastSlider.LazyTravelTime / clockRate, min_delta_time); MovementTime = Math.Max(StrainTime - TravelTime, min_delta_time); // Jump distance from the slider tail to the next object, as opposed to the lazy position of JumpDistance. float tailJumpDistance = Vector2.Subtract(lastSlider.TailCircle.StackedPosition, BaseObject.StackedPosition).Length() * scalingFactor; // For hitobjects which continue in the direction of the slider, the player will normally follow through the slider, // such that they're not jumping from the lazy position but rather from very close to (or the end of) the slider. // In such cases, a leniency is applied by also considering the jump distance from the tail of the slider, and taking the minimum jump distance. // Additional distance is removed based on position of jump relative to slider follow circle radius. // JumpDistance is the leniency distance beyond the assumed_slider_radius. tailJumpDistance is maximum_slider_radius since the full distance of radial leniency is still possible. MovementDistance = Math.Max(0, Math.Min(JumpDistance - (maximum_slider_radius - assumed_slider_radius), tailJumpDistance - maximum_slider_radius)); } else { MovementTime = StrainTime; MovementDistance = JumpDistance; } if (lastLastObject != null && !(lastLastObject is Spinner)) { Vector2 lastLastCursorPosition = getEndCursorPosition(lastLastObject); Vector2 v1 = lastLastCursorPosition - lastObject.StackedPosition; Vector2 v2 = BaseObject.StackedPosition - lastCursorPosition; float dot = Vector2.Dot(v1, v2); float det = v1.X * v2.Y - v1.Y * v2.X; Angle = Math.Abs(Math.Atan2(det, dot)); } } private void computeSliderCursorPosition(Slider slider) { if (slider.LazyEndPosition != null) return; slider.LazyTravelTime = slider.NestedHitObjects[^1].StartTime - slider.StartTime; double endTimeMin = slider.LazyTravelTime / slider.SpanDuration; if (endTimeMin % 2 >= 1) endTimeMin = 1 - endTimeMin % 1; else endTimeMin %= 1; slider.LazyEndPosition = slider.StackedPosition + slider.Path.PositionAt(endTimeMin); // temporary lazy end position until a real result can be derived. var currCursorPosition = slider.StackedPosition; double scalingFactor = normalized_radius / slider.Radius; // lazySliderDistance is coded to be sensitive to scaling, this makes the maths easier with the thresholds being used. for (int i = 1; i < slider.NestedHitObjects.Count; i++) { var currMovementObj = (OsuHitObject)slider.NestedHitObjects[i]; Vector2 currMovement = Vector2.Subtract(currMovementObj.StackedPosition, currCursorPosition); double currMovementLength = scalingFactor * currMovement.Length(); // Amount of movement required so that the cursor position needs to be updated. double requiredMovement = assumed_slider_radius; if (i == slider.NestedHitObjects.Count - 1) { // The end of a slider has special aim rules due to the relaxed time constraint on position. // There is both a lazy end position as well as the actual end slider position. We assume the player takes the simpler movement. // For sliders that are circular, the lazy end position may actually be farther away than the sliders true end. // This code is designed to prevent buffing situations where lazy end is actually a less efficient movement. Vector2 lazyMovement = Vector2.Subtract((Vector2)slider.LazyEndPosition, currCursorPosition); if (lazyMovement.Length() < currMovement.Length()) currMovement = lazyMovement; currMovementLength = scalingFactor * currMovement.Length(); } else if (currMovementObj is SliderRepeat) { // For a slider repeat, assume a tighter movement threshold to better assess repeat sliders. requiredMovement = normalized_radius; } if (currMovementLength > requiredMovement) { // this finds the positional delta from the required radius and the current position, and updates the currCursorPosition accordingly, as well as rewarding distance. currCursorPosition = Vector2.Add(currCursorPosition, Vector2.Multiply(currMovement, (float)((currMovementLength - requiredMovement) / currMovementLength))); currMovementLength *= (currMovementLength - requiredMovement) / currMovementLength; slider.LazyTravelDistance += (float)currMovementLength; } if (i == slider.NestedHitObjects.Count - 1) slider.LazyEndPosition = currCursorPosition; } slider.LazyTravelDistance *= (float)Math.Pow(1 + slider.RepeatCount / 2.5, 1.0 / 2.5); // Bonus for repeat sliders until a better per nested object strain system can be achieved. } private Vector2 getEndCursorPosition(OsuHitObject hitObject) { Vector2 pos = hitObject.StackedPosition; if (hitObject is Slider slider) { computeSliderCursorPosition(slider); pos = slider.LazyEndPosition ?? pos; } return pos; } } }
51.960396
206
0.62862
[ "MIT" ]
Azyyyyyy/osu
osu.Game.Rulesets.Osu/Difficulty/Preprocessing/OsuDifficultyHitObject.cs
10,295
C#
using Gedcom4Sharp.Models.Gedcom; using Gedcom4Sharp.Parser; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Threading.Tasks; namespace Gedcom4Sharp.Tests.Parser { [TestClass] public class FamilyEventTypeParser { private Gedcom g; [TestInitialize] public async Task TestInitialize() { var gp = new GedcomParser(); await gp.Load(@"Assets\Samples\TGC551.ged"); g = gp.Gedcom; } /// <summary> /// Positive test case for google code issue 2 /// </summary> [TestMethod] public void TestIssue2() { int familyCount = g.Families.Count; int events = 0; foreach(var fam in g.Families.Values) { if(fam.Events != null) { foreach(var ev in fam.Events) { Assert.IsNotNull(ev.Type); events++; } } } Assert.IsTrue(events > 0); Assert.AreEqual(7, familyCount); } } }
25.217391
56
0.493103
[ "MIT" ]
ThomasPe/Gedcom4Sharp
Gedcom4Sharp.Tests/Parser/FamilyEventTypeParser.Tests.cs
1,162
C#
using System; using System.Collections.Generic; using System.Linq; namespace _01.Max_Sequence_of_Equal_Elements { class MaxSequenceOfEqualElements { static void Main() { List<int> numbers = Console.ReadLine().Split().Select(int.Parse).ToList(); List<int> currSubsequence = new List<int>(); List<int> longestSubsequence = new List<int>(); currSubsequence.Add(numbers[0]); for (int i = 1; i < numbers.Count; i++) { if (currSubsequence[0] == numbers[i]) { currSubsequence.Add(numbers[i]); } else { if (currSubsequence.Count > longestSubsequence.Count) { longestSubsequence.Clear(); longestSubsequence.AddRange(currSubsequence); } currSubsequence.Clear(); currSubsequence.Add(numbers[i]); } } if (currSubsequence.Count > longestSubsequence.Count) { longestSubsequence.Clear(); longestSubsequence.AddRange(currSubsequence); } Console.WriteLine(string.Join(" ", longestSubsequence)); } } }
28.851064
86
0.497788
[ "MIT" ]
IvelinMarinov/SoftUni
02. Programming Fundamentals - Jan2017/05. Lists - Exercises/01. Max Sequence of Equal Elements/MaxSequenceOfEqualElements.cs
1,358
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Diagnostics.CodeAnalysis; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http.Controllers; namespace System.Web.Http.Filters { public interface IAuthorizationFilter : IFilter { [SuppressMessage( "Microsoft.Design", "CA1006:DoNotNestGenericTypesInMemberSignatures", Justification = "Represents a continuation call" )] Task<HttpResponseMessage> ExecuteAuthorizationFilterAsync( HttpActionContext actionContext, CancellationToken cancellationToken, Func<Task<HttpResponseMessage>> continuation ); } }
32.461538
111
0.707346
[ "Apache-2.0" ]
belav/AspNetWebStack
src/System.Web.Http/Filters/IAuthorizationFilter.cs
846
C#
// © XIV-Tools. // Licensed under the MIT license. namespace TexToolsModExtractor.Metadatas { using System; using System.Collections; using System.Collections.Generic; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Text; using FfxivResourceConverter; using FfxivResourceConverter.Resources; /// <summary> /// .meta files are an arbitrarily created fake file type used for storing and managing item metadata. /// /// A .meta "file" is composed of five elements. /// /// 1. An EQP entry (Part Hiding Information) /// 2. A Set of EQDP Entries (Racial Model Availability) /// 3. A Set of IMC Entries (IMC Part Hiding mask, etc.) /// 4. A set of EST Table Entries (Extra Skeleton References) /// 5. A GMP Entry (Gimmick/Visor Information) /// /// .meta files must be capable of being serialized and deserialized to a pure binary representation, /// for storage within DAT files or Modpack files if needed. /// </summary> public class Metadata { /// <summary> /// The available IMC entries for this item. (May be length 0). /// </summary> public List<Imc> ImcEntries = new List<Imc>(); /// <summary> /// The available EQDP entries for the item. (May be length 0). /// </summary> public Dictionary<XivRace, EquipmentDeformationParameter> EqdpEntries = new Dictionary<XivRace, EquipmentDeformationParameter>(); /// <summary> /// The available Extra Skeleton Table entries for the item. (May be length 0). /// </summary> public Dictionary<XivRace, ExtraSkeletonEntry> EstEntries = new Dictionary<XivRace, ExtraSkeletonEntry>(); /// <summary> /// The available Gimmick Paramater for the item. (May be null). /// </summary> public GimmickParameter GmpEntry; /// <summary> /// The available EQP entry for the item. (May be null). /// </summary> public EquipmentParameter EqpEntry = null; // The list of all playable races. private static readonly List<XivRace> PlayableRaces = new List<XivRace>() { XivRace.Hyur_Midlander_Male, XivRace.Hyur_Midlander_Female, XivRace.Hyur_Highlander_Male, XivRace.Hyur_Highlander_Female, XivRace.Elezen_Male, XivRace.Elezen_Female, XivRace.Miqote_Male, XivRace.Miqote_Female, XivRace.Roegadyn_Male, XivRace.Roegadyn_Female, XivRace.Lalafell_Male, XivRace.Lalafell_Female, XivRace.AuRa_Male, XivRace.AuRa_Female, XivRace.Hrothgar, XivRace.Viera, }; public enum XivRace { [Description("0101")] Hyur_Midlander_Male, [Description("0104")] Hyur_Midlander_Male_NPC, [Description("0201")] Hyur_Midlander_Female, [Description("0204")] Hyur_Midlander_Female_NPC, [Description("0301")] Hyur_Highlander_Male, [Description("0304")] Hyur_Highlander_Male_NPC, [Description("0401")] Hyur_Highlander_Female, [Description("0404")] Hyur_Highlander_Female_NPC, [Description("0501")] Elezen_Male, [Description("0504")] Elezen_Male_NPC, [Description("0601")] Elezen_Female, [Description("0604")] Elezen_Female_NPC, [Description("0701")] Miqote_Male, [Description("0704")] Miqote_Male_NPC, [Description("0801")] Miqote_Female, [Description("0804")] Miqote_Female_NPC, [Description("0901")] Roegadyn_Male, [Description("0904")] Roegadyn_Male_NPC, [Description("1001")] Roegadyn_Female, [Description("1004")] Roegadyn_Female_NPC, [Description("1101")] Lalafell_Male, [Description("1104")] Lalafell_Male_NPC, [Description("1201")] Lalafell_Female, [Description("1204")] Lalafell_Female_NPC, [Description("1301")] AuRa_Male, [Description("1304")] AuRa_Male_NPC, [Description("1401")] AuRa_Female, [Description("1404")] AuRa_Female_NPC, [Description("1501")] Hrothgar, [Description("1504")] Hrothgar_NPC, [Description("1801")] Viera, [Description("1804")] Viera_NPC, [Description("9104")] NPC_Male, [Description("9204")] NPC_Female, [Description("0000")] All_Races, [Description("0000")] Monster, [Description("0000")] DemiHuman, } /// <summary> /// Binary enum types for usage when serializing/deserializing the data in question. /// These values may be added to but should --NEVER BE CHANGED--, as existing Metadata /// entries will depend on the values of these enums. /// </summary> private enum MetaDataType : uint { Invalid = 0, Imc = 1, Eqdp = 2, Eqp = 3, Est = 4, Gmp = 5, } public static List<FileInfo> Expand(FileInfo file) { Metadata met = FromMeta(file); List<FileInfo> expandedfiles = new List<FileInfo>(); ConverterSettings settngs = new ConverterSettings(); for (int i = 0; i < met.ImcEntries.Count; i++) { string name = Path.GetFileNameWithoutExtension(file.FullName); FileInfo imcfile = new FileInfo(file.DirectoryName + "/" + name + "_imc_" + i); met.ImcEntries[i].ToImc(imcfile, settngs); expandedfiles.Add(imcfile); } /*foreach (KeyValuePair<XivRace, EquipmentDeformationParameter> entry in met.EqdpEntries) { } foreach (KeyValuePair<XivRace, ExtraSkeletonEntry> entry in met.EstEntries) { } GmpEntry; EqpEntry; */ return expandedfiles; } public static Metadata FromMeta(FileInfo file) { using BinaryReader reader = new BinaryReader(file.OpenRead()); uint version = reader.ReadUInt32(); // File path name. string path = string.Empty; char c; while ((c = reader.ReadChar()) != '\0') { path += c; } Console.WriteLine("WARNING: No slot for metadata!"); string slot = "UNK"; ////var root = await XivCache.GetFirstRoot(path); Metadata ret = new Metadata(); // General header data. uint headerCount = reader.ReadUInt32(); uint perHeaderSize = reader.ReadUInt32(); uint headerEntryStart = reader.ReadUInt32(); // Per-Segment Header data. reader.BaseStream.Seek(headerEntryStart, SeekOrigin.Begin); List<(MetaDataType type, uint offset, uint size)> entries = new List<(MetaDataType type, uint size, uint offset)>(); for (int i = 0; i < headerCount; i++) { // Save offset. long currentOffset = reader.BaseStream.Position; // Read data. MetaDataType type = (MetaDataType)reader.ReadUInt32(); uint offset = reader.ReadUInt32(); uint size = reader.ReadUInt32(); entries.Add((type, offset, size)); // Seek to next. reader.BaseStream.Seek(currentOffset + perHeaderSize, SeekOrigin.Begin); } (MetaDataType type, uint offset, uint size) imc = entries.FirstOrDefault(x => x.type == MetaDataType.Imc); if (imc.type != MetaDataType.Invalid) { reader.BaseStream.Seek(imc.offset, SeekOrigin.Begin); byte[] bytes = reader.ReadBytes((int)imc.size); // Deserialize IMC entry bytes here. ret.ImcEntries = DeserializeImcData(bytes, version); } (MetaDataType type, uint offset, uint size) eqp = entries.FirstOrDefault(x => x.type == MetaDataType.Eqp); if (eqp.type != MetaDataType.Invalid) { reader.BaseStream.Seek(eqp.offset, SeekOrigin.Begin); byte[] bytes = reader.ReadBytes((int)eqp.size); // Deserialize EQP entry bytes here. ret.EqpEntry = new EquipmentParameter(slot, bytes); ////ret.EqpEntry = DeserializeEqpData(bytes, root, version); } (MetaDataType type, uint offset, uint size) eqdp = entries.FirstOrDefault(x => x.type == MetaDataType.Eqdp); if (eqdp.type != MetaDataType.Invalid) { reader.BaseStream.Seek(eqdp.offset, SeekOrigin.Begin); byte[] bytes = reader.ReadBytes((int)eqdp.size); ret.EqdpEntries = DeserializeEqdpData(bytes, version); } (MetaDataType type, uint offset, uint size) est = entries.FirstOrDefault(x => x.type == MetaDataType.Est); if (est.type != MetaDataType.Invalid) { reader.BaseStream.Seek(est.offset, SeekOrigin.Begin); byte[] bytes = reader.ReadBytes((int)est.size); ret.EstEntries = DeserializeEstData(bytes, version); } (MetaDataType type, uint offset, uint size) gmp = entries.FirstOrDefault(x => x.type == MetaDataType.Gmp); if (gmp.type != MetaDataType.Invalid) { reader.BaseStream.Seek(gmp.offset, SeekOrigin.Begin); byte[] bytes = reader.ReadBytes((int)gmp.size); ret.GmpEntry = DeserializeGmpData(bytes, version); } // Done deserializing all the parts. return ret; } /// <summary> /// Deserializes the binary IMC data into a list of IMC entries. /// </summary> private static List<Imc> DeserializeImcData(byte[] data, uint dataVersion) { const int ImcSubEntrySize = 6; int entries = data.Length / ImcSubEntrySize; List<Imc> ret = new List<Imc>(); for (int i = 0; i < entries; i++) { byte[] entryData = data.Skip(i * ImcSubEntrySize).Take(ImcSubEntrySize).ToArray(); using BinaryReader br = new BinaryReader(new MemoryStream(entryData)); byte variant = br.ReadByte(); byte unknown = br.ReadByte(); ushort mask = br.ReadUInt16(); byte vfx = br.ReadByte(); byte anim = br.ReadByte(); ret.Add(new Imc() { MaterialSet = variant, Decal = unknown, Mask = mask, Vfx = vfx, Animation = anim, }); } return ret; } /// <summary> /// Deserializes the binary EQDP data into a dictionary of EQDP entries. /// </summary> private static Dictionary<XivRace, EquipmentDeformationParameter> DeserializeEqdpData(byte[] data, uint dataVersion) { const int eqdpEntrySize = 5; int entries = data.Length / eqdpEntrySize; Dictionary<XivRace, EquipmentDeformationParameter> ret = new Dictionary<XivRace, EquipmentDeformationParameter>(); int read = 0; using (BinaryReader reader = new BinaryReader(new MemoryStream(data))) { while (read < entries) { int raceCode = reader.ReadInt32(); XivRace race = GetXivRace(raceCode.ToString().PadLeft(4, '0')); byte eqpByte = reader.ReadByte(); EquipmentDeformationParameter entry = EquipmentDeformationParameter.FromByte(eqpByte); ret.Add(race, entry); read++; } } // Catch for cases where for some reason the EQP doesn't have all races, // for example, SE adding more races in the future, and we're // reading old metadata entries. foreach (XivRace race in PlayableRaces) { if (!ret.ContainsKey(race)) { ret.Add(race, new EquipmentDeformationParameter()); } } return ret; } private static Dictionary<XivRace, ExtraSkeletonEntry> DeserializeEstData(byte[] data, uint dataVersion) { if (dataVersion == 1) { // Version 1 didn't include EST data, so just get the defaults. return null; //// await Est.GetExtraSkeletonEntries(root); } // 6 Bytes per entry. int count = data.Length / 6; Dictionary<XivRace, ExtraSkeletonEntry> ret = new Dictionary<XivRace, ExtraSkeletonEntry>(count); for (int i = 0; i < count; i++) { int offset = i * 6; ushort raceCode = BitConverter.ToUInt16(data, offset); ushort setId = BitConverter.ToUInt16(data, offset + 2); ushort skelId = BitConverter.ToUInt16(data, offset + 4); XivRace race = GetXivRace(raceCode); ret.Add(race, new ExtraSkeletonEntry(race, setId, skelId)); } return ret; } private static GimmickParameter DeserializeGmpData(byte[] data, uint dataVersion) { if (dataVersion == 1) { // Version 1 didn't have GMP data, so include the default GMP data. ////Eqp _eqp = new Eqp(XivCache.GameInfo.GameDirectory); return null; ////await _eqp.GetGimmickParameter(root, true); } // 5 Bytes to parse, ezpz lemon sqzy return new GimmickParameter(data); } private static void ReplaceBytesAt(byte[] original, byte[] toInject, int index) { for (int i = 0; i < toInject.Length; i++) { original[index + i] = toInject[i]; } } private static XivRace GetXivRace(string value) { IEnumerable<XivRace> races = Enum.GetValues(typeof(XivRace)).Cast<XivRace>(); return races.FirstOrDefault(race => GetRaceCode(race) == value); } private static XivRace GetXivRace(int value) { string code = value.ToString().PadLeft(4, '0'); return GetXivRace(code); } private static string GetRaceCode(XivRace value) { FieldInfo field = value.GetType().GetField(value.ToString()); DescriptionAttribute[] attribute = (DescriptionAttribute[])field.GetCustomAttributes(typeof(DescriptionAttribute), false); return attribute.Length > 0 ? attribute[0].Description : value.ToString(); } /// <summary> /// Class representing an Equipment Deformation parameter for a given race/slot. /// </summary> public class EquipmentDeformationParameter { #pragma warning disable SA1307 public bool bit0; public bool bit1; #pragma warning restore SA1307 /// <summary> /// Create a EquipmentDeformation Parameter from a full byte representation. /// </summary> public static EquipmentDeformationParameter FromByte(byte b) { BitArray r = new BitArray(new byte[] { b }); EquipmentDeformationParameter def = new EquipmentDeformationParameter(); def.bit0 = r[0]; def.bit1 = r[1]; return def; } /// <summary> /// Gets a single byte representation of this entry. /// </summary> public byte GetByte() { BitArray r = new BitArray(8); r[0] = this.bit0; r[1] = this.bit1; byte[] arr = new byte[1]; r.CopyTo(arr, 0); return arr[0]; } } /// <summary> /// Class Representing a Extra Skeletons Table Entry for a Equipment Set. /// </summary> public class ExtraSkeletonEntry { public ushort SetId; public XivRace Race; public ushort SkelId; public ExtraSkeletonEntry(XivRace race, ushort setId) { this.Race = race; this.SetId = setId; this.SkelId = 0; } public ExtraSkeletonEntry(XivRace race, ushort setId, ushort skelId) { this.SetId = setId; this.Race = race; this.SkelId = skelId; } public static void Write(byte[] data, ExtraSkeletonEntry entry, int count, int index) { int offset = (int)(4 + (index * 4)); short raceId = short.Parse(GetRaceCode(entry.Race)); ReplaceBytesAt(data, BitConverter.GetBytes(entry.SetId), offset); ReplaceBytesAt(data, BitConverter.GetBytes(raceId), offset + 2); int baseOffset = 4 + (count * 4); offset = (int)(baseOffset + (index * 2)); ReplaceBytesAt(data, BitConverter.GetBytes(entry.SkelId), offset); } public static ExtraSkeletonEntry Read(byte[] data, uint count, uint index) { int offset = (int)(4 + (index * 4)); ushort setId = BitConverter.ToUInt16(data, offset); ushort raceId = BitConverter.ToUInt16(data, offset + 2); XivRace race = GetXivRace(raceId.ToString().PadLeft(4, '0')); uint baseOffset = 4 + (count * 4); offset = (int)(baseOffset + (index * 2)); ushort skelId = BitConverter.ToUInt16(data, offset); ExtraSkeletonEntry ret = new ExtraSkeletonEntry(race, setId, skelId); return ret; } } public class GimmickParameter { public bool Enabled; public bool Animated; public ushort RotationA; public ushort RotationB; public ushort RotationC; public byte UnknownHigh; public byte UnknownLow; public GimmickParameter() { this.Enabled = false; this.Animated = false; this.RotationA = 0; this.RotationB = 0; this.RotationC = 0; this.UnknownHigh = 0; this.UnknownLow = 0; } public GimmickParameter(byte[] bytes) { uint l = BitConverter.ToUInt32(bytes, 0); this.Enabled = (l & 1) > 0; this.Animated = (l & 2) > 0; uint d1 = l >> 2; this.RotationA = (ushort)(d1 & 0x3FF); uint d2 = l >> 12; this.RotationB = (ushort)(d2 & 0x3FF); uint d3 = l >> 22; this.RotationC = (ushort)(d3 & 0x3FF); this.UnknownHigh = (byte)((bytes[4] >> 4) & 0x0F); this.UnknownLow = (byte)(bytes[4] & 0x0F); } /// <summary> /// Retrieves the raw bytewise representation of the parameter. /// </summary> public byte[] GetBytes() { int ret = 0; if (this.Enabled) { ret = ret | 1; } if (this.Animated) { ret = ret | 2; } int rot1 = (this.RotationA & 0x3FF) << 2; int rot2 = (this.RotationB & 0x3FF) << 12; int rot3 = (this.RotationC & 0x3FF) << 22; ret = ret | rot1; ret = ret | rot2; ret = ret | rot3; byte last = (byte)((this.UnknownHigh << 4) | (this.UnknownLow & 0x0F)); byte[] bytes = new byte[5]; ReplaceBytesAt(bytes, BitConverter.GetBytes(ret), 0); bytes[4] = last; return bytes; } } /// <summary> /// Class representing an EquipmentParameter entry, /// mostly contains data relating to whether or not /// certain elements should be shown or hidden for /// this piece of gear. /// </summary> public class EquipmentParameter { /// <summary> /// Slot abbreviation for ths parameter set. /// </summary> public readonly string Slot; /// <summary> /// The raw bits which make up this parameter. /// </summary> private BitArray bits; /// <summary> /// Initializes a new instance of the <see cref="EquipmentParameter"/> class. /// Constructor. Slot is required. /// </summary> public EquipmentParameter(string slot, byte[] rawBytes) { this.Slot = slot; this.bits = new BitArray(rawBytes); } /// <summary> /// Bitwise flags for the main equipment parameter 64 bit array. /// Flag names are set based on what they do when they are set to [1]. /// </summary> public enum EquipmentParameterFlag { // Default flag set is 0x 3F E0 00 70 60 3F 00 // For FULL GEAR PIECES, they're always marked as TRUE = Show // For PARTIAL GEAR PIECES, they're marked as TRUE = HIDE // Byte 0 - Body EnableBodyFlags = 0, BodyHideWaist = 1, Bit2 = 2, BodyHideShortGloves = 3, // Bit 3 OR Bit 4 is often set on Legacy gear. Bit4 = 4, // Bit 3 OR Bit 4 is often set on Legacy gear. BodyHideMidGloves = 5, BodyHideLongGloves = 6, BodyHideGorget = 7, // Byte 1 - Body BodyShowLeg = 8, // When turned off, Leg hiding data is resolved from this same set, rather than the set of the equipped piece. BodyShowHand = 9, // When turned off, Hand hiding data is resolved from this same set, rather than the set of the equipped piece. BodyShowHead = 10, // When turned off, Head hiding data is resolved from this same set, rather than the set of the equipped piece. BodyShowNecklace = 11, BodyShowBracelet = 12, // "Wrist[slot]" is not used in this context b/c it can be confusing with other settings. BodyShowTail = 13, BodyTriggersomeShapeData = 14, Bit15 = 15, // Byte 2 - Leg EnableLegFlags = 16, LegHideKneePads = 17, // atr_lpd LegHideShortBoot = 18, // atr_leg LegHideHalfBoot = 19, // atr_leg LegBootUnknown = 20, LegShowFoot = 21, Bit22 = 22, Bit23 = 23, // Byte 3 - Hand EnableHandFlags = 24, HandHideElbow = 25, // Requires bit 26 on as well to work. HandHideForearm = 26, // "Wrist[anatomy]" is not used in this context b/c it can be confusing with other settings. Bit27 = 27, HandShowBracelet = 28, // "Wrist[slot]" is not used in this context b/c it can be confusing with other settings. HandShowRingL = 29, HandShowRingR = 30, Bit31 = 31, // Byte 4 - Foot EnableFootFlags = 32, FootHideKnee = 33, // Requires bit 34 on as well to work. FootHideCalf = 34, FootHideAnkle = 35, // Usually set to [1], the remaining bits of this byte are always [0]. Bit36 = 36, Bit37 = 37, Bit38 = 38, Bit39 = 39, // Byte 5 - Head & Hair EnableHeadFlags = 40, HeadHideScalp = 41, // When set alone, hides top(hat part) of hair. When set with 42, hides everything. HeadHideHair = 42, // When set with 41, hides everything neck up. When set without, hides all hair. HeadShowHairOverride = 43, // Overrides Bit 41 & 42 When set. HeadHideNeck = 44, HeadShowNecklace = 45, Bit46 = 46, HeadShowEarrings = 47, // This cannot be toggled off without enabling bit 42. // Byte 6 - Ears/Horns/Etc. HeadShowEarringsHuman = 48, HeadShowEarringsAura = 49, HeadShowEarHuman = 50, HeadShowEarMiqo = 51, HeadShowEarAura = 52, HeadShowEarViera = 53, HeadUnknownHelmet1 = 54, // Usually set on for helmets, in place of 48/49 HeadUnknownHelmet2 = 55, // Usually set on for helmets, in place of 48/49 // Byte 7 - Shadowbringers Race Settings HeadShowHrothgarHat = 56, HeadShowVieraHat = 57, Bit58 = 58, Bit59 = 59, Bit60 = 60, Bit61 = 61, Bit62 = 62, Bit63 = 63, } /// <summary> /// Gets a dictionary of [Slot] => [Flag] => [Index within the slot's byte array] for each flag. /// </summary> public static Dictionary<string, Dictionary<EquipmentParameterFlag, int>> FlagOffsetDictionaries { get { Dictionary<string, Dictionary<EquipmentParameterFlag, int>> ret = new Dictionary<string, Dictionary<EquipmentParameterFlag, int>>() { { "met", new Dictionary<EquipmentParameterFlag, int>() }, { "top", new Dictionary<EquipmentParameterFlag, int>() }, { "glv", new Dictionary<EquipmentParameterFlag, int>() }, { "dwn", new Dictionary<EquipmentParameterFlag, int>() }, { "sho", new Dictionary<EquipmentParameterFlag, int>() }, }; IEnumerable<EquipmentParameterFlag> flags = Enum.GetValues(typeof(EquipmentParameterFlag)).Cast<EquipmentParameterFlag>(); foreach (EquipmentParameterFlag flag in flags) { int raw = (int)flag; int byteIndex = raw / 8; // Find the slot that this byte belongs to. KeyValuePair<string, int> slotKv = EquipmentParameterSet.EntryOffsets.Reverse().First(x => x.Value <= byteIndex); string slot = slotKv.Key; int slotByteOffset = slotKv.Value; // Compute the relevant bit position within the slot's grouping. int relevantIndex = raw - (slotByteOffset * 8); ret[slot].Add(flag, relevantIndex); } return ret; } } /// <summary> /// Gets the available flags for this EquipmentParameter. /// </summary> public List<EquipmentParameterFlag> AvailableFlags { get { return FlagOffsetDictionaries[this.Slot].Keys.ToList(); } } /// <summary> /// Retrieves the list of all available flags, with their values. /// Changing the values will not affect the actual underlying data. /// </summary> public Dictionary<EquipmentParameterFlag, bool> GetFlags() { Dictionary<EquipmentParameterFlag, bool> ret = new Dictionary<EquipmentParameterFlag, bool>(); List<EquipmentParameterFlag> flags = this.AvailableFlags; foreach (EquipmentParameterFlag flag in flags) { ret.Add(flag, this.GetFlag(flag)); } return ret; } /// <summary> /// Set all (or a subset) of flags in this Parameter set at once. /// </summary> public void SetFlags(Dictionary<EquipmentParameterFlag, bool> flags) { foreach (KeyValuePair<EquipmentParameterFlag, bool> kv in flags) { this.SetFlag(kv.Key, kv.Value); } } public bool GetFlag(EquipmentParameterFlag flag) { if (!FlagOffsetDictionaries[this.Slot].ContainsKey(flag)) return false; int index = FlagOffsetDictionaries[this.Slot][flag]; return this.bits[index]; } public void SetFlag(EquipmentParameterFlag flag, bool value) { if (!FlagOffsetDictionaries[this.Slot].ContainsKey(flag)) return; int index = FlagOffsetDictionaries[this.Slot][flag]; this.bits[index] = value; } /// <summary> /// Gets the raw bytes of this EquipmentParameter. /// </summary> public byte[] GetBytes() { byte[] bytes = new byte[this.bits.Count / 8]; this.bits.CopyTo(bytes, 0); return bytes; } public void SetBytes(byte[] bytes) { this.bits = new BitArray(bytes); } public class EquipmentParameterSet { // Entry order within the set. public static readonly List<string> EntryOrder = new List<string>() { "top", "dwn", "glv", "sho", "met", }; // Byte sizes within the set. public static readonly Dictionary<string, int> EntrySizes = new Dictionary<string, int>() { { "top", 2 }, { "dwn", 1 }, { "glv", 1 }, { "sho", 1 }, { "met", 3 }, }; // Byte offsets within the set. public static readonly Dictionary<string, int> EntryOffsets = new Dictionary<string, int>() { { "top", 0 }, { "dwn", 2 }, { "glv", 3 }, { "sho", 4 }, { "met", 5 }, }; /// <summary> /// The actual parameters contained in this set, by Slot Abbreviation. /// Strings should match up to Mdl.SlotAbbreviationDictionary Keys /// This element should always contain 5 entries: [met, top, glv, dwn, sho]. /// </summary> public Dictionary<string, EquipmentParameter> Parameters; public EquipmentParameterSet(List<byte> rawBytes) { Dictionary<string, List<byte>> slotBytes = new Dictionary<string, List<byte>>(); slotBytes.Add("top", new List<byte>()); slotBytes.Add("dwn", new List<byte>()); slotBytes.Add("glv", new List<byte>()); slotBytes.Add("sho", new List<byte>()); slotBytes.Add("met", new List<byte>()); slotBytes["top"].Add(rawBytes[0]); slotBytes["top"].Add(rawBytes[1]); slotBytes["dwn"].Add(rawBytes[2]); slotBytes["glv"].Add(rawBytes[3]); slotBytes["sho"].Add(rawBytes[4]); slotBytes["met"].Add(rawBytes[5]); slotBytes["met"].Add(rawBytes[6]); slotBytes["met"].Add(rawBytes[7]); this.Parameters = new Dictionary<string, EquipmentParameter>() { { "top", new EquipmentParameter("top", slotBytes["top"].ToArray()) }, { "dwn", new EquipmentParameter("dwn", slotBytes["dwn"].ToArray()) }, { "glv", new EquipmentParameter("glv", slotBytes["glv"].ToArray()) }, { "sho", new EquipmentParameter("sho", slotBytes["sho"].ToArray()) }, { "met", new EquipmentParameter("met", slotBytes["met"].ToArray()) }, }; } public static List<string> SlotsAsList() { return new List<string>() { "met", "top", "glv", "dwn", "sho" }; } } } } }
29.12967
147
0.651351
[ "MIT" ]
XIV-Tools/TexToolsModExtractor
Extractor/Metadatas/Metadata.cs
26,511
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Linq; using System.Text; using System.Windows.Forms; namespace UH { public partial class MineSweeperUI : Form { MineSweeperBoard _board; const int _gridSize = 10; Button[,] _cells = new Button[_gridSize, _gridSize]; const int _cellSize = 35; const int _fontSize = 14; public MineSweeperUI() { InitializeComponent(); CreateCells(); StartNewGame(); } private void CreateCells() { for (int row = 0; row < _gridSize; row++) { for (int column = 0; column < _gridSize; column++) { _cells[row, column] = GetCellForLocation(row, column); pnlGame.Controls.Add(_cells[row, column]); } } } private Button GetCellForLocation(int row, int column) { Button cell = new Button(); cell.Font = new Font(this.Font.FontFamily, _fontSize, this.Font.Style); cell.Width = cell.Height = _cellSize; cell.Location = new Point(row * _cellSize, column * _cellSize); cell.MouseDown += new MouseEventHandler(CellClick); return cell; } private void StartNewGame() { _board = new MineSweeperBoard(); pnlGame.Enabled = true; ResetCells(); } private void ResetCells() { for (int row = 0; row < _gridSize; row++) { for (int column = 0; column < _gridSize; column++) { _cells[row, column].Text = String.Empty; _cells[row, column].BackColor = buttonNewGame.BackColor; _cells[row, column].Enabled = true; } } } private void ButtonNewGameClick(object sender, EventArgs e) { StartNewGame(); } void CellClick(object sender, EventArgs e) { for (int row = 0; row < _gridSize; row++) { for (int column = 0; column < _gridSize; column++) { if (_cells[row, column] == (Button)sender) { HandleButtonClick(((MouseEventArgs)e).Button, row, column); CheckForGameEnd(row, column); } } } } private void CheckForGameEnd(int lastClickedCellRow, int lastClickedCellColumn) { if (_board.IsGameLost()) { _cells[lastClickedCellRow, lastClickedCellColumn].BackColor = Color.Red; pnlGame.Enabled = false; MessageBox.Show("You Lost.", "MineSweeper"); } else if (_board.IsGameWon()) { pnlGame.Enabled = false; MessageBox.Show("You Won.", "MineSweeper"); } } private void HandleButtonClick(MouseButtons buttonClicked, int cellRow, int cellColumn) { switch (buttonClicked) { case MouseButtons.Left: HandleExposeCell(cellRow, cellColumn); break; case MouseButtons.Right: HandleSealUnSealCell(cellRow, cellColumn); break; } } private void HandleExposeCell(int row, int column) { _board.ExposeCellAt(row, column); ShowValueOfExposedCellsAndDisableThem(); } private void HandleSealUnSealCell(int row, int column) { _board.ToggleSealCellAt(row, column); _cells[row, column].Text = String.Empty; if (_board.IsCellSealedAt(row, column)) { _cells[row, column].Text = "S"; } } private void ShowValueOfExposedCellsAndDisableThem() { for (int row = 0; row < _gridSize; row++) { for (int column = 0; column < _gridSize; column++) { if (_board.IsCellExposedAt(row, column)) { _cells[row, column].Text = _board.GetCellValueAt(row, column); _cells[row, column].BackColor = Color.White; _cells[row, column].Enabled = false; } } } } } }
31.520548
95
0.498696
[ "MIT" ]
jsvasani/mine-sweeper
UH.MineSweeperUI/MineSweeperUI.cs
4,604
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System.Linq; using System.Threading.Tasks; using Microsoft.EntityFrameworkCore.TestModels.GearsOfWarModel; using Microsoft.EntityFrameworkCore.TestUtilities; using Xunit; using Xunit.Abstractions; namespace Microsoft.EntityFrameworkCore.Query { public class GearsOfWarQuerySqlServerTest : GearsOfWarQueryRelationalTestBase<GearsOfWarQuerySqlServerFixture> { #pragma warning disable IDE0060 // Remove unused parameter public GearsOfWarQuerySqlServerTest(GearsOfWarQuerySqlServerFixture fixture, ITestOutputHelper testOutputHelper) #pragma warning restore IDE0060 // Remove unused parameter : base(fixture) { Fixture.TestSqlLoggerFactory.Clear(); //Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper); } protected override bool CanExecuteQueryString => true; public override async Task Negate_on_binary_expression(bool async) { await base.Negate_on_binary_expression(async); AssertSql( @"SELECT [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Squads] AS [s] WHERE [s].[Id] = -([s].[Id] + [s].[Id])"); } public override async Task Negate_on_column(bool async) { await base.Negate_on_column(async); AssertSql( @"SELECT [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Squads] AS [s] WHERE [s].[Id] = -[s].[Id]"); } public override async Task Negate_on_like_expression(bool async) { await base.Negate_on_like_expression(async); AssertSql( @"SELECT [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Squads] AS [s] WHERE [s].[Name] IS NOT NULL AND NOT ([s].[Name] LIKE N'us%')"); } public override async Task Entity_equality_empty(bool async) { await base.Entity_equality_empty(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE 0 = 1"); } public override async Task Include_multiple_one_to_one_and_one_to_many(bool async) { await base.Include_multiple_one_to_one_and_one_to_many(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] ORDER BY [t].[Id], [g].[Nickname], [g].[SquadId]"); } public override async Task Include_multiple_one_to_one_optional_and_one_to_one_required(bool async) { await base.Include_multiple_one_to_one_optional_and_one_to_one_required(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) LEFT JOIN [Squads] AS [s] ON [g].[SquadId] = [s].[Id]"); } public override async Task Include_multiple_circular(bool async) { await base.Include_multiple_circular(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [c].[Name], [c].[Location], [c].[Nation], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g] INNER JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name] LEFT JOIN [Gears] AS [g0] ON [c].[Name] = [g0].[AssignedCityName] ORDER BY [g].[Nickname], [g].[SquadId], [c].[Name], [g0].[Nickname]"); } public override async Task Include_multiple_circular_with_filter(bool async) { await base.Include_multiple_circular_with_filter(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [c].[Name], [c].[Location], [c].[Nation], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g] INNER JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name] LEFT JOIN [Gears] AS [g0] ON [c].[Name] = [g0].[AssignedCityName] WHERE [g].[Nickname] = N'Marcus' ORDER BY [g].[Nickname], [g].[SquadId], [c].[Name], [g0].[Nickname]"); } public override async Task Include_using_alternate_key(bool async) { await base.Include_using_alternate_key(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] WHERE [g].[Nickname] = N'Marcus' ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Include_navigation_on_derived_type(bool async) { await base.Include_navigation_on_derived_type(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[Nickname], [g].[SquadId], [g0].[Nickname]"); } public override async Task String_based_Include_navigation_on_derived_type(bool async) { await base.String_based_Include_navigation_on_derived_type(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[Nickname], [g].[SquadId], [g0].[Nickname]"); } public override async Task Select_Where_Navigation_Included(bool async) { await base.Select_Where_Navigation_Included(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE [g].[Nickname] = N'Marcus'"); } public override async Task Include_with_join_reference1(bool async) { await base.Include_with_join_reference1(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [c].[Name], [c].[Location], [c].[Nation] FROM [Gears] AS [g] INNER JOIN [Tags] AS [t] ON ([g].[SquadId] = [t].[GearSquadId]) AND ([g].[Nickname] = [t].[GearNickName]) INNER JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name]"); } public override async Task Include_with_join_reference2(bool async) { await base.Include_with_join_reference2(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [c].[Name], [c].[Location], [c].[Nation] FROM [Tags] AS [t] INNER JOIN [Gears] AS [g] ON ([t].[GearSquadId] = [g].[SquadId]) AND ([t].[GearNickName] = [g].[Nickname]) INNER JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name]"); } public override async Task Include_with_join_collection1(bool async) { await base.Include_with_join_collection1(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Id], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] INNER JOIN [Tags] AS [t] ON ([g].[SquadId] = [t].[GearSquadId]) AND ([g].[Nickname] = [t].[GearNickName]) LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] ORDER BY [g].[Nickname], [g].[SquadId], [t].[Id]"); } public override async Task Include_with_join_collection2(bool async) { await base.Include_with_join_collection2(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Id], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Tags] AS [t] INNER JOIN [Gears] AS [g] ON ([t].[GearSquadId] = [g].[SquadId]) AND ([t].[GearNickName] = [g].[Nickname]) LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] ORDER BY [t].[Id], [g].[Nickname], [g].[SquadId]"); } public override async Task Include_where_list_contains_navigation(bool async) { await base.Include_where_list_contains_navigation(async); AssertSql( @"SELECT [t].[Id] FROM [Tags] AS [t]", // @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) WHERE [t].[Id] IS NOT NULL AND [t].[Id] IN ('34c8d86e-a4ac-4be5-827f-584dda348a07', 'df36f493-463f-4123-83f9-6b135deeb7ba', 'a8ad98f9-e023-4e2a-9a70-c2728455bd34', '70534e05-782c-4052-8720-c2c54481ce5f', 'a7be028a-0cf2-448f-ab55-ce8bc5d8cf69', 'b39a6fba-9026-4d69-828e-fd7068673e57')"); } public override async Task Include_where_list_contains_navigation2(bool async) { await base.Include_where_list_contains_navigation2(async); AssertSql( @"SELECT [t].[Id] FROM [Tags] AS [t]", // @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Gears] AS [g] INNER JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) WHERE [c].[Location] IS NOT NULL AND [t].[Id] IN ('34c8d86e-a4ac-4be5-827f-584dda348a07', 'df36f493-463f-4123-83f9-6b135deeb7ba', 'a8ad98f9-e023-4e2a-9a70-c2728455bd34', '70534e05-782c-4052-8720-c2c54481ce5f', 'a7be028a-0cf2-448f-ab55-ce8bc5d8cf69', 'b39a6fba-9026-4d69-828e-fd7068673e57')"); } public override async Task Navigation_accessed_twice_outside_and_inside_subquery(bool async) { await base.Navigation_accessed_twice_outside_and_inside_subquery(async); AssertSql( @"SELECT [t].[Id] FROM [Tags] AS [t]", // @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) WHERE [t].[Id] IS NOT NULL AND [t].[Id] IN ('34c8d86e-a4ac-4be5-827f-584dda348a07', 'df36f493-463f-4123-83f9-6b135deeb7ba', 'a8ad98f9-e023-4e2a-9a70-c2728455bd34', '70534e05-782c-4052-8720-c2c54481ce5f', 'a7be028a-0cf2-448f-ab55-ce8bc5d8cf69', 'b39a6fba-9026-4d69-828e-fd7068673e57')"); } public override async Task Include_with_join_multi_level(bool async) { await base.Include_with_join_multi_level(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [c].[Name], [c].[Location], [c].[Nation], [t].[Id], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g] INNER JOIN [Tags] AS [t] ON ([g].[SquadId] = [t].[GearSquadId]) AND ([g].[Nickname] = [t].[GearNickName]) INNER JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name] LEFT JOIN [Gears] AS [g0] ON [c].[Name] = [g0].[AssignedCityName] ORDER BY [g].[Nickname], [g].[SquadId], [t].[Id], [c].[Name], [g0].[Nickname]"); } public override async Task Include_with_join_and_inheritance1(bool async) { await base.Include_with_join_and_inheritance1(async); AssertSql( @"SELECT [t0].[Nickname], [t0].[SquadId], [t0].[AssignedCityName], [t0].[CityOfBirthName], [t0].[Discriminator], [t0].[FullName], [t0].[HasSoulPatch], [t0].[LeaderNickname], [t0].[LeaderSquadId], [t0].[Rank], [c].[Name], [c].[Location], [c].[Nation] FROM [Tags] AS [t] INNER JOIN ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] = N'Officer' ) AS [t0] ON ([t].[GearSquadId] = [t0].[SquadId]) AND ([t].[GearNickName] = [t0].[Nickname]) INNER JOIN [Cities] AS [c] ON [t0].[CityOfBirthName] = [c].[Name]"); } public override async Task Include_with_join_and_inheritance_with_orderby_before_and_after_include(bool async) { await base.Include_with_join_and_inheritance_with_orderby_before_and_after_include(async); AssertSql( @"SELECT [t0].[Nickname], [t0].[SquadId], [t0].[AssignedCityName], [t0].[CityOfBirthName], [t0].[Discriminator], [t0].[FullName], [t0].[HasSoulPatch], [t0].[LeaderNickname], [t0].[LeaderSquadId], [t0].[Rank], [t].[Id], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Tags] AS [t] INNER JOIN ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] = N'Officer' ) AS [t0] ON ([t].[GearSquadId] = [t0].[SquadId]) AND ([t].[GearNickName] = [t0].[Nickname]) LEFT JOIN [Gears] AS [g0] ON ([t0].[Nickname] = [g0].[LeaderNickname]) AND ([t0].[SquadId] = [g0].[LeaderSquadId]) ORDER BY [t0].[HasSoulPatch], [t0].[Nickname] DESC, [t].[Id], [t0].[SquadId], [g0].[Nickname]"); } public override async Task Include_with_join_and_inheritance2(bool async) { await base.Include_with_join_and_inheritance2(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Id], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] INNER JOIN [Tags] AS [t] ON ([g].[SquadId] = [t].[GearSquadId]) AND ([g].[Nickname] = [t].[GearNickName]) LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[Nickname], [g].[SquadId], [t].[Id]"); } public override async Task Include_with_join_and_inheritance3(bool async) { await base.Include_with_join_and_inheritance3(async); AssertSql( @"SELECT [t0].[Nickname], [t0].[SquadId], [t0].[AssignedCityName], [t0].[CityOfBirthName], [t0].[Discriminator], [t0].[FullName], [t0].[HasSoulPatch], [t0].[LeaderNickname], [t0].[LeaderSquadId], [t0].[Rank], [t].[Id], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Tags] AS [t] INNER JOIN ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] = N'Officer' ) AS [t0] ON ([t].[GearSquadId] = [t0].[SquadId]) AND ([t].[GearNickName] = [t0].[Nickname]) LEFT JOIN [Gears] AS [g0] ON ([t0].[Nickname] = [g0].[LeaderNickname]) AND ([t0].[SquadId] = [g0].[LeaderSquadId]) ORDER BY [t].[Id], [t0].[Nickname], [t0].[SquadId], [g0].[Nickname]"); } public override async Task Include_with_nested_navigation_in_order_by(bool async) { await base.Include_with_nested_navigation_in_order_by(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g] ON [w].[OwnerFullName] = [g].[FullName] LEFT JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name] WHERE ([g].[Nickname] <> N'Paduk') OR [g].[Nickname] IS NULL ORDER BY [c].[Name], [w].[Id]"); } public override async Task Where_enum(bool async) { await base.Where_enum(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Rank] = 4"); } public override async Task Where_nullable_enum_with_constant(bool async) { await base.Where_nullable_enum_with_constant(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [w].[AmmunitionType] = 1"); } public override async Task Where_nullable_enum_with_null_constant(bool async) { await base.Where_nullable_enum_with_null_constant(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [w].[AmmunitionType] IS NULL"); } public override async Task Where_nullable_enum_with_non_nullable_parameter(bool async) { await base.Where_nullable_enum_with_non_nullable_parameter(async); AssertSql( @"@__ammunitionType_0='1' SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [w].[AmmunitionType] = @__ammunitionType_0"); } public override async Task Where_nullable_enum_with_nullable_parameter(bool async) { await base.Where_nullable_enum_with_nullable_parameter(async); AssertSql( @"@__ammunitionType_0='1' (Nullable = true) SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [w].[AmmunitionType] = @__ammunitionType_0", // @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [w].[AmmunitionType] IS NULL"); } public override async Task Where_bitwise_and_enum(bool async) { await base.Where_bitwise_and_enum(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Rank] & 2) > 0", // @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Rank] & 2) = 2"); } public override async Task Where_bitwise_and_integral(bool async) { await base.Where_bitwise_and_integral(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Rank] & 1) = 1", // @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE (CAST([g].[Rank] AS bigint) & CAST(1 AS bigint)) = CAST(1 AS bigint)", // @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE (CAST([g].[Rank] AS smallint) & CAST(1 AS smallint)) = CAST(1 AS smallint)"); } public override async Task Where_bitwise_and_nullable_enum_with_constant(bool async) { await base.Where_bitwise_and_nullable_enum_with_constant(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[AmmunitionType] & 1) > 0"); } public override async Task Where_bitwise_and_nullable_enum_with_null_constant(bool async) { await base.Where_bitwise_and_nullable_enum_with_null_constant(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[AmmunitionType] & NULL) > 0"); } public override async Task Where_bitwise_and_nullable_enum_with_non_nullable_parameter(bool async) { await base.Where_bitwise_and_nullable_enum_with_non_nullable_parameter(async); AssertSql( @"@__ammunitionType_0='1' SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[AmmunitionType] & @__ammunitionType_0) > 0"); } public override async Task Where_bitwise_and_nullable_enum_with_nullable_parameter(bool async) { await base.Where_bitwise_and_nullable_enum_with_nullable_parameter(async); AssertSql( @"@__ammunitionType_0='1' (Nullable = true) SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[AmmunitionType] & @__ammunitionType_0) > 0", // @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[AmmunitionType] & NULL) > 0"); } public override async Task Where_bitwise_or_enum(bool async) { await base.Where_bitwise_or_enum(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Rank] | 2) > 0"); } public override async Task Bitwise_projects_values_in_select(bool async) { await base.Bitwise_projects_values_in_select(async); AssertSql( @"SELECT TOP(1) CASE WHEN ([g].[Rank] & 2) = 2 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [BitwiseTrue], CASE WHEN ([g].[Rank] & 2) = 4 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [BitwiseFalse], [g].[Rank] & 2 AS [BitwiseValue] FROM [Gears] AS [g] WHERE ([g].[Rank] & 2) = 2"); } public override async Task Where_enum_has_flag(bool async) { await base.Where_enum_has_flag(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Rank] & 2) = 2", // @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Rank] & 18) = 18", // @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Rank] & 1) = 1", // @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Rank] & 1) = 1", // @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE (2 & [g].[Rank]) = [g].[Rank]"); } public override async Task Where_enum_has_flag_subquery(bool async) { await base.Where_enum_has_flag_subquery(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Rank] & COALESCE(( SELECT TOP(1) [g0].[Rank] FROM [Gears] AS [g0] ORDER BY [g0].[Nickname], [g0].[SquadId]), 0)) = COALESCE(( SELECT TOP(1) [g0].[Rank] FROM [Gears] AS [g0] ORDER BY [g0].[Nickname], [g0].[SquadId]), 0)", // @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE (2 & COALESCE(( SELECT TOP(1) [g0].[Rank] FROM [Gears] AS [g0] ORDER BY [g0].[Nickname], [g0].[SquadId]), 0)) = COALESCE(( SELECT TOP(1) [g0].[Rank] FROM [Gears] AS [g0] ORDER BY [g0].[Nickname], [g0].[SquadId]), 0)"); } public override async Task Where_enum_has_flag_subquery_with_pushdown(bool async) { await base.Where_enum_has_flag_subquery_with_pushdown(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE (([g].[Rank] & ( SELECT TOP(1) [g0].[Rank] FROM [Gears] AS [g0] ORDER BY [g0].[Nickname], [g0].[SquadId])) = ( SELECT TOP(1) [g0].[Rank] FROM [Gears] AS [g0] ORDER BY [g0].[Nickname], [g0].[SquadId])) OR ( SELECT TOP(1) [g0].[Rank] FROM [Gears] AS [g0] ORDER BY [g0].[Nickname], [g0].[SquadId]) IS NULL", // @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ((2 & ( SELECT TOP(1) [g0].[Rank] FROM [Gears] AS [g0] ORDER BY [g0].[Nickname], [g0].[SquadId])) = ( SELECT TOP(1) [g0].[Rank] FROM [Gears] AS [g0] ORDER BY [g0].[Nickname], [g0].[SquadId])) OR ( SELECT TOP(1) [g0].[Rank] FROM [Gears] AS [g0] ORDER BY [g0].[Nickname], [g0].[SquadId]) IS NULL"); } public override async Task Where_enum_has_flag_subquery_client_eval(bool async) { await base.Where_enum_has_flag_subquery_client_eval(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE (([g].[Rank] & ( SELECT TOP(1) [g0].[Rank] FROM [Gears] AS [g0] ORDER BY [g0].[Nickname], [g0].[SquadId])) = ( SELECT TOP(1) [g0].[Rank] FROM [Gears] AS [g0] ORDER BY [g0].[Nickname], [g0].[SquadId])) OR ( SELECT TOP(1) [g0].[Rank] FROM [Gears] AS [g0] ORDER BY [g0].[Nickname], [g0].[SquadId]) IS NULL"); } public override async Task Where_enum_has_flag_with_non_nullable_parameter(bool async) { await base.Where_enum_has_flag_with_non_nullable_parameter(async); AssertSql( @"@__parameter_0='2' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Rank] & @__parameter_0) = @__parameter_0"); } public override async Task Where_has_flag_with_nullable_parameter(bool async) { await base.Where_has_flag_with_nullable_parameter(async); AssertSql( @"@__parameter_0='2' (Nullable = true) SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Rank] & @__parameter_0) = @__parameter_0"); } public override async Task Select_enum_has_flag(bool async) { await base.Select_enum_has_flag(async); AssertSql( @"SELECT TOP(1) CASE WHEN ([g].[Rank] & 2) = 2 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [hasFlagTrue], CASE WHEN ([g].[Rank] & 4) = 4 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [hasFlagFalse] FROM [Gears] AS [g] WHERE ([g].[Rank] & 2) = 2"); } public override async Task Where_count_subquery_without_collision(bool async) { await base.Where_count_subquery_without_collision(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ( SELECT COUNT(*) FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName]) = 2"); } public override async Task Where_any_subquery_without_collision(bool async) { await base.Where_any_subquery_without_collision(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE EXISTS ( SELECT 1 FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName])"); } public override async Task Select_inverted_boolean(bool async) { await base.Select_inverted_boolean(async); AssertSql( @"SELECT [w].[Id], CASE WHEN [w].[IsAutomatic] = CAST(0 AS bit) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [Manual] FROM [Weapons] AS [w] WHERE [w].[IsAutomatic] = CAST(1 AS bit)"); } public override async Task Select_comparison_with_null(bool async) { await base.Select_comparison_with_null(async); AssertSql( @"@__ammunitionType_0='1' (Nullable = true) SELECT [w].[Id], CASE WHEN ([w].[AmmunitionType] = @__ammunitionType_0) AND [w].[AmmunitionType] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [Cartridge] FROM [Weapons] AS [w] WHERE [w].[AmmunitionType] = @__ammunitionType_0", // @"SELECT [w].[Id], CASE WHEN [w].[AmmunitionType] IS NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [Cartridge] FROM [Weapons] AS [w] WHERE [w].[AmmunitionType] IS NULL"); } public override async Task Select_null_parameter(bool async) { await base.Select_null_parameter(async); AssertSql( @"@__ammunitionType_0='1' (Nullable = true) SELECT [w].[Id], @__ammunitionType_0 AS [AmmoType] FROM [Weapons] AS [w]", // @"SELECT [w].[Id], NULL AS [AmmoType] FROM [Weapons] AS [w]", // @"@__ammunitionType_0='2' (Nullable = true) SELECT [w].[Id], @__ammunitionType_0 AS [AmmoType] FROM [Weapons] AS [w]", // @"SELECT [w].[Id], NULL AS [AmmoType] FROM [Weapons] AS [w]"); } public override async Task Select_ternary_operation_with_boolean(bool async) { await base.Select_ternary_operation_with_boolean(async); AssertSql( @"SELECT [w].[Id], CASE WHEN [w].[IsAutomatic] = CAST(1 AS bit) THEN 1 ELSE 0 END AS [Num] FROM [Weapons] AS [w]"); } public override async Task Select_ternary_operation_with_inverted_boolean(bool async) { await base.Select_ternary_operation_with_inverted_boolean(async); AssertSql( @"SELECT [w].[Id], CASE WHEN [w].[IsAutomatic] = CAST(0 AS bit) THEN 1 ELSE 0 END AS [Num] FROM [Weapons] AS [w]"); } public override async Task Select_ternary_operation_with_has_value_not_null(bool async) { await base.Select_ternary_operation_with_has_value_not_null(async); AssertSql( @"SELECT [w].[Id], CASE WHEN [w].[AmmunitionType] IS NOT NULL AND ([w].[AmmunitionType] = 1) THEN N'Yes' ELSE N'No' END AS [IsCartridge] FROM [Weapons] AS [w] WHERE [w].[AmmunitionType] IS NOT NULL AND ([w].[AmmunitionType] = 1)"); } public override async Task Select_ternary_operation_multiple_conditions(bool async) { await base.Select_ternary_operation_multiple_conditions(async); AssertSql( @"SELECT [w].[Id], CASE WHEN ([w].[AmmunitionType] = 2) AND ([w].[SynergyWithId] = 1) THEN N'Yes' ELSE N'No' END AS [IsCartridge] FROM [Weapons] AS [w]"); } public override async Task Select_ternary_operation_multiple_conditions_2(bool async) { await base.Select_ternary_operation_multiple_conditions_2(async); AssertSql( @"SELECT [w].[Id], CASE WHEN ([w].[IsAutomatic] = CAST(0 AS bit)) AND ([w].[SynergyWithId] = 1) THEN N'Yes' ELSE N'No' END AS [IsCartridge] FROM [Weapons] AS [w]"); } public override async Task Select_multiple_conditions(bool async) { await base.Select_multiple_conditions(async); AssertSql( @"SELECT [w].[Id], CASE WHEN ([w].[IsAutomatic] = CAST(0 AS bit)) AND (([w].[SynergyWithId] = 1) AND [w].[SynergyWithId] IS NOT NULL) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [IsCartridge] FROM [Weapons] AS [w]"); } public override async Task Select_nested_ternary_operations(bool async) { await base.Select_nested_ternary_operations(async); AssertSql( @"SELECT [w].[Id], CASE WHEN [w].[IsAutomatic] = CAST(0 AS bit) THEN CASE WHEN [w].[AmmunitionType] = 1 THEN N'ManualCartridge' ELSE N'Manual' END ELSE N'Auto' END AS [IsManualCartridge] FROM [Weapons] AS [w]"); } public override async Task Null_propagation_optimization1(bool async) { await base.Null_propagation_optimization1(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[LeaderNickname] = N'Marcus') AND [g].[LeaderNickname] IS NOT NULL"); } public override async Task Null_propagation_optimization2(bool async) { await base.Null_propagation_optimization2(async); // issue #16050 AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE CASE WHEN [g].[LeaderNickname] IS NULL THEN NULL ELSE CASE WHEN [g].[LeaderNickname] IS NOT NULL AND ([g].[LeaderNickname] LIKE N'%us') THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END END = CAST(1 AS bit)"); } public override async Task Null_propagation_optimization3(bool async) { await base.Null_propagation_optimization3(async); // issue #16050 AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN CASE WHEN [g].[LeaderNickname] LIKE N'%us' THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END ELSE NULL END = CAST(1 AS bit)"); } public override async Task Null_propagation_optimization4(bool async) { await base.Null_propagation_optimization4(async); // issue #16050 AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE (CASE WHEN [g].[LeaderNickname] IS NULL THEN NULL ELSE CAST(LEN([g].[LeaderNickname]) AS int) END = 5) AND CASE WHEN [g].[LeaderNickname] IS NULL THEN NULL ELSE CAST(LEN([g].[LeaderNickname]) AS int) END IS NOT NULL"); } public override async Task Null_propagation_optimization5(bool async) { await base.Null_propagation_optimization5(async); // issue #16050 AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE (CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN CAST(LEN([g].[LeaderNickname]) AS int) ELSE NULL END = 5) AND CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN CAST(LEN([g].[LeaderNickname]) AS int) ELSE NULL END IS NOT NULL"); } public override async Task Null_propagation_optimization6(bool async) { await base.Null_propagation_optimization6(async); // issue #16050 AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE (CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN CAST(LEN([g].[LeaderNickname]) AS int) ELSE NULL END = 5) AND CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN CAST(LEN([g].[LeaderNickname]) AS int) ELSE NULL END IS NOT NULL"); } public override async Task Select_null_propagation_optimization7(bool async) { await base.Select_null_propagation_optimization7(async); // issue #16050 AssertSql( @"SELECT CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN [g].[LeaderNickname] + [g].[LeaderNickname] ELSE NULL END FROM [Gears] AS [g]"); } public override async Task Select_null_propagation_optimization8(bool async) { await base.Select_null_propagation_optimization8(async); AssertSql( @"SELECT [g].[LeaderNickname] + [g].[LeaderNickname] FROM [Gears] AS [g]"); } public override async Task Select_null_propagation_optimization9(bool async) { await base.Select_null_propagation_optimization9(async); AssertSql( @"SELECT CAST(LEN([g].[FullName]) AS int) FROM [Gears] AS [g]"); } public override async Task Select_null_propagation_negative1(bool async) { await base.Select_null_propagation_negative1(async); AssertSql( @"SELECT CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN CASE WHEN CAST(LEN([g].[Nickname]) AS int) = 5 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END ELSE NULL END FROM [Gears] AS [g]"); } public override async Task Select_null_propagation_negative2(bool async) { await base.Select_null_propagation_negative2(async); AssertSql( @"SELECT CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN [g0].[LeaderNickname] ELSE NULL END FROM [Gears] AS [g] CROSS JOIN [Gears] AS [g0]"); } public override async Task Select_null_propagation_negative3(bool async) { await base.Select_null_propagation_negative3(async); AssertSql( @"SELECT [g0].[Nickname], CASE WHEN [g0].[Nickname] IS NOT NULL AND [g0].[SquadId] IS NOT NULL THEN CASE WHEN [g0].[LeaderNickname] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END ELSE NULL END AS [Condition] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON [g].[HasSoulPatch] = CAST(1 AS bit) ORDER BY [g0].[Nickname]"); } public override async Task Select_null_propagation_negative4(bool async) { await base.Select_null_propagation_negative4(async); AssertSql( @"SELECT CASE WHEN [g0].[Nickname] IS NOT NULL AND [g0].[SquadId] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, [g0].[Nickname] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON [g].[HasSoulPatch] = CAST(1 AS bit) ORDER BY [g0].[Nickname]"); } public override async Task Select_null_propagation_negative5(bool async) { await base.Select_null_propagation_negative5(async); AssertSql( @"SELECT CASE WHEN [g0].[Nickname] IS NOT NULL AND [g0].[SquadId] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, [g0].[Nickname] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON [g].[HasSoulPatch] = CAST(1 AS bit) ORDER BY [g0].[Nickname]"); } public override async Task Select_null_propagation_negative6(bool async) { await base.Select_null_propagation_negative6(async); AssertSql( @"SELECT CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN CASE WHEN CAST(LEN([g].[LeaderNickname]) AS int) <> CAST(LEN([g].[LeaderNickname]) AS int) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END ELSE NULL END FROM [Gears] AS [g]"); } public override async Task Select_null_propagation_negative7(bool async) { await base.Select_null_propagation_negative7(async); AssertSql( @"SELECT CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN CAST(1 AS bit) ELSE NULL END FROM [Gears] AS [g]"); } public override async Task Select_null_propagation_negative8(bool async) { await base.Select_null_propagation_negative8(async); AssertSql( @"SELECT CASE WHEN [s].[Id] IS NOT NULL THEN [c].[Name] ELSE NULL END FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) LEFT JOIN [Squads] AS [s] ON [g].[SquadId] = [s].[Id] LEFT JOIN [Cities] AS [c] ON [g].[AssignedCityName] = [c].[Name]"); } public override async Task Select_null_propagation_negative9(bool async) { await base.Select_null_propagation_negative9(async); AssertSql( @"SELECT CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN COALESCE(CASE WHEN CAST(LEN([g].[Nickname]) AS int) = 5 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, CAST(0 AS bit)) ELSE NULL END FROM [Gears] AS [g]"); } public override async Task Select_null_propagation_works_for_navigations_with_composite_keys(bool async) { await base.Select_null_propagation_works_for_navigations_with_composite_keys(async); AssertSql( @"SELECT [g].[Nickname] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId])"); } public override async Task Select_null_propagation_works_for_multiple_navigations_with_composite_keys(bool async) { await base.Select_null_propagation_works_for_multiple_navigations_with_composite_keys(async); AssertSql( @"SELECT CASE WHEN [c].[Name] IS NOT NULL THEN [c].[Name] ELSE NULL END FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) LEFT JOIN [Tags] AS [t0] ON (([g].[Nickname] = [t0].[GearNickName]) OR ([g].[Nickname] IS NULL AND [t0].[GearNickName] IS NULL)) AND (([g].[SquadId] = [t0].[GearSquadId]) OR ([g].[SquadId] IS NULL AND [t0].[GearSquadId] IS NULL)) LEFT JOIN [Gears] AS [g0] ON ([t0].[GearNickName] = [g0].[Nickname]) AND ([t0].[GearSquadId] = [g0].[SquadId]) LEFT JOIN [Cities] AS [c] ON [g0].[AssignedCityName] = [c].[Name]"); } public override async Task Select_conditional_with_anonymous_type_and_null_constant(bool async) { await base.Select_conditional_with_anonymous_type_and_null_constant(async); AssertSql( @"SELECT CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, [g].[HasSoulPatch] FROM [Gears] AS [g] ORDER BY [g].[Nickname]"); } public override async Task Select_conditional_with_anonymous_types(bool async) { await base.Select_conditional_with_anonymous_types(async); AssertSql( @"SELECT CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, [g].[Nickname], [g].[FullName] FROM [Gears] AS [g] ORDER BY [g].[Nickname]"); } public override async Task Where_conditional_equality_1(bool async) { await base.Where_conditional_equality_1(async); AssertSql( @"SELECT [g].[Nickname] FROM [Gears] AS [g] WHERE [g].[LeaderNickname] IS NULL ORDER BY [g].[Nickname]"); } public override async Task Where_conditional_equality_2(bool async) { await base.Where_conditional_equality_2(async); AssertSql( @"SELECT [g].[Nickname] FROM [Gears] AS [g] WHERE [g].[LeaderNickname] IS NULL ORDER BY [g].[Nickname]"); } public override async Task Where_conditional_equality_3(bool async) { await base.Where_conditional_equality_3(async); AssertSql( @"SELECT [g].[Nickname] FROM [Gears] AS [g] ORDER BY [g].[Nickname]"); } public override async Task Select_coalesce_with_anonymous_types(bool async) { await base.Select_coalesce_with_anonymous_types(async); AssertSql( @"SELECT [g].[LeaderNickname], [g].[FullName] FROM [Gears] AS [g] ORDER BY [g].[Nickname]"); } public override async Task Where_compare_anonymous_types(bool async) { await base.Where_compare_anonymous_types(async); AssertSql( " "); } public override async Task Where_member_access_on_anonymous_type(bool async) { await base.Where_member_access_on_anonymous_type(async); AssertSql( @"SELECT [g].[Nickname] FROM [Gears] AS [g] WHERE [g].[LeaderNickname] = N'Marcus'"); } public override async Task Where_compare_anonymous_types_with_uncorrelated_members(bool async) { await base.Where_compare_anonymous_types_with_uncorrelated_members(async); AssertSql( @"SELECT [g].[Nickname] FROM [Gears] AS [g] WHERE 0 = 1"); } public override async Task Select_Where_Navigation_Scalar_Equals_Navigation_Scalar(bool async) { await base.Select_Where_Navigation_Scalar_Equals_Navigation_Scalar(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note], [t0].[Id], [t0].[GearNickName], [t0].[GearSquadId], [t0].[IssueDate], [t0].[Note] FROM [Tags] AS [t] CROSS JOIN [Tags] AS [t0] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) LEFT JOIN [Gears] AS [g0] ON ([t0].[GearNickName] = [g0].[Nickname]) AND ([t0].[GearSquadId] = [g0].[SquadId]) WHERE ([g].[Nickname] = [g0].[Nickname]) OR ([g].[Nickname] IS NULL AND [g0].[Nickname] IS NULL)"); } public override async Task Select_Singleton_Navigation_With_Member_Access(bool async) { await base.Select_Singleton_Navigation_With_Member_Access(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE ([g].[Nickname] = N'Marcus') AND (([g].[CityOfBirthName] <> N'Ephyra') OR [g].[CityOfBirthName] IS NULL)"); } public override async Task Select_Where_Navigation(bool async) { await base.Select_Where_Navigation(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE [g].[Nickname] = N'Marcus'"); } public override async Task Select_Where_Navigation_Equals_Navigation(bool async) { await base.Select_Where_Navigation_Equals_Navigation(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note], [t0].[Id], [t0].[GearNickName], [t0].[GearSquadId], [t0].[IssueDate], [t0].[Note] FROM [Tags] AS [t] CROSS JOIN [Tags] AS [t0] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) LEFT JOIN [Gears] AS [g0] ON ([t0].[GearNickName] = [g0].[Nickname]) AND ([t0].[GearSquadId] = [g0].[SquadId]) WHERE (([g].[Nickname] = [g0].[Nickname]) OR ([g].[Nickname] IS NULL AND [g0].[Nickname] IS NULL)) AND (([g].[SquadId] = [g0].[SquadId]) OR ([g].[SquadId] IS NULL AND [g0].[SquadId] IS NULL))"); } public override async Task Select_Where_Navigation_Null(bool async) { await base.Select_Where_Navigation_Null(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE [g].[Nickname] IS NULL OR [g].[SquadId] IS NULL"); } public override async Task Select_Where_Navigation_Null_Reverse(bool async) { await base.Select_Where_Navigation_Null_Reverse(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE [g].[Nickname] IS NULL OR [g].[SquadId] IS NULL"); } public override async Task Select_Where_Navigation_Scalar_Equals_Navigation_Scalar_Projected(bool async) { await base.Select_Where_Navigation_Scalar_Equals_Navigation_Scalar_Projected(async); AssertSql( @"SELECT [t].[Id] AS [Id1], [t0].[Id] AS [Id2] FROM [Tags] AS [t] CROSS JOIN [Tags] AS [t0] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) LEFT JOIN [Gears] AS [g0] ON ([t0].[GearNickName] = [g0].[Nickname]) AND ([t0].[GearSquadId] = [g0].[SquadId]) WHERE ([g].[Nickname] = [g0].[Nickname]) OR ([g].[Nickname] IS NULL AND [g0].[Nickname] IS NULL)"); } public override async Task Optional_Navigation_Null_Coalesce_To_Clr_Type(bool async) { await base.Optional_Navigation_Null_Coalesce_To_Clr_Type(async); AssertSql( @"SELECT TOP(1) COALESCE([w0].[IsAutomatic], CAST(0 AS bit)) AS [IsAutomatic] FROM [Weapons] AS [w] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id] ORDER BY [w].[Id]"); } public override async Task Where_subquery_boolean(bool async) { await base.Where_subquery_boolean(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE COALESCE(( SELECT TOP(1) [w].[IsAutomatic] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ORDER BY [w].[Id]), CAST(0 AS bit)) = CAST(1 AS bit)"); } public override async Task Where_subquery_boolean_with_pushdown(bool async) { await base.Where_subquery_boolean_with_pushdown(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ( SELECT TOP(1) [w].[IsAutomatic] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ORDER BY [w].[Id]) = CAST(1 AS bit)"); } public override async Task Where_subquery_distinct_firstordefault_boolean(bool async) { await base.Where_subquery_distinct_firstordefault_boolean(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) AND (COALESCE(( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT DISTINCT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ) AS [t] ORDER BY [t].[Id]), CAST(0 AS bit)) = CAST(1 AS bit))"); } public override async Task Where_subquery_distinct_firstordefault_boolean_with_pushdown(bool async) { await base.Where_subquery_distinct_firstordefault_boolean_with_pushdown(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) AND (( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT DISTINCT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ) AS [t] ORDER BY [t].[Id]) = CAST(1 AS bit))"); } public override async Task Where_subquery_distinct_first_boolean(bool async) { await base.Where_subquery_distinct_first_boolean(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) AND (( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT DISTINCT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ) AS [t] ORDER BY [t].[Id]) = CAST(1 AS bit)) ORDER BY [g].[Nickname]"); } public override async Task Where_subquery_distinct_singleordefault_boolean1(bool async) { await base.Where_subquery_distinct_singleordefault_boolean1(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) AND (COALESCE(( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT DISTINCT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[Name] LIKE N'%Lancer%') ) AS [t]), CAST(0 AS bit)) = CAST(1 AS bit)) ORDER BY [g].[Nickname]"); } public override async Task Where_subquery_distinct_singleordefault_boolean2(bool async) { await base.Where_subquery_distinct_singleordefault_boolean2(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) AND (COALESCE(( SELECT DISTINCT TOP(1) [w].[IsAutomatic] FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[Name] LIKE N'%Lancer%')), CAST(0 AS bit)) = CAST(1 AS bit)) ORDER BY [g].[Nickname]"); } public override async Task Where_subquery_distinct_singleordefault_boolean_with_pushdown(bool async) { await base.Where_subquery_distinct_singleordefault_boolean_with_pushdown(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) AND (( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT DISTINCT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[Name] LIKE N'%Lancer%') ) AS [t]) = CAST(1 AS bit)) ORDER BY [g].[Nickname]"); } public override async Task Where_subquery_distinct_lastordefault_boolean(bool async) { await base.Where_subquery_distinct_lastordefault_boolean(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT DISTINCT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ) AS [t] ORDER BY [t].[Id] DESC) = CAST(0 AS bit) ORDER BY [g].[Nickname]"); } public override async Task Where_subquery_distinct_last_boolean(bool async) { await base.Where_subquery_distinct_last_boolean(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[HasSoulPatch] = CAST(0 AS bit)) AND (( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT DISTINCT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ) AS [t] ORDER BY [t].[Id] DESC) = CAST(1 AS bit)) ORDER BY [g].[Nickname]"); } public override async Task Where_subquery_distinct_orderby_firstordefault_boolean(bool async) { await base.Where_subquery_distinct_orderby_firstordefault_boolean(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) AND (COALESCE(( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT DISTINCT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ) AS [t] ORDER BY [t].[Id]), CAST(0 AS bit)) = CAST(1 AS bit))"); } public override async Task Where_subquery_distinct_orderby_firstordefault_boolean_with_pushdown(bool async) { await base.Where_subquery_distinct_orderby_firstordefault_boolean_with_pushdown(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) AND (( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT DISTINCT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ) AS [t] ORDER BY [t].[Id]) = CAST(1 AS bit))"); } public override async Task Where_subquery_union_firstordefault_boolean(bool async) { await base.Where_subquery_union_firstordefault_boolean(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) AND (( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] UNION SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w0] WHERE [g].[FullName] = [w0].[OwnerFullName] ) AS [t] ORDER BY [t].[Id]) = CAST(1 AS bit))"); } public override async Task Where_subquery_join_firstordefault_boolean(bool async) { await base.Where_subquery_join_firstordefault_boolean(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) AND (( SELECT TOP(1) [w].[IsAutomatic] FROM [Weapons] AS [w] INNER JOIN ( SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w0] WHERE [g].[FullName] = [w0].[OwnerFullName] ) AS [t] ON [w].[Id] = [t].[Id] WHERE [g].[FullName] = [w].[OwnerFullName] ORDER BY [w].[Id]) = CAST(1 AS bit))"); } public override async Task Where_subquery_left_join_firstordefault_boolean(bool async) { await base.Where_subquery_left_join_firstordefault_boolean(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) AND (( SELECT TOP(1) [w].[IsAutomatic] FROM [Weapons] AS [w] LEFT JOIN ( SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w0] WHERE [g].[FullName] = [w0].[OwnerFullName] ) AS [t] ON [w].[Id] = [t].[Id] WHERE [g].[FullName] = [w].[OwnerFullName] ORDER BY [w].[Id]) = CAST(1 AS bit))"); } public override async Task Where_subquery_concat_firstordefault_boolean(bool async) { await base.Where_subquery_concat_firstordefault_boolean(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) AND (( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] UNION ALL SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w0] WHERE [g].[FullName] = [w0].[OwnerFullName] ) AS [t] ORDER BY [t].[Id]) = CAST(1 AS bit))"); } public override async Task Concat_with_count(bool async) { await base.Concat_with_count(async); AssertSql( @"SELECT COUNT(*) FROM ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] UNION ALL SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g0] ) AS [t]"); } public override async Task Concat_scalars_with_count(bool async) { await base.Concat_scalars_with_count(async); AssertSql( @"SELECT COUNT(*) FROM ( SELECT [g].[Nickname] FROM [Gears] AS [g] UNION ALL SELECT [g0].[FullName] AS [Nickname] FROM [Gears] AS [g0] ) AS [t]"); } public override async Task Concat_anonymous_with_count(bool async) { await base.Concat_anonymous_with_count(async); AssertSql( @"SELECT COUNT(*) FROM ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [g].[Nickname] AS [Name] FROM [Gears] AS [g] UNION ALL SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank], [g0].[FullName] AS [Name] FROM [Gears] AS [g0] ) AS [t]"); } public override async Task Concat_with_scalar_projection(bool async) { await base.Concat_with_scalar_projection(async); AssertSql( @"SELECT [t].[Nickname] FROM ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] UNION ALL SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g0] ) AS [t]"); } public override async Task Select_navigation_with_concat_and_count(bool async) { await base.Select_navigation_with_concat_and_count(async); AssertSql( @"SELECT ( SELECT COUNT(*) FROM ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] UNION ALL SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w0] WHERE [g].[FullName] = [w0].[OwnerFullName] ) AS [t]) FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(0 AS bit)"); } public override async Task Concat_with_collection_navigations(bool async) { await base.Concat_with_collection_navigations(async); AssertSql( @"SELECT ( SELECT COUNT(*) FROM ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] UNION SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w0] WHERE [g].[FullName] = [w0].[OwnerFullName] ) AS [t]) FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(1 AS bit)"); } public override async Task Union_with_collection_navigations(bool async) { await base.Union_with_collection_navigations(async); AssertSql( @"SELECT ( SELECT COUNT(*) FROM ( SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g0] WHERE ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId]) UNION SELECT [g1].[Nickname], [g1].[SquadId], [g1].[AssignedCityName], [g1].[CityOfBirthName], [g1].[Discriminator], [g1].[FullName], [g1].[HasSoulPatch], [g1].[LeaderNickname], [g1].[LeaderSquadId], [g1].[Rank] FROM [Gears] AS [g1] WHERE ([g].[Nickname] = [g1].[LeaderNickname]) AND ([g].[SquadId] = [g1].[LeaderSquadId]) ) AS [t]) FROM [Gears] AS [g] WHERE [g].[Discriminator] = N'Officer'"); } public override async Task Select_subquery_distinct_firstordefault(bool async) { await base.Select_subquery_distinct_firstordefault(async); AssertSql( @"SELECT ( SELECT TOP(1) [t].[Name] FROM ( SELECT DISTINCT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ) AS [t] ORDER BY [t].[Id]) FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(1 AS bit)"); } public override async Task Singleton_Navigation_With_Member_Access(bool async) { await base.Singleton_Navigation_With_Member_Access(async); AssertSql( @"SELECT [g].[CityOfBirthName] AS [B] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE ([g].[Nickname] = N'Marcus') AND (([g].[CityOfBirthName] <> N'Ephyra') OR [g].[CityOfBirthName] IS NULL)"); } public override async Task GroupJoin_Composite_Key(bool async) { await base.GroupJoin_Composite_Key(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Tags] AS [t] INNER JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId])"); } public override async Task Join_navigation_translated_to_subquery_composite_key(bool async) { await base.Join_navigation_translated_to_subquery_composite_key(async); AssertSql( @"SELECT [g].[FullName], [t0].[Note] FROM [Gears] AS [g] INNER JOIN ( SELECT [t].[Note], [g0].[FullName] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g0] ON ([t].[GearNickName] = [g0].[Nickname]) AND ([t].[GearSquadId] = [g0].[SquadId]) ) AS [t0] ON [g].[FullName] = [t0].[FullName]"); } public override async Task Join_with_order_by_on_inner_sequence_navigation_translated_to_subquery_composite_key(bool async) { await base.Join_with_order_by_on_inner_sequence_navigation_translated_to_subquery_composite_key(async); AssertSql( @"SELECT [g].[FullName], [t0].[Note] FROM [Gears] AS [g] INNER JOIN ( SELECT [t].[Note], [g0].[FullName] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g0] ON ([t].[GearNickName] = [g0].[Nickname]) AND ([t].[GearSquadId] = [g0].[SquadId]) ) AS [t0] ON [g].[FullName] = [t0].[FullName]"); } public override async Task Join_with_order_by_without_skip_or_take(bool async) { await base.Join_with_order_by_without_skip_or_take(async); AssertSql( @"SELECT [t].[Name], [g].[FullName] FROM [Gears] AS [g] INNER JOIN ( SELECT [w].[Name], [w].[OwnerFullName] FROM [Weapons] AS [w] ) AS [t] ON [g].[FullName] = [t].[OwnerFullName]"); } public override async Task Join_with_order_by_without_skip_or_take_nested(bool async) { await base.Join_with_order_by_without_skip_or_take_nested(async); AssertSql( @"SELECT [t0].[Name], [t].[FullName] FROM [Squads] AS [s] INNER JOIN ( SELECT [g].[SquadId], [g].[FullName] FROM [Gears] AS [g] ) AS [t] ON [s].[Id] = [t].[SquadId] INNER JOIN ( SELECT [w].[Name], [w].[OwnerFullName] FROM [Weapons] AS [w] ) AS [t0] ON [t].[FullName] = [t0].[OwnerFullName]"); } public override async Task Collection_with_inheritance_and_join_include_joined(bool async) { await base.Collection_with_inheritance_and_join_include_joined(async); AssertSql( @"SELECT [t0].[Nickname], [t0].[SquadId], [t0].[AssignedCityName], [t0].[CityOfBirthName], [t0].[Discriminator], [t0].[FullName], [t0].[HasSoulPatch], [t0].[LeaderNickname], [t0].[LeaderSquadId], [t0].[Rank], [t1].[Id], [t1].[GearNickName], [t1].[GearSquadId], [t1].[IssueDate], [t1].[Note] FROM [Tags] AS [t] INNER JOIN ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] = N'Officer' ) AS [t0] ON ([t].[GearSquadId] = [t0].[SquadId]) AND ([t].[GearNickName] = [t0].[Nickname]) LEFT JOIN [Tags] AS [t1] ON ([t0].[Nickname] = [t1].[GearNickName]) AND ([t0].[SquadId] = [t1].[GearSquadId])"); } public override async Task Collection_with_inheritance_and_join_include_source(bool async) { await base.Collection_with_inheritance_and_join_include_source(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t0].[Id], [t0].[GearNickName], [t0].[GearSquadId], [t0].[IssueDate], [t0].[Note] FROM [Gears] AS [g] INNER JOIN [Tags] AS [t] ON ([g].[SquadId] = [t].[GearSquadId]) AND ([g].[Nickname] = [t].[GearNickName]) LEFT JOIN [Tags] AS [t0] ON ([g].[Nickname] = [t0].[GearNickName]) AND ([g].[SquadId] = [t0].[GearSquadId]) WHERE [g].[Discriminator] = N'Officer'"); } public override async Task Non_unicode_string_literal_is_used_for_non_unicode_column(bool async) { await base.Non_unicode_string_literal_is_used_for_non_unicode_column(async); AssertSql( @"SELECT [c].[Name], [c].[Location], [c].[Nation] FROM [Cities] AS [c] WHERE [c].[Location] = 'Unknown'"); } public override async Task Non_unicode_string_literal_is_used_for_non_unicode_column_right(bool async) { await base.Non_unicode_string_literal_is_used_for_non_unicode_column_right(async); AssertSql( @"SELECT [c].[Name], [c].[Location], [c].[Nation] FROM [Cities] AS [c] WHERE 'Unknown' = [c].[Location]"); } public override async Task Non_unicode_parameter_is_used_for_non_unicode_column(bool async) { await base.Non_unicode_parameter_is_used_for_non_unicode_column(async); AssertSql( @"@__value_0='Unknown' (Size = 100) (DbType = AnsiString) SELECT [c].[Name], [c].[Location], [c].[Nation] FROM [Cities] AS [c] WHERE [c].[Location] = @__value_0"); } public override async Task Non_unicode_string_literals_in_contains_is_used_for_non_unicode_column(bool async) { await base.Non_unicode_string_literals_in_contains_is_used_for_non_unicode_column(async); AssertSql( @"SELECT [c].[Name], [c].[Location], [c].[Nation] FROM [Cities] AS [c] WHERE [c].[Location] IN ('Unknown', 'Jacinto''s location', 'Ephyra''s location')"); } public override async Task Non_unicode_string_literals_is_used_for_non_unicode_column_with_subquery(bool async) { await base.Non_unicode_string_literals_is_used_for_non_unicode_column_with_subquery(async); AssertSql( @"SELECT [c].[Name], [c].[Location], [c].[Nation] FROM [Cities] AS [c] WHERE ([c].[Location] = 'Unknown') AND (( SELECT COUNT(*) FROM [Gears] AS [g] WHERE ([c].[Name] = [g].[CityOfBirthName]) AND ([g].[Nickname] = N'Paduk')) = 1)"); } public override async Task Non_unicode_string_literals_is_used_for_non_unicode_column_in_subquery(bool async) { await base.Non_unicode_string_literals_is_used_for_non_unicode_column_in_subquery(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] INNER JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name] WHERE ([g].[Nickname] = N'Marcus') AND ([c].[Location] = 'Jacinto''s location')"); } public override async Task Non_unicode_string_literals_is_used_for_non_unicode_column_with_contains(bool async) { await base.Non_unicode_string_literals_is_used_for_non_unicode_column_with_contains(async); AssertSql( @"SELECT [c].[Name], [c].[Location], [c].[Nation] FROM [Cities] AS [c] WHERE [c].[Location] LIKE '%Jacinto%'"); } public override async Task Non_unicode_string_literals_is_used_for_non_unicode_column_with_concat(bool async) { await base.Non_unicode_string_literals_is_used_for_non_unicode_column_with_concat(async); AssertSql( @"SELECT [c].[Name], [c].[Location], [c].[Nation] FROM [Cities] AS [c] WHERE COALESCE([c].[Location], '') + 'Added' LIKE '%Add%'"); } public override void Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_coalesce_result1() { base.Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_coalesce_result1(); // Issue#16897 AssertSql( @"SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON [g].[LeaderNickname] = [g0].[Nickname] LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] ORDER BY [g].[Nickname], [g].[SquadId], [g0].[Nickname], [g0].[SquadId]"); } public override void Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_coalesce_result2() { base.Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_coalesce_result2(); // Issue#16897 AssertSql( @"SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank], [g].[Nickname], [g].[SquadId], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON [g].[LeaderNickname] = [g0].[Nickname] LEFT JOIN [Weapons] AS [w] ON [g0].[FullName] = [w].[OwnerFullName] ORDER BY [g].[Nickname], [g].[SquadId], [g0].[Nickname], [g0].[SquadId]"); } public override async Task Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_coalesce_result3(bool async) { await base.Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_coalesce_result3(async); // Issue#16897 AssertSql( @"SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank], [g].[Nickname], [g].[SquadId], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON [g].[LeaderNickname] = [g0].[Nickname] LEFT JOIN [Weapons] AS [w] ON [g0].[FullName] = [w].[OwnerFullName] LEFT JOIN [Weapons] AS [w0] ON [g].[FullName] = [w0].[OwnerFullName] ORDER BY [g].[Nickname], [g].[SquadId], [g0].[Nickname], [g0].[SquadId], [w].[Id]"); } public override async Task Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_coalesce_result4(bool async) { await base.Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_coalesce_result4(async); // Issue#16897 AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank] FROM [Gears] AS [g] LEFT JOIN ( SELECT [g2].* FROM [Gears] AS [g2] WHERE [g2].[Discriminator] IN (N'Officer', N'Gear') ) AS [t] ON [g].[LeaderNickname] = [t].[Nickname] WHERE [g].[Discriminator] IN (N'Officer', N'Gear') ORDER BY [g].[FullName], [t].[FullName]", // @"SELECT [g.Weapons].[Id], [g.Weapons].[AmmunitionType], [g.Weapons].[IsAutomatic], [g.Weapons].[Name], [g.Weapons].[OwnerFullName], [g.Weapons].[SynergyWithId] FROM [Weapons] AS [g.Weapons] INNER JOIN ( SELECT DISTINCT [g0].[FullName] FROM [Gears] AS [g0] LEFT JOIN ( SELECT [g20].* FROM [Gears] AS [g20] WHERE [g20].[Discriminator] IN (N'Officer', N'Gear') ) AS [t0] ON [g0].[LeaderNickname] = [t0].[Nickname] WHERE [g0].[Discriminator] IN (N'Officer', N'Gear') ) AS [t1] ON [g.Weapons].[OwnerFullName] = [t1].[FullName] ORDER BY [t1].[FullName]", // @"SELECT [g2.Weapons].[Id], [g2.Weapons].[AmmunitionType], [g2.Weapons].[IsAutomatic], [g2.Weapons].[Name], [g2.Weapons].[OwnerFullName], [g2.Weapons].[SynergyWithId] FROM [Weapons] AS [g2.Weapons] INNER JOIN ( SELECT DISTINCT [t2].[FullName], [g1].[FullName] AS [FullName0] FROM [Gears] AS [g1] LEFT JOIN ( SELECT [g21].* FROM [Gears] AS [g21] WHERE [g21].[Discriminator] IN (N'Officer', N'Gear') ) AS [t2] ON [g1].[LeaderNickname] = [t2].[Nickname] WHERE [g1].[Discriminator] IN (N'Officer', N'Gear') ) AS [t3] ON [g2.Weapons].[OwnerFullName] = [t3].[FullName] ORDER BY [t3].[FullName0], [t3].[FullName]"); } public override async Task Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_inheritance_and_coalesce_result(bool async) { await base.Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_inheritance_and_coalesce_result(async); // Issue#16897 AssertSql( @"SELECT [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank], [g].[Nickname], [g].[SquadId], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN ( SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g0] WHERE [g0].[Discriminator] = N'Officer' ) AS [t] ON [g].[LeaderNickname] = [t].[Nickname] LEFT JOIN [Weapons] AS [w] ON [t].[FullName] = [w].[OwnerFullName] LEFT JOIN [Weapons] AS [w0] ON [g].[FullName] = [w0].[OwnerFullName] ORDER BY [g].[Nickname], [g].[SquadId], [t].[Nickname], [t].[SquadId], [w].[Id]"); } public override async Task Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_conditional_result(bool async) { await base.Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_conditional_result(async); // Issue#16897 AssertSql( @"SELECT CASE WHEN [g0].[Nickname] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId], [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON [g].[LeaderNickname] = [g0].[Nickname] LEFT JOIN [Weapons] AS [w] ON [g0].[FullName] = [w].[OwnerFullName] LEFT JOIN [Weapons] AS [w0] ON [g].[FullName] = [w0].[OwnerFullName] ORDER BY [g].[Nickname], [g].[SquadId], [w].[Id], [w0].[Id]"); } public override async Task Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_complex_projection_result(bool async) { await base.Include_on_GroupJoin_SelectMany_DefaultIfEmpty_with_complex_projection_result(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank] FROM [Gears] AS [g] LEFT JOIN ( SELECT [g2].* FROM [Gears] AS [g2] WHERE [g2].[Discriminator] IN (N'Officer', N'Gear') ) AS [t] ON [g].[LeaderNickname] = [t].[Nickname] WHERE [g].[Discriminator] IN (N'Officer', N'Gear') ORDER BY [g].[FullName], [t].[FullName]", // @"SELECT [g.Weapons].[Id], [g.Weapons].[AmmunitionType], [g.Weapons].[IsAutomatic], [g.Weapons].[Name], [g.Weapons].[OwnerFullName], [g.Weapons].[SynergyWithId] FROM [Weapons] AS [g.Weapons] INNER JOIN ( SELECT DISTINCT [g0].[FullName] FROM [Gears] AS [g0] LEFT JOIN ( SELECT [g20].* FROM [Gears] AS [g20] WHERE [g20].[Discriminator] IN (N'Officer', N'Gear') ) AS [t0] ON [g0].[LeaderNickname] = [t0].[Nickname] WHERE [g0].[Discriminator] IN (N'Officer', N'Gear') AND ([g0].[Nickname] IS NOT NULL AND [t0].[Nickname] IS NULL) ) AS [t1] ON [g.Weapons].[OwnerFullName] = [t1].[FullName] ORDER BY [t1].[FullName]", // @"SELECT [g2.Weapons].[Id], [g2.Weapons].[AmmunitionType], [g2.Weapons].[IsAutomatic], [g2.Weapons].[Name], [g2.Weapons].[OwnerFullName], [g2.Weapons].[SynergyWithId] FROM [Weapons] AS [g2.Weapons] INNER JOIN ( SELECT DISTINCT [t2].[FullName], [g1].[FullName] AS [FullName0] FROM [Gears] AS [g1] LEFT JOIN ( SELECT [g21].* FROM [Gears] AS [g21] WHERE [g21].[Discriminator] IN (N'Officer', N'Gear') ) AS [t2] ON [g1].[LeaderNickname] = [t2].[Nickname] WHERE [g1].[Discriminator] IN (N'Officer', N'Gear') AND [t2].[Nickname] IS NOT NULL ) AS [t3] ON [g2.Weapons].[OwnerFullName] = [t3].[FullName] ORDER BY [t3].[FullName0], [t3].[FullName]"); } public override async Task Coalesce_operator_in_predicate(bool async) { await base.Coalesce_operator_in_predicate(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE COALESCE([w].[IsAutomatic], CAST(0 AS bit)) = CAST(1 AS bit)"); } public override async Task Coalesce_operator_in_predicate_with_other_conditions(bool async) { await base.Coalesce_operator_in_predicate_with_other_conditions(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[AmmunitionType] = 1) AND (COALESCE([w].[IsAutomatic], CAST(0 AS bit)) = CAST(1 AS bit))"); } public override async Task Coalesce_operator_in_projection_with_other_conditions(bool async) { await base.Coalesce_operator_in_projection_with_other_conditions(async); AssertSql( @"SELECT CASE WHEN (([w].[AmmunitionType] = 1) AND [w].[AmmunitionType] IS NOT NULL) AND (COALESCE([w].[IsAutomatic], CAST(0 AS bit)) = CAST(1 AS bit)) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END FROM [Weapons] AS [w]"); } public override async Task Optional_navigation_type_compensation_works_with_predicate(bool async) { await base.Optional_navigation_type_compensation_works_with_predicate(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE (([t].[Note] <> N'K.I.A.') OR [t].[Note] IS NULL) AND ([g].[HasSoulPatch] = CAST(1 AS bit))"); } public override async Task Optional_navigation_type_compensation_works_with_predicate2(bool async) { await base.Optional_navigation_type_compensation_works_with_predicate2(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE [g].[HasSoulPatch] = CAST(1 AS bit)"); } public override async Task Optional_navigation_type_compensation_works_with_predicate_negated(bool async) { await base.Optional_navigation_type_compensation_works_with_predicate_negated(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE [g].[HasSoulPatch] = CAST(0 AS bit)"); } public override async Task Optional_navigation_type_compensation_works_with_predicate_negated_complex1(bool async) { await base.Optional_navigation_type_compensation_works_with_predicate_negated_complex1(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE CASE WHEN [g].[HasSoulPatch] = CAST(1 AS bit) THEN CAST(1 AS bit) ELSE [g].[HasSoulPatch] END = CAST(0 AS bit)"); } public override async Task Optional_navigation_type_compensation_works_with_predicate_negated_complex2(bool async) { await base.Optional_navigation_type_compensation_works_with_predicate_negated_complex2(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE CASE WHEN [g].[HasSoulPatch] = CAST(0 AS bit) THEN CAST(0 AS bit) ELSE [g].[HasSoulPatch] END = CAST(0 AS bit)"); } public override async Task Optional_navigation_type_compensation_works_with_conditional_expression(bool async) { await base.Optional_navigation_type_compensation_works_with_conditional_expression(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE CASE WHEN [g].[HasSoulPatch] = CAST(1 AS bit) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END = CAST(1 AS bit)"); } public override async Task Optional_navigation_type_compensation_works_with_binary_expression(bool async) { await base.Optional_navigation_type_compensation_works_with_binary_expression(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) OR ([t].[Note] LIKE N'%Cole%')"); } public override async Task Optional_navigation_type_compensation_works_with_binary_and_expression(bool async) { await base.Optional_navigation_type_compensation_works_with_binary_and_expression(async); AssertSql( @"SELECT CASE WHEN ([g].[HasSoulPatch] = CAST(1 AS bit)) AND ([t].[Note] LIKE N'%Cole%') THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId])"); } public override async Task Optional_navigation_type_compensation_works_with_projection(bool async) { await base.Optional_navigation_type_compensation_works_with_projection(async); AssertSql( @"SELECT [g].[SquadId] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE ([t].[Note] <> N'K.I.A.') OR [t].[Note] IS NULL"); } public override async Task Optional_navigation_type_compensation_works_with_projection_into_anonymous_type(bool async) { await base.Optional_navigation_type_compensation_works_with_projection_into_anonymous_type(async); AssertSql( @"SELECT [g].[SquadId] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE ([t].[Note] <> N'K.I.A.') OR [t].[Note] IS NULL"); } public override async Task Optional_navigation_type_compensation_works_with_DTOs(bool async) { await base.Optional_navigation_type_compensation_works_with_DTOs(async); AssertSql( @"SELECT [g].[SquadId] AS [Id] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE ([t].[Note] <> N'K.I.A.') OR [t].[Note] IS NULL"); } public override async Task Optional_navigation_type_compensation_works_with_list_initializers(bool async) { await base.Optional_navigation_type_compensation_works_with_list_initializers(async); AssertSql( @"SELECT [g].[SquadId], [g].[SquadId] + 1 FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE ([t].[Note] <> N'K.I.A.') OR [t].[Note] IS NULL ORDER BY [t].[Note]"); } public override async Task Optional_navigation_type_compensation_works_with_array_initializers(bool async) { await base.Optional_navigation_type_compensation_works_with_array_initializers(async); AssertSql( @"SELECT [g].[SquadId] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE ([t].[Note] <> N'K.I.A.') OR [t].[Note] IS NULL"); } public override async Task Optional_navigation_type_compensation_works_with_orderby(bool async) { await base.Optional_navigation_type_compensation_works_with_orderby(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE ([t].[Note] <> N'K.I.A.') OR [t].[Note] IS NULL ORDER BY [g].[SquadId]"); } public override async Task Optional_navigation_type_compensation_works_with_all(bool async) { await base.Optional_navigation_type_compensation_works_with_all(async); AssertSql( @"SELECT CASE WHEN NOT EXISTS ( SELECT 1 FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE (([t].[Note] <> N'K.I.A.') OR [t].[Note] IS NULL) AND ([g].[HasSoulPatch] = CAST(0 AS bit))) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END"); } public override async Task Optional_navigation_type_compensation_works_with_negated_predicate(bool async) { await base.Optional_navigation_type_compensation_works_with_negated_predicate(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE (([t].[Note] <> N'K.I.A.') OR [t].[Note] IS NULL) AND ([g].[HasSoulPatch] = CAST(0 AS bit))"); } public override async Task Optional_navigation_type_compensation_works_with_contains(bool async) { await base.Optional_navigation_type_compensation_works_with_contains(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE (([t].[Note] <> N'K.I.A.') OR [t].[Note] IS NULL) AND EXISTS ( SELECT 1 FROM [Gears] AS [g0] WHERE [g0].[SquadId] = [g].[SquadId])"); } public override async Task Optional_navigation_type_compensation_works_with_skip(bool async) { await base.Optional_navigation_type_compensation_works_with_skip(async); AssertSql( @"SELECT [t0].[SquadId] FROM [Tags] AS [t] LEFT JOIN ( SELECT [t.Gear].* FROM [Gears] AS [t.Gear] WHERE [t.Gear].[Discriminator] IN (N'Officer', N'Gear') ) AS [t0] ON ([t].[GearNickName] = [t0].[Nickname]) AND ([t].[GearSquadId] = [t0].[SquadId]) WHERE ([t].[Note] <> N'K.I.A.') OR [t].[Note] IS NULL ORDER BY [t].[Note]", // @"@_outer_SquadId='1' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] IN (N'Officer', N'Gear') ORDER BY [g].[Nickname] OFFSET @_outer_SquadId ROWS", // @"@_outer_SquadId='1' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] IN (N'Officer', N'Gear') ORDER BY [g].[Nickname] OFFSET @_outer_SquadId ROWS", // @"@_outer_SquadId='1' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] IN (N'Officer', N'Gear') ORDER BY [g].[Nickname] OFFSET @_outer_SquadId ROWS", // @"@_outer_SquadId='1' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] IN (N'Officer', N'Gear') ORDER BY [g].[Nickname] OFFSET @_outer_SquadId ROWS", // @"@_outer_SquadId='2' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] IN (N'Officer', N'Gear') ORDER BY [g].[Nickname] OFFSET @_outer_SquadId ROWS"); } public override async Task Optional_navigation_type_compensation_works_with_take(bool async) { await base.Optional_navigation_type_compensation_works_with_take(async); AssertSql( @"SELECT [t0].[SquadId] FROM [Tags] AS [t] LEFT JOIN ( SELECT [t.Gear].* FROM [Gears] AS [t.Gear] WHERE [t.Gear].[Discriminator] IN (N'Officer', N'Gear') ) AS [t0] ON ([t].[GearNickName] = [t0].[Nickname]) AND ([t].[GearSquadId] = [t0].[SquadId]) WHERE ([t].[Note] <> N'K.I.A.') OR [t].[Note] IS NULL ORDER BY [t].[Note]", // @"@_outer_SquadId='1' SELECT TOP(@_outer_SquadId) [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] IN (N'Officer', N'Gear') ORDER BY [g].[Nickname]", // @"@_outer_SquadId='1' SELECT TOP(@_outer_SquadId) [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] IN (N'Officer', N'Gear') ORDER BY [g].[Nickname]", // @"@_outer_SquadId='1' SELECT TOP(@_outer_SquadId) [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] IN (N'Officer', N'Gear') ORDER BY [g].[Nickname]", // @"@_outer_SquadId='1' SELECT TOP(@_outer_SquadId) [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] IN (N'Officer', N'Gear') ORDER BY [g].[Nickname]", // @"@_outer_SquadId='2' SELECT TOP(@_outer_SquadId) [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] IN (N'Officer', N'Gear') ORDER BY [g].[Nickname]"); } public override async Task Select_correlated_filtered_collection(bool async) { await base.Select_correlated_filtered_collection(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [c].[Name], [t].[Id], [t].[AmmunitionType], [t].[IsAutomatic], [t].[Name], [t].[OwnerFullName], [t].[SynergyWithId] FROM [Gears] AS [g] INNER JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name] LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[Name] <> N'Lancer') OR [w].[Name] IS NULL ) AS [t] ON [g].[FullName] = [t].[OwnerFullName] WHERE [c].[Name] IN (N'Ephyra', N'Hanover') ORDER BY [g].[Nickname], [g].[SquadId], [c].[Name]"); } public override async Task Select_correlated_filtered_collection_with_composite_key(bool async) { await base.Select_correlated_filtered_collection_with_composite_key(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank] FROM [Gears] AS [g] LEFT JOIN ( SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g0] WHERE [g0].[Nickname] <> N'Dom' ) AS [t] ON ([g].[Nickname] = [t].[LeaderNickname]) AND ([g].[SquadId] = [t].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[Nickname], [g].[SquadId], [t].[Nickname]"); } public override async Task Select_correlated_filtered_collection_works_with_caching(bool async) { await base.Select_correlated_filtered_collection_works_with_caching(async); AssertSql( @"SELECT [t].[Id], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON [t].[GearNickName] = [g].[Nickname] ORDER BY [t].[Note], [t].[Id], [g].[Nickname]"); } public override async Task Join_predicate_value_equals_condition(bool async) { await base.Join_predicate_value_equals_condition(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] INNER JOIN [Weapons] AS [w] ON [w].[SynergyWithId] IS NOT NULL"); } public override async Task Join_predicate_value(bool async) { await base.Join_predicate_value(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] INNER JOIN [Weapons] AS [w] ON [g].[HasSoulPatch] = CAST(1 AS bit)"); } public override async Task Join_predicate_condition_equals_condition(bool async) { await base.Join_predicate_condition_equals_condition(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] INNER JOIN [Weapons] AS [w] ON [w].[SynergyWithId] IS NOT NULL"); } public override async Task Left_join_predicate_value_equals_condition(bool async) { await base.Left_join_predicate_value_equals_condition(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON [w].[SynergyWithId] IS NOT NULL"); } public override async Task Left_join_predicate_value(bool async) { await base.Left_join_predicate_value(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON [g].[HasSoulPatch] = CAST(1 AS bit)"); } public override async Task Left_join_predicate_condition_equals_condition(bool async) { await base.Left_join_predicate_condition_equals_condition(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON [w].[SynergyWithId] IS NOT NULL"); } public override async Task Where_datetimeoffset_now(bool async) { await base.Where_datetimeoffset_now(async); AssertSql( @"SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE [m].[Timeline] <> SYSDATETIMEOFFSET()"); } public override async Task Where_datetimeoffset_utcnow(bool async) { await base.Where_datetimeoffset_utcnow(async); AssertSql( @"SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE [m].[Timeline] <> CAST(SYSUTCDATETIME() AS datetimeoffset)"); } public override async Task Where_datetimeoffset_date_component(bool async) { await base.Where_datetimeoffset_date_component(async); AssertSql( @"@__Date_0='0001-01-01T00:00:00.0000000' SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE CONVERT(date, [m].[Timeline]) > @__Date_0"); } public override async Task Where_datetimeoffset_year_component(bool async) { await base.Where_datetimeoffset_year_component(async); AssertSql( @"SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE DATEPART(year, [m].[Timeline]) = 2"); } public override async Task Where_datetimeoffset_month_component(bool async) { await base.Where_datetimeoffset_month_component(async); AssertSql( @"SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE DATEPART(month, [m].[Timeline]) = 1"); } public override async Task Where_datetimeoffset_dayofyear_component(bool async) { await base.Where_datetimeoffset_dayofyear_component(async); AssertSql( @"SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE DATEPART(dayofyear, [m].[Timeline]) = 2"); } public override async Task Where_datetimeoffset_day_component(bool async) { await base.Where_datetimeoffset_day_component(async); AssertSql( @"SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE DATEPART(day, [m].[Timeline]) = 2"); } public override async Task Where_datetimeoffset_hour_component(bool async) { await base.Where_datetimeoffset_hour_component(async); AssertSql( @"SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE DATEPART(hour, [m].[Timeline]) = 10"); } public override async Task Where_datetimeoffset_minute_component(bool async) { await base.Where_datetimeoffset_minute_component(async); AssertSql( @"SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE DATEPART(minute, [m].[Timeline]) = 0"); } public override async Task Where_datetimeoffset_second_component(bool async) { await base.Where_datetimeoffset_second_component(async); AssertSql( @"SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE DATEPART(second, [m].[Timeline]) = 0"); } public override async Task Where_datetimeoffset_millisecond_component(bool async) { await base.Where_datetimeoffset_millisecond_component(async); AssertSql( @"SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE DATEPART(millisecond, [m].[Timeline]) = 0"); } public override async Task DateTimeOffset_DateAdd_AddMonths(bool async) { await base.DateTimeOffset_DateAdd_AddMonths(async); AssertSql( @"SELECT DATEADD(month, CAST(1 AS int), [m].[Timeline]) FROM [Missions] AS [m]"); } public override async Task DateTimeOffset_DateAdd_AddDays(bool async) { await base.DateTimeOffset_DateAdd_AddDays(async); AssertSql( @"SELECT DATEADD(day, CAST(1.0E0 AS int), [m].[Timeline]) FROM [Missions] AS [m]"); } public override async Task DateTimeOffset_DateAdd_AddHours(bool async) { await base.DateTimeOffset_DateAdd_AddHours(async); AssertSql( @"SELECT DATEADD(hour, CAST(1.0E0 AS int), [m].[Timeline]) FROM [Missions] AS [m]"); } public override async Task DateTimeOffset_DateAdd_AddMinutes(bool async) { await base.DateTimeOffset_DateAdd_AddMinutes(async); AssertSql( @"SELECT DATEADD(minute, CAST(1.0E0 AS int), [m].[Timeline]) FROM [Missions] AS [m]"); } public override async Task DateTimeOffset_DateAdd_AddSeconds(bool async) { await base.DateTimeOffset_DateAdd_AddSeconds(async); AssertSql( @"SELECT DATEADD(second, CAST(1.0E0 AS int), [m].[Timeline]) FROM [Missions] AS [m]"); } public override async Task DateTimeOffset_DateAdd_AddMilliseconds(bool async) { await base.DateTimeOffset_DateAdd_AddMilliseconds(async); AssertSql( @"SELECT DATEADD(millisecond, CAST(300.0E0 AS int), [m].[Timeline]) FROM [Missions] AS [m]"); } public override async Task Where_datetimeoffset_milliseconds_parameter_and_constant(bool async) { await base.Where_datetimeoffset_milliseconds_parameter_and_constant(async); AssertSql( @"SELECT COUNT(*) FROM [Missions] AS [m] WHERE [m].[Timeline] = '1902-01-02T10:00:00.1234567+01:30'"); } public override async Task Orderby_added_for_client_side_GroupJoin_composite_dependent_to_principal_LOJ_when_incomplete_key_is_used( bool async) { await base.Orderby_added_for_client_side_GroupJoin_composite_dependent_to_principal_LOJ_when_incomplete_key_is_used(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[Note], [t0].[Nickname], [t0].[SquadId], [t0].[AssignedCityName], [t0].[CityOfBirthName], [t0].[Discriminator], [t0].[FullName], [t0].[HasSoulPatch], [t0].[LeaderNickname], [t0].[LeaderSquadId], [t0].[Rank] FROM [Tags] AS [t] LEFT JOIN ( SELECT [g].* FROM [Gears] AS [g] WHERE [g].[Discriminator] IN (N'Officer', N'Gear') ) AS [t0] ON [t].[GearNickName] = [t0].[Nickname] ORDER BY [t].[GearNickName]"); } public override async Task Complex_predicate_with_AndAlso_and_nullable_bool_property(bool async) { await base.Complex_predicate_with_AndAlso_and_nullable_bool_property(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g] ON [w].[OwnerFullName] = [g].[FullName] WHERE ([w].[Id] <> 50) AND ([g].[HasSoulPatch] = CAST(0 AS bit))"); } public override async Task Distinct_with_optional_navigation_is_translated_to_sql(bool async) { await base.Distinct_with_optional_navigation_is_translated_to_sql(async); AssertSql( @"SELECT DISTINCT [g].[HasSoulPatch] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) WHERE ([t].[Note] <> N'Foo') OR [t].[Note] IS NULL"); } public override async Task Sum_with_optional_navigation_is_translated_to_sql(bool async) { await base.Sum_with_optional_navigation_is_translated_to_sql(async); AssertSql( @"SELECT COALESCE(SUM([g].[SquadId]), 0) FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) WHERE ([t].[Note] <> N'Foo') OR [t].[Note] IS NULL"); } public override async Task Count_with_optional_navigation_is_translated_to_sql(bool async) { await base.Count_with_optional_navigation_is_translated_to_sql(async); AssertSql( @"SELECT COUNT(*) FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) WHERE ([t].[Note] <> N'Foo') OR [t].[Note] IS NULL"); } public override async Task FirstOrDefault_with_manually_created_groupjoin_is_translated_to_sql(bool async) { await base.FirstOrDefault_with_manually_created_groupjoin_is_translated_to_sql(async); AssertSql( @"SELECT TOP(1) [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Squads] AS [s] LEFT JOIN [Gears] AS [g] ON [s].[Id] = [g].[SquadId] WHERE [s].[Name] = N'Kilo'"); } public override async Task Any_with_optional_navigation_as_subquery_predicate_is_translated_to_sql(bool async) { await base.Any_with_optional_navigation_as_subquery_predicate_is_translated_to_sql(async); AssertSql( @"SELECT [s].[Name] FROM [Squads] AS [s] WHERE NOT (EXISTS ( SELECT 1 FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) WHERE ([s].[Id] = [g].[SquadId]) AND ([t].[Note] = N'Dom''s Tag')))"); } public override async Task All_with_optional_navigation_is_translated_to_sql(bool async) { await base.All_with_optional_navigation_is_translated_to_sql(async); AssertSql( @"SELECT CASE WHEN NOT EXISTS ( SELECT 1 FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) WHERE ([t].[Note] = N'Foo') AND [t].[Note] IS NOT NULL) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END"); } public override async Task Contains_with_local_nullable_guid_list_closure(bool async) { await base.Contains_with_local_nullable_guid_list_closure(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] WHERE [t].[Id] IN ('d2c26679-562b-44d1-ab96-23d1775e0926', '23cbcf9b-ce14-45cf-aafa-2c2667ebfdd3', 'ab1b82d7-88db-42bd-a132-7eef9aa68af4')"); } public override async Task Unnecessary_include_doesnt_get_added_complex_when_projecting_EF_Property(bool async) { await base.Unnecessary_include_doesnt_get_added_complex_when_projecting_EF_Property(async); AssertSql( @"SELECT [g].[FullName] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(1 AS bit) ORDER BY [g].[Rank]"); } public override async Task Multiple_order_bys_are_properly_lifted_from_subquery_created_by_include(bool async) { await base.Multiple_order_bys_are_properly_lifted_from_subquery_created_by_include(async); AssertSql( @"SELECT [g].[FullName] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(0 AS bit) ORDER BY [g].[FullName]"); } public override async Task Order_by_is_properly_lifted_from_subquery_with_same_order_by_in_the_outer_query(bool async) { await base.Order_by_is_properly_lifted_from_subquery_with_same_order_by_in_the_outer_query(async); AssertSql( @"SELECT [g].[FullName] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(0 AS bit) ORDER BY [g].[FullName]"); } public override async Task Where_is_properly_lifted_from_subquery_created_by_include(bool async) { await base.Where_is_properly_lifted_from_subquery_created_by_include(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) WHERE ([g].[FullName] <> N'Augustus Cole') AND ([g].[HasSoulPatch] = CAST(0 AS bit)) ORDER BY [g].[FullName]"); } public override async Task Subquery_is_lifted_from_main_from_clause_of_SelectMany(bool async) { await base.Subquery_is_lifted_from_main_from_clause_of_SelectMany(async); AssertSql( @"SELECT [g].[FullName] AS [Name1], [g0].[FullName] AS [Name2] FROM [Gears] AS [g] CROSS JOIN [Gears] AS [g0] WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) AND ([g0].[HasSoulPatch] = CAST(0 AS bit)) ORDER BY [g].[FullName]"); } public override async Task Subquery_containing_SelectMany_projecting_main_from_clause_gets_lifted(bool async) { await base.Subquery_containing_SelectMany_projecting_main_from_clause_gets_lifted(async); AssertSql( @"SELECT [g].[FullName] FROM [Gears] AS [g] CROSS JOIN [Tags] AS [t] WHERE [g].[HasSoulPatch] = CAST(1 AS bit) ORDER BY [g].[FullName]"); } public override async Task Subquery_containing_join_projecting_main_from_clause_gets_lifted(bool async) { await base.Subquery_containing_join_projecting_main_from_clause_gets_lifted(async); AssertSql( @"SELECT [g].[Nickname] FROM [Gears] AS [g] INNER JOIN [Tags] AS [t] ON [g].[Nickname] = [t].[GearNickName] ORDER BY [g].[Nickname]"); } public override async Task Subquery_containing_left_join_projecting_main_from_clause_gets_lifted(bool async) { await base.Subquery_containing_left_join_projecting_main_from_clause_gets_lifted(async); AssertSql( @"SELECT [g].[Nickname] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON [g].[Nickname] = [t].[GearNickName] ORDER BY [g].[Nickname]"); } public override async Task Subquery_containing_join_gets_lifted_clashing_names(bool async) { await base.Subquery_containing_join_gets_lifted_clashing_names(async); AssertSql( @"SELECT [g].[Nickname] FROM [Gears] AS [g] INNER JOIN [Tags] AS [t] ON [g].[Nickname] = [t].[GearNickName] INNER JOIN [Tags] AS [t0] ON [g].[Nickname] = [t0].[GearNickName] WHERE ([t].[GearNickName] <> N'Cole Train') OR [t].[GearNickName] IS NULL ORDER BY [g].[Nickname], [t0].[Id]"); } public override async Task Subquery_created_by_include_gets_lifted_nested(bool async) { await base.Subquery_created_by_include_gets_lifted_nested(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [c].[Name], [c].[Location], [c].[Nation] FROM [Gears] AS [g] INNER JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name] WHERE EXISTS ( SELECT 1 FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName]) AND ([g].[HasSoulPatch] = CAST(0 AS bit)) ORDER BY [g].[Nickname]"); } public override async Task Subquery_is_lifted_from_additional_from_clause(bool async) { await base.Subquery_is_lifted_from_additional_from_clause(async); AssertSql( @"SELECT [g].[FullName] AS [Name1], [t].[FullName] AS [Name2] FROM [Gears] AS [g] CROSS JOIN ( SELECT [g0].[FullName], [g0].[HasSoulPatch] FROM [Gears] AS [g0] ) AS [t] WHERE ([g].[HasSoulPatch] = CAST(1 AS bit)) AND ([t].[HasSoulPatch] = CAST(0 AS bit)) ORDER BY [g].[FullName]"); } public override async Task Subquery_with_result_operator_is_not_lifted(bool async) { await base.Subquery_with_result_operator_is_not_lifted(async); AssertSql( @"@__p_0='2' SELECT [t].[FullName] FROM ( SELECT TOP(@__p_0) [g].[FullName], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(0 AS bit) ORDER BY [g].[FullName] ) AS [t] ORDER BY [t].[Rank]"); } public override async Task Skip_with_orderby_followed_by_orderBy_is_pushed_down(bool async) { await base.Skip_with_orderby_followed_by_orderBy_is_pushed_down(async); AssertSql( @"@__p_0='1' SELECT [t].[FullName] FROM ( SELECT [g].[FullName], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(0 AS bit) ORDER BY [g].[FullName] OFFSET @__p_0 ROWS ) AS [t] ORDER BY [t].[Rank]"); } public override async Task Take_without_orderby_followed_by_orderBy_is_pushed_down1(bool async) { await base.Take_without_orderby_followed_by_orderBy_is_pushed_down1(async); AssertSql( @"@__p_0='999' SELECT [t].[FullName] FROM ( SELECT TOP(@__p_0) [g].[FullName], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(0 AS bit) ) AS [t] ORDER BY [t].[Rank]"); } public override async Task Take_without_orderby_followed_by_orderBy_is_pushed_down2(bool async) { await base.Take_without_orderby_followed_by_orderBy_is_pushed_down2(async); AssertSql( @"@__p_0='999' SELECT [t].[FullName] FROM ( SELECT TOP(@__p_0) [g].[FullName], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(0 AS bit) ) AS [t] ORDER BY [t].[Rank]"); } public override async Task Take_without_orderby_followed_by_orderBy_is_pushed_down3(bool async) { await base.Take_without_orderby_followed_by_orderBy_is_pushed_down3(async); AssertSql( @"@__p_0='999' SELECT [t].[FullName] FROM ( SELECT TOP(@__p_0) [g].[FullName], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(0 AS bit) ) AS [t] ORDER BY [t].[FullName], [t].[Rank]"); } public override async Task Select_length_of_string_property(bool async) { await base.Select_length_of_string_property(async); AssertSql( @"SELECT [w].[Name], CAST(LEN([w].[Name]) AS int) AS [Length] FROM [Weapons] AS [w]"); } public override async Task Client_method_on_collection_navigation_in_outer_join_key(bool async) { await base.Client_method_on_collection_navigation_in_outer_join_key(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname] FROM [Gears] AS [g] WHERE [g].[Discriminator] IN (N'Officer', N'Gear')", // @"@_outer_FullName1='Damon Baird' (Size = 450) SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w0] WHERE @_outer_FullName1 = [w0].[OwnerFullName]", // @"@_outer_FullName1='Augustus Cole' (Size = 450) SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w0] WHERE @_outer_FullName1 = [w0].[OwnerFullName]", // @"@_outer_FullName1='Dominic Santiago' (Size = 450) SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w0] WHERE @_outer_FullName1 = [w0].[OwnerFullName]", // @"@_outer_FullName1='Marcus Fenix' (Size = 450) SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w0] WHERE @_outer_FullName1 = [w0].[OwnerFullName]", // @"@_outer_FullName1='Garron Paduk' (Size = 450) SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w0] WHERE @_outer_FullName1 = [w0].[OwnerFullName]", // @"SELECT [o].[FullName], [o].[Nickname] AS [o] FROM [Gears] AS [o] WHERE ([o].[Discriminator] = N'Officer') AND ([o].[HasSoulPatch] = 1)", // @"@_outer_FullName='Damon Baird' (Size = 450) SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE @_outer_FullName = [w].[OwnerFullName]", // @"@_outer_FullName='Marcus Fenix' (Size = 450) SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE @_outer_FullName = [w].[OwnerFullName]"); } public override async Task Member_access_on_derived_entity_using_cast(bool async) { await base.Member_access_on_derived_entity_using_cast(async); AssertSql( @"SELECT [f].[Name], [f].[Eradicated] FROM [Factions] AS [f] ORDER BY [f].[Name]"); } public override async Task Member_access_on_derived_materialized_entity_using_cast(bool async) { await base.Member_access_on_derived_materialized_entity_using_cast(async); AssertSql( @"SELECT [f].[Id], [f].[CapitalName], [f].[Discriminator], [f].[Name], [f].[ServerAddress], [f].[CommanderName], [f].[Eradicated] FROM [Factions] AS [f] ORDER BY [f].[Name]"); } public override async Task Member_access_on_derived_entity_using_cast_and_let(bool async) { await base.Member_access_on_derived_entity_using_cast_and_let(async); AssertSql( @"SELECT [f].[Name], [f].[Eradicated] FROM [Factions] AS [f] ORDER BY [f].[Name]"); } public override async Task Property_access_on_derived_entity_using_cast(bool async) { await base.Property_access_on_derived_entity_using_cast(async); AssertSql( @"SELECT [f].[Name], [f].[Eradicated] FROM [Factions] AS [f] ORDER BY [f].[Name]"); } public override async Task Navigation_access_on_derived_entity_using_cast(bool async) { await base.Navigation_access_on_derived_entity_using_cast(async); AssertSql( @"SELECT [f].[Name], [t].[ThreatLevel] AS [Threat] FROM [Factions] AS [f] LEFT JOIN ( SELECT [l].[Name], [l].[ThreatLevel] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name] ORDER BY [f].[Name]"); } public override async Task Navigation_access_on_derived_materialized_entity_using_cast(bool async) { await base.Navigation_access_on_derived_materialized_entity_using_cast(async); AssertSql( @"SELECT [f].[Id], [f].[CapitalName], [f].[Discriminator], [f].[Name], [f].[ServerAddress], [f].[CommanderName], [f].[Eradicated], [t].[ThreatLevel] AS [Threat] FROM [Factions] AS [f] LEFT JOIN ( SELECT [l].[Name], [l].[ThreatLevel] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name] ORDER BY [f].[Name]"); } public override async Task Navigation_access_via_EFProperty_on_derived_entity_using_cast(bool async) { await base.Navigation_access_via_EFProperty_on_derived_entity_using_cast(async); AssertSql( @"SELECT [f].[Name], [t].[ThreatLevel] AS [Threat] FROM [Factions] AS [f] LEFT JOIN ( SELECT [l].[Name], [l].[ThreatLevel] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name] ORDER BY [f].[Name]"); } public override async Task Navigation_access_fk_on_derived_entity_using_cast(bool async) { await base.Navigation_access_fk_on_derived_entity_using_cast(async); AssertSql( @"SELECT [f].[Name], [t].[Name] AS [CommanderName] FROM [Factions] AS [f] LEFT JOIN ( SELECT [l].[Name] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name] ORDER BY [f].[Name]"); } public override async Task Collection_navigation_access_on_derived_entity_using_cast(bool async) { await base.Collection_navigation_access_on_derived_entity_using_cast(async); AssertSql( @"SELECT [f].[Name], ( SELECT COUNT(*) FROM [LocustLeaders] AS [l] WHERE [f].[Id] = [l].[LocustHordeId]) AS [LeadersCount] FROM [Factions] AS [f] ORDER BY [f].[Name]"); } public override async Task Collection_navigation_access_on_derived_entity_using_cast_in_SelectMany(bool async) { await base.Collection_navigation_access_on_derived_entity_using_cast_in_SelectMany(async); AssertSql( @"SELECT [f].[Name], [l].[Name] AS [LeaderName] FROM [Factions] AS [f] INNER JOIN [LocustLeaders] AS [l] ON [f].[Id] = [l].[LocustHordeId] ORDER BY [l].[Name]"); } public override async Task Include_on_derived_entity_using_OfType(bool async) { await base.Include_on_derived_entity_using_OfType(async); AssertSql( @"SELECT [f].[Id], [f].[CapitalName], [f].[Discriminator], [f].[Name], [f].[ServerAddress], [f].[CommanderName], [f].[Eradicated], [t].[Name], [t].[Discriminator], [t].[LocustHordeId], [t].[ThreatLevel], [t].[ThreatLevelByte], [t].[ThreatLevelNullableByte], [t].[DefeatedByNickname], [t].[DefeatedBySquadId], [t].[HighCommandId], [l0].[Name], [l0].[Discriminator], [l0].[LocustHordeId], [l0].[ThreatLevel], [l0].[ThreatLevelByte], [l0].[ThreatLevelNullableByte], [l0].[DefeatedByNickname], [l0].[DefeatedBySquadId], [l0].[HighCommandId] FROM [Factions] AS [f] LEFT JOIN ( SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name] LEFT JOIN [LocustLeaders] AS [l0] ON [f].[Id] = [l0].[LocustHordeId] ORDER BY [f].[Name], [f].[Id], [t].[Name]"); } public override async Task Distinct_on_subquery_doesnt_get_lifted(bool async) { await base.Distinct_on_subquery_doesnt_get_lifted(async); AssertSql( @"SELECT [t].[HasSoulPatch] FROM ( SELECT DISTINCT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] ) AS [t]"); } public override async Task Cast_result_operator_on_subquery_is_properly_lifted_to_a_convert(bool async) { await base.Cast_result_operator_on_subquery_is_properly_lifted_to_a_convert(async); AssertSql( @"SELECT [f].[Eradicated] FROM [Factions] AS [f]"); } public override async Task Comparing_two_collection_navigations_composite_key(bool async) { await base.Comparing_two_collection_navigations_composite_key(async); AssertSql( @"SELECT [g].[Nickname] AS [Nickname1], [g0].[Nickname] AS [Nickname2] FROM [Gears] AS [g] CROSS JOIN [Gears] AS [g0] WHERE ([g].[Nickname] = [g0].[Nickname]) AND ([g].[SquadId] = [g0].[SquadId]) ORDER BY [g].[Nickname]"); } public override async Task Comparing_two_collection_navigations_inheritance(bool async) { await base.Comparing_two_collection_navigations_inheritance(async); AssertSql( @"SELECT [f].[Name], [t].[Nickname] FROM [Factions] AS [f] CROSS JOIN ( SELECT [g].[Nickname], [g].[SquadId], [g].[HasSoulPatch] FROM [Gears] AS [g] WHERE [g].[Discriminator] = N'Officer' ) AS [t] LEFT JOIN ( SELECT [l].[Name], [l].[DefeatedByNickname], [l].[DefeatedBySquadId] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t0] ON [f].[CommanderName] = [t0].[Name] LEFT JOIN [Gears] AS [g0] ON ([t0].[DefeatedByNickname] = [g0].[Nickname]) AND ([t0].[DefeatedBySquadId] = [g0].[SquadId]) WHERE ([t].[HasSoulPatch] = CAST(1 AS bit)) AND (([g0].[Nickname] = [t].[Nickname]) AND ([g0].[SquadId] = [t].[SquadId]))"); } public override async Task Comparing_entities_using_Equals_inheritance(bool async) { await base.Comparing_entities_using_Equals_inheritance(async); AssertSql( @"SELECT [g].[Nickname] AS [Nickname1], [t].[Nickname] AS [Nickname2] FROM [Gears] AS [g] CROSS JOIN ( SELECT [g0].[Nickname], [g0].[SquadId] FROM [Gears] AS [g0] WHERE [g0].[Discriminator] = N'Officer' ) AS [t] WHERE ([g].[Nickname] = [t].[Nickname]) AND ([g].[SquadId] = [t].[SquadId]) ORDER BY [g].[Nickname], [t].[Nickname]"); } public override async Task Contains_on_nullable_array_produces_correct_sql(bool async) { await base.Contains_on_nullable_array_produces_correct_sql(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] LEFT JOIN [Cities] AS [c] ON [g].[AssignedCityName] = [c].[Name] WHERE ([g].[SquadId] < 2) AND (([c].[Name] = N'Ephyra') OR [c].[Name] IS NULL)"); } public override async Task Optional_navigation_with_collection_composite_key(bool async) { await base.Optional_navigation_with_collection_composite_key(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE ([g].[Discriminator] = N'Officer') AND (( SELECT COUNT(*) FROM [Gears] AS [g0] WHERE (([g].[Nickname] IS NOT NULL AND [g].[SquadId] IS NOT NULL) AND (([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId]))) AND ([g0].[Nickname] = N'Dom')) > 0)"); } public override async Task Select_null_conditional_with_inheritance(bool async) { await base.Select_null_conditional_with_inheritance(async); AssertSql( @"SELECT CASE WHEN [f].[CommanderName] IS NOT NULL THEN [f].[CommanderName] ELSE NULL END FROM [Factions] AS [f]"); } public override async Task Select_null_conditional_with_inheritance_negative(bool async) { await base.Select_null_conditional_with_inheritance_negative(async); AssertSql( @"SELECT CASE WHEN [f].[CommanderName] IS NOT NULL THEN [f].[Eradicated] ELSE NULL END FROM [Factions] AS [f]"); } public override async Task Project_collection_navigation_with_inheritance1(bool async) { await base.Project_collection_navigation_with_inheritance1(async); AssertSql( @"SELECT [f].[Id], [t].[Name], [f0].[Id], [l0].[Name], [l0].[Discriminator], [l0].[LocustHordeId], [l0].[ThreatLevel], [l0].[ThreatLevelByte], [l0].[ThreatLevelNullableByte], [l0].[DefeatedByNickname], [l0].[DefeatedBySquadId], [l0].[HighCommandId] FROM [Factions] AS [f] LEFT JOIN ( SELECT [l].[Name] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name] LEFT JOIN [Factions] AS [f0] ON [t].[Name] = [f0].[CommanderName] LEFT JOIN [LocustLeaders] AS [l0] ON [f0].[Id] = [l0].[LocustHordeId] ORDER BY [f].[Id], [t].[Name], [f0].[Id]"); } public override async Task Project_collection_navigation_with_inheritance2(bool async) { await base.Project_collection_navigation_with_inheritance2(async); AssertSql( @"SELECT [f].[Id], [t].[Name], [g].[Nickname], [g].[SquadId], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Factions] AS [f] LEFT JOIN ( SELECT [l].[Name], [l].[DefeatedByNickname], [l].[DefeatedBySquadId] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name] LEFT JOIN [Gears] AS [g] ON ([t].[DefeatedByNickname] = [g].[Nickname]) AND ([t].[DefeatedBySquadId] = [g].[SquadId]) LEFT JOIN [Gears] AS [g0] ON (([g].[Nickname] = [g0].[LeaderNickname]) OR ([g].[Nickname] IS NULL AND [g0].[LeaderNickname] IS NULL)) AND ([g].[SquadId] = [g0].[LeaderSquadId]) ORDER BY [f].[Id], [t].[Name], [g].[Nickname], [g].[SquadId], [g0].[Nickname]"); } public override async Task Project_collection_navigation_with_inheritance3(bool async) { await base.Project_collection_navigation_with_inheritance3(async); AssertSql( @"SELECT [f].[Id], [t].[Name], [g].[Nickname], [g].[SquadId], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Factions] AS [f] LEFT JOIN ( SELECT [l].[Name], [l].[DefeatedByNickname], [l].[DefeatedBySquadId] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name] LEFT JOIN [Gears] AS [g] ON ([t].[DefeatedByNickname] = [g].[Nickname]) AND ([t].[DefeatedBySquadId] = [g].[SquadId]) LEFT JOIN [Gears] AS [g0] ON (([g].[Nickname] = [g0].[LeaderNickname]) OR ([g].[Nickname] IS NULL AND [g0].[LeaderNickname] IS NULL)) AND ([g].[SquadId] = [g0].[LeaderSquadId]) ORDER BY [f].[Id], [t].[Name], [g].[Nickname], [g].[SquadId], [g0].[Nickname]"); } public override async Task Include_reference_on_derived_type_using_string(bool async) { await base.Include_reference_on_derived_type_using_string(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [LocustLeaders] AS [l] LEFT JOIN [Gears] AS [g] ON ([l].[DefeatedByNickname] = [g].[Nickname]) AND ([l].[DefeatedBySquadId] = [g].[SquadId])"); } public override async Task Include_reference_on_derived_type_using_string_nested1(bool async) { await base.Include_reference_on_derived_type_using_string_nested1(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [LocustLeaders] AS [l] LEFT JOIN [Gears] AS [g] ON ([l].[DefeatedByNickname] = [g].[Nickname]) AND ([l].[DefeatedBySquadId] = [g].[SquadId]) LEFT JOIN [Squads] AS [s] ON [g].[SquadId] = [s].[Id]"); } public override async Task Include_reference_on_derived_type_using_string_nested2(bool async) { await base.Include_reference_on_derived_type_using_string_nested2(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank], [t].[Name], [t].[Location], [t].[Nation] FROM [LocustLeaders] AS [l] LEFT JOIN [Gears] AS [g] ON ([l].[DefeatedByNickname] = [g].[Nickname]) AND ([l].[DefeatedBySquadId] = [g].[SquadId]) LEFT JOIN ( SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank], [c].[Name], [c].[Location], [c].[Nation] FROM [Gears] AS [g0] INNER JOIN [Cities] AS [c] ON [g0].[CityOfBirthName] = [c].[Name] ) AS [t] ON (([g].[Nickname] = [t].[LeaderNickname]) OR ([g].[Nickname] IS NULL AND [t].[LeaderNickname] IS NULL)) AND ([g].[SquadId] = [t].[LeaderSquadId]) ORDER BY [l].[Name], [g].[Nickname], [g].[SquadId], [t].[Nickname], [t].[SquadId]"); } public override async Task Include_reference_on_derived_type_using_lambda(bool async) { await base.Include_reference_on_derived_type_using_lambda(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [LocustLeaders] AS [l] LEFT JOIN [Gears] AS [g] ON ([l].[DefeatedByNickname] = [g].[Nickname]) AND ([l].[DefeatedBySquadId] = [g].[SquadId])"); } public override async Task Include_reference_on_derived_type_using_lambda_with_soft_cast(bool async) { await base.Include_reference_on_derived_type_using_lambda_with_soft_cast(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [LocustLeaders] AS [l] LEFT JOIN [Gears] AS [g] ON ([l].[DefeatedByNickname] = [g].[Nickname]) AND ([l].[DefeatedBySquadId] = [g].[SquadId])"); } public override async Task Include_reference_on_derived_type_using_lambda_with_tracking(bool async) { await base.Include_reference_on_derived_type_using_lambda_with_tracking(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [LocustLeaders] AS [l] LEFT JOIN [Gears] AS [g] ON ([l].[DefeatedByNickname] = [g].[Nickname]) AND ([l].[DefeatedBySquadId] = [g].[SquadId])"); } public override async Task Include_collection_on_derived_type_using_string(bool async) { await base.Include_collection_on_derived_type_using_string(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId]) ORDER BY [g].[Nickname], [g].[SquadId], [g0].[Nickname]"); } public override async Task Include_collection_on_derived_type_using_lambda(bool async) { await base.Include_collection_on_derived_type_using_lambda(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId]) ORDER BY [g].[Nickname], [g].[SquadId], [g0].[Nickname]"); } public override async Task Include_collection_on_derived_type_using_lambda_with_soft_cast(bool async) { await base.Include_collection_on_derived_type_using_lambda_with_soft_cast(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId]) ORDER BY [g].[Nickname], [g].[SquadId], [g0].[Nickname]"); } public override async Task Include_base_navigation_on_derived_entity(bool async) { await base.Include_base_navigation_on_derived_entity(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] ORDER BY [g].[Nickname], [g].[SquadId], [t].[Id]"); } public override async Task ThenInclude_collection_on_derived_after_base_reference(bool async) { await base.ThenInclude_collection_on_derived_after_base_reference(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] ORDER BY [t].[Id], [g].[Nickname], [g].[SquadId]"); } public override async Task ThenInclude_collection_on_derived_after_derived_reference(bool async) { await base.ThenInclude_collection_on_derived_after_derived_reference(async); AssertSql( @"SELECT [f].[Id], [f].[CapitalName], [f].[Discriminator], [f].[Name], [f].[ServerAddress], [f].[CommanderName], [f].[Eradicated], [t].[Name], [t].[Discriminator], [t].[LocustHordeId], [t].[ThreatLevel], [t].[ThreatLevelByte], [t].[ThreatLevelNullableByte], [t].[DefeatedByNickname], [t].[DefeatedBySquadId], [t].[HighCommandId], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Factions] AS [f] LEFT JOIN ( SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name] LEFT JOIN [Gears] AS [g] ON ([t].[DefeatedByNickname] = [g].[Nickname]) AND ([t].[DefeatedBySquadId] = [g].[SquadId]) LEFT JOIN [Gears] AS [g0] ON (([g].[Nickname] = [g0].[LeaderNickname]) OR ([g].[Nickname] IS NULL AND [g0].[LeaderNickname] IS NULL)) AND ([g].[SquadId] = [g0].[LeaderSquadId]) ORDER BY [f].[Id], [t].[Name], [g].[Nickname], [g].[SquadId], [g0].[Nickname]"); } public override async Task ThenInclude_collection_on_derived_after_derived_collection(bool async) { await base.ThenInclude_collection_on_derived_after_derived_collection(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank], [t].[Nickname0], [t].[SquadId0], [t].[AssignedCityName0], [t].[CityOfBirthName0], [t].[Discriminator0], [t].[FullName0], [t].[HasSoulPatch0], [t].[LeaderNickname0], [t].[LeaderSquadId0], [t].[Rank0] FROM [Gears] AS [g] LEFT JOIN ( SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank], [g1].[Nickname] AS [Nickname0], [g1].[SquadId] AS [SquadId0], [g1].[AssignedCityName] AS [AssignedCityName0], [g1].[CityOfBirthName] AS [CityOfBirthName0], [g1].[Discriminator] AS [Discriminator0], [g1].[FullName] AS [FullName0], [g1].[HasSoulPatch] AS [HasSoulPatch0], [g1].[LeaderNickname] AS [LeaderNickname0], [g1].[LeaderSquadId] AS [LeaderSquadId0], [g1].[Rank] AS [Rank0] FROM [Gears] AS [g0] LEFT JOIN [Gears] AS [g1] ON ([g0].[Nickname] = [g1].[LeaderNickname]) AND ([g0].[SquadId] = [g1].[LeaderSquadId]) ) AS [t] ON ([g].[Nickname] = [t].[LeaderNickname]) AND ([g].[SquadId] = [t].[LeaderSquadId]) ORDER BY [g].[Nickname], [g].[SquadId], [t].[Nickname], [t].[SquadId], [t].[Nickname0]"); } public override async Task ThenInclude_reference_on_derived_after_derived_collection(bool async) { await base.ThenInclude_reference_on_derived_after_derived_collection(async); AssertSql( @"SELECT [f].[Id], [f].[CapitalName], [f].[Discriminator], [f].[Name], [f].[ServerAddress], [f].[CommanderName], [f].[Eradicated], [t].[Name], [t].[Discriminator], [t].[LocustHordeId], [t].[ThreatLevel], [t].[ThreatLevelByte], [t].[ThreatLevelNullableByte], [t].[DefeatedByNickname], [t].[DefeatedBySquadId], [t].[HighCommandId], [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator0], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank] FROM [Factions] AS [f] LEFT JOIN ( SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator] AS [Discriminator0], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [LocustLeaders] AS [l] LEFT JOIN [Gears] AS [g] ON ([l].[DefeatedByNickname] = [g].[Nickname]) AND ([l].[DefeatedBySquadId] = [g].[SquadId]) ) AS [t] ON [f].[Id] = [t].[LocustHordeId] ORDER BY [f].[Id], [t].[Name], [t].[Nickname]"); } public override async Task Multiple_derived_included_on_one_method(bool async) { await base.Multiple_derived_included_on_one_method(async); AssertSql( @"SELECT [f].[Id], [f].[CapitalName], [f].[Discriminator], [f].[Name], [f].[ServerAddress], [f].[CommanderName], [f].[Eradicated], [t].[Name], [t].[Discriminator], [t].[LocustHordeId], [t].[ThreatLevel], [t].[ThreatLevelByte], [t].[ThreatLevelNullableByte], [t].[DefeatedByNickname], [t].[DefeatedBySquadId], [t].[HighCommandId], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Factions] AS [f] LEFT JOIN ( SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name] LEFT JOIN [Gears] AS [g] ON ([t].[DefeatedByNickname] = [g].[Nickname]) AND ([t].[DefeatedBySquadId] = [g].[SquadId]) LEFT JOIN [Gears] AS [g0] ON (([g].[Nickname] = [g0].[LeaderNickname]) OR ([g].[Nickname] IS NULL AND [g0].[LeaderNickname] IS NULL)) AND ([g].[SquadId] = [g0].[LeaderSquadId]) ORDER BY [f].[Id], [t].[Name], [g].[Nickname], [g].[SquadId], [g0].[Nickname]"); } public override async Task Include_on_derived_multi_level(bool async) { await base.Include_on_derived_multi_level(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank], [t].[Id], [t].[Banner], [t].[Banner5], [t].[InternalNumber], [t].[Name], [t].[SquadId0], [t].[MissionId] FROM [Gears] AS [g] LEFT JOIN ( SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank], [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name], [s0].[SquadId] AS [SquadId0], [s0].[MissionId] FROM [Gears] AS [g0] INNER JOIN [Squads] AS [s] ON [g0].[SquadId] = [s].[Id] LEFT JOIN [SquadMissions] AS [s0] ON [s].[Id] = [s0].[SquadId] ) AS [t] ON ([g].[Nickname] = [t].[LeaderNickname]) AND ([g].[SquadId] = [t].[LeaderSquadId]) ORDER BY [g].[Nickname], [g].[SquadId], [t].[Nickname], [t].[SquadId], [t].[Id], [t].[SquadId0]"); } public override async Task Projecting_nullable_bool_in_conditional_works(bool async) { await base.Projecting_nullable_bool_in_conditional_works(async); AssertSql( @"SELECT CASE WHEN [g].[Nickname] IS NOT NULL AND [g].[SquadId] IS NOT NULL THEN [g].[HasSoulPatch] ELSE CAST(0 AS bit) END AS [Prop] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId])"); } public override async Task Enum_ToString_is_client_eval(bool async) { await base.Enum_ToString_is_client_eval(async); AssertSql( @"SELECT [g].[Rank] FROM [Gears] AS [g] ORDER BY [g].[SquadId], [g].[Nickname]"); } public override async Task ToString_boolean_property_non_nullable(bool async) { await base.ToString_boolean_property_non_nullable(async); AssertSql( @"SELECT CASE WHEN [w].[IsAutomatic] = CAST(0 AS bit) THEN N'False' ELSE N'True' END FROM [Weapons] AS [w]"); } public override async Task ToString_boolean_property_nullable(bool async) { await base.ToString_boolean_property_nullable(async); AssertSql( @"SELECT CASE WHEN [f].[Eradicated] = CAST(0 AS bit) THEN N'False' WHEN [f].[Eradicated] = CAST(1 AS bit) THEN N'True' ELSE NULL END FROM [Factions] AS [f]"); } public override async Task Correlated_collections_naked_navigation_with_ToList(bool async) { await base.Correlated_collections_naked_navigation_with_ToList(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] WHERE [g].[Nickname] <> N'Marcus' ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collections_naked_navigation_with_ToList_followed_by_projecting_count(bool async) { await base.Correlated_collections_naked_navigation_with_ToList_followed_by_projecting_count(async); AssertSql( @"SELECT ( SELECT COUNT(*) FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName]) FROM [Gears] AS [g] WHERE [g].[Nickname] <> N'Marcus' ORDER BY [g].[Nickname]"); } public override async Task Correlated_collections_naked_navigation_with_ToArray(bool async) { await base.Correlated_collections_naked_navigation_with_ToArray(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] WHERE [g].[Nickname] <> N'Marcus' ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collections_basic_projection(bool async) { await base.Correlated_collections_basic_projection(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Id], [t].[AmmunitionType], [t].[IsAutomatic], [t].[Name], [t].[OwnerFullName], [t].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[IsAutomatic] = CAST(1 AS bit)) OR (([w].[Name] <> N'foo') OR [w].[Name] IS NULL) ) AS [t] ON [g].[FullName] = [t].[OwnerFullName] WHERE [g].[Nickname] <> N'Marcus' ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collections_basic_projection_explicit_to_list(bool async) { await base.Correlated_collections_basic_projection_explicit_to_list(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Id], [t].[AmmunitionType], [t].[IsAutomatic], [t].[Name], [t].[OwnerFullName], [t].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[IsAutomatic] = CAST(1 AS bit)) OR (([w].[Name] <> N'foo') OR [w].[Name] IS NULL) ) AS [t] ON [g].[FullName] = [t].[OwnerFullName] WHERE [g].[Nickname] <> N'Marcus' ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collections_basic_projection_explicit_to_array(bool async) { await base.Correlated_collections_basic_projection_explicit_to_array(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Id], [t].[AmmunitionType], [t].[IsAutomatic], [t].[Name], [t].[OwnerFullName], [t].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[IsAutomatic] = CAST(1 AS bit)) OR (([w].[Name] <> N'foo') OR [w].[Name] IS NULL) ) AS [t] ON [g].[FullName] = [t].[OwnerFullName] WHERE [g].[Nickname] <> N'Marcus' ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collections_basic_projection_ordered(bool async) { await base.Correlated_collections_basic_projection_ordered(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Id], [t].[AmmunitionType], [t].[IsAutomatic], [t].[Name], [t].[OwnerFullName], [t].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[IsAutomatic] = CAST(1 AS bit)) OR (([w].[Name] <> N'foo') OR [w].[Name] IS NULL) ) AS [t] ON [g].[FullName] = [t].[OwnerFullName] WHERE [g].[Nickname] <> N'Marcus' ORDER BY [g].[Nickname], [g].[SquadId], [t].[Name] DESC"); } public override async Task Correlated_collections_basic_projection_composite_key(bool async) { await base.Correlated_collections_basic_projection_composite_key(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Nickname], [t].[FullName], [t].[SquadId] FROM [Gears] AS [g] LEFT JOIN ( SELECT [g0].[Nickname], [g0].[FullName], [g0].[SquadId], [g0].[LeaderNickname], [g0].[LeaderSquadId] FROM [Gears] AS [g0] WHERE [g0].[HasSoulPatch] = CAST(0 AS bit) ) AS [t] ON ([g].[Nickname] = [t].[LeaderNickname]) AND ([g].[SquadId] = [t].[LeaderSquadId]) WHERE ([g].[Discriminator] = N'Officer') AND ([g].[Nickname] <> N'Foo') ORDER BY [g].[Nickname], [g].[SquadId], [t].[Nickname]"); } public override async Task Correlated_collections_basic_projecting_single_property(bool async) { await base.Correlated_collections_basic_projecting_single_property(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Name], [t].[Id] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w].[Name], [w].[Id], [w].[OwnerFullName] FROM [Weapons] AS [w] WHERE ([w].[IsAutomatic] = CAST(1 AS bit)) OR (([w].[Name] <> N'foo') OR [w].[Name] IS NULL) ) AS [t] ON [g].[FullName] = [t].[OwnerFullName] WHERE [g].[Nickname] <> N'Marcus' ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collections_basic_projecting_constant(bool async) { await base.Correlated_collections_basic_projecting_constant(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[c], [t].[Id] FROM [Gears] AS [g] LEFT JOIN ( SELECT N'BFG' AS [c], [w].[Id], [w].[OwnerFullName] FROM [Weapons] AS [w] WHERE ([w].[IsAutomatic] = CAST(1 AS bit)) OR (([w].[Name] <> N'foo') OR [w].[Name] IS NULL) ) AS [t] ON [g].[FullName] = [t].[OwnerFullName] WHERE [g].[Nickname] <> N'Marcus' ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collections_basic_projecting_constant_bool(bool async) { await base.Correlated_collections_basic_projecting_constant_bool(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[c], [t].[Id] FROM [Gears] AS [g] LEFT JOIN ( SELECT CAST(1 AS bit) AS [c], [w].[Id], [w].[OwnerFullName] FROM [Weapons] AS [w] WHERE ([w].[IsAutomatic] = CAST(1 AS bit)) OR (([w].[Name] <> N'foo') OR [w].[Name] IS NULL) ) AS [t] ON [g].[FullName] = [t].[OwnerFullName] WHERE [g].[Nickname] <> N'Marcus' ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collections_projection_of_collection_thru_navigation(bool async) { await base.Correlated_collections_projection_of_collection_thru_navigation(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [s].[Id], [t].[SquadId], [t].[MissionId] FROM [Gears] AS [g] INNER JOIN [Squads] AS [s] ON [g].[SquadId] = [s].[Id] LEFT JOIN ( SELECT [s0].[SquadId], [s0].[MissionId] FROM [SquadMissions] AS [s0] WHERE [s0].[MissionId] <> 17 ) AS [t] ON [s].[Id] = [t].[SquadId] WHERE [g].[Nickname] <> N'Marcus' ORDER BY [g].[FullName], [g].[Nickname], [g].[SquadId], [s].[Id], [t].[SquadId]"); } public override async Task Correlated_collections_project_anonymous_collection_result(bool async) { await base.Correlated_collections_project_anonymous_collection_result(async); AssertSql( @"SELECT [s].[Name], [s].[Id], [g].[FullName], [g].[Rank], [g].[Nickname], [g].[SquadId] FROM [Squads] AS [s] LEFT JOIN [Gears] AS [g] ON [s].[Id] = [g].[SquadId] WHERE [s].[Id] < 20 ORDER BY [s].[Id], [g].[Nickname]"); } public override async Task Correlated_collections_nested(bool async) { await base.Correlated_collections_nested(async); AssertSql( @"SELECT [s].[Id], [t0].[SquadId], [t0].[MissionId], [t0].[Id], [t0].[SquadId0], [t0].[MissionId0] FROM [Squads] AS [s] LEFT JOIN ( SELECT [s0].[SquadId], [s0].[MissionId], [m].[Id], [t].[SquadId] AS [SquadId0], [t].[MissionId] AS [MissionId0] FROM [SquadMissions] AS [s0] INNER JOIN [Missions] AS [m] ON [s0].[MissionId] = [m].[Id] LEFT JOIN ( SELECT [s1].[SquadId], [s1].[MissionId] FROM [SquadMissions] AS [s1] WHERE [s1].[SquadId] < 7 ) AS [t] ON [m].[Id] = [t].[MissionId] WHERE [s0].[MissionId] < 42 ) AS [t0] ON [s].[Id] = [t0].[SquadId] ORDER BY [s].[Id], [t0].[SquadId], [t0].[MissionId], [t0].[Id], [t0].[SquadId0]"); } public override async Task Correlated_collections_nested_mixed_streaming_with_buffer1(bool async) { await base.Correlated_collections_nested_mixed_streaming_with_buffer1(async); AssertSql( @"SELECT [s].[Id], [t0].[SquadId], [t0].[MissionId], [t0].[Id], [t0].[SquadId0], [t0].[MissionId0] FROM [Squads] AS [s] LEFT JOIN ( SELECT [s0].[SquadId], [s0].[MissionId], [m].[Id], [t].[SquadId] AS [SquadId0], [t].[MissionId] AS [MissionId0] FROM [SquadMissions] AS [s0] INNER JOIN [Missions] AS [m] ON [s0].[MissionId] = [m].[Id] LEFT JOIN ( SELECT [s1].[SquadId], [s1].[MissionId] FROM [SquadMissions] AS [s1] WHERE [s1].[SquadId] < 2 ) AS [t] ON [m].[Id] = [t].[MissionId] WHERE [s0].[MissionId] < 3 ) AS [t0] ON [s].[Id] = [t0].[SquadId] ORDER BY [s].[Id], [t0].[SquadId], [t0].[MissionId], [t0].[Id], [t0].[SquadId0]"); } public override async Task Correlated_collections_nested_mixed_streaming_with_buffer2(bool async) { await base.Correlated_collections_nested_mixed_streaming_with_buffer2(async); AssertSql( @"SELECT [s].[Id], [t0].[SquadId], [t0].[MissionId], [t0].[Id], [t0].[SquadId0], [t0].[MissionId0] FROM [Squads] AS [s] LEFT JOIN ( SELECT [s0].[SquadId], [s0].[MissionId], [m].[Id], [t].[SquadId] AS [SquadId0], [t].[MissionId] AS [MissionId0] FROM [SquadMissions] AS [s0] INNER JOIN [Missions] AS [m] ON [s0].[MissionId] = [m].[Id] LEFT JOIN ( SELECT [s1].[SquadId], [s1].[MissionId] FROM [SquadMissions] AS [s1] WHERE [s1].[SquadId] < 7 ) AS [t] ON [m].[Id] = [t].[MissionId] WHERE [s0].[MissionId] < 42 ) AS [t0] ON [s].[Id] = [t0].[SquadId] ORDER BY [s].[Id], [t0].[SquadId], [t0].[MissionId], [t0].[Id], [t0].[SquadId0]"); } public override async Task Correlated_collections_nested_with_custom_ordering(bool async) { await base.Correlated_collections_nested_with_custom_ordering(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t0].[FullName], [t0].[Nickname], [t0].[SquadId], [t0].[Id], [t0].[AmmunitionType], [t0].[IsAutomatic], [t0].[Name], [t0].[OwnerFullName], [t0].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN ( SELECT [g0].[FullName], [g0].[Nickname], [g0].[SquadId], [t].[Id], [t].[AmmunitionType], [t].[IsAutomatic], [t].[Name], [t].[OwnerFullName], [t].[SynergyWithId], [g0].[Rank], [g0].[LeaderNickname], [g0].[LeaderSquadId] FROM [Gears] AS [g0] LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[Name] <> N'Bar') OR [w].[Name] IS NULL ) AS [t] ON [g0].[FullName] = [t].[OwnerFullName] WHERE [g0].[FullName] <> N'Foo' ) AS [t0] ON ([g].[Nickname] = [t0].[LeaderNickname]) AND ([g].[SquadId] = [t0].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[HasSoulPatch] DESC, [g].[Nickname], [g].[SquadId], [t0].[Rank], [t0].[Nickname], [t0].[SquadId], [t0].[IsAutomatic]"); } public override async Task Correlated_collections_same_collection_projected_multiple_times(bool async) { await base.Correlated_collections_same_collection_projected_multiple_times(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t].[Id], [t].[AmmunitionType], [t].[IsAutomatic], [t].[Name], [t].[OwnerFullName], [t].[SynergyWithId], [t0].[Id], [t0].[AmmunitionType], [t0].[IsAutomatic], [t0].[Name], [t0].[OwnerFullName], [t0].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [w].[IsAutomatic] = CAST(1 AS bit) ) AS [t] ON [g].[FullName] = [t].[OwnerFullName] LEFT JOIN ( SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w0] WHERE [w0].[IsAutomatic] = CAST(1 AS bit) ) AS [t0] ON [g].[FullName] = [t0].[OwnerFullName] ORDER BY [g].[Nickname], [g].[SquadId], [t].[Id]"); } public override async Task Correlated_collections_similar_collection_projected_multiple_times(bool async) { await base.Correlated_collections_similar_collection_projected_multiple_times(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t].[Id], [t].[AmmunitionType], [t].[IsAutomatic], [t].[Name], [t].[OwnerFullName], [t].[SynergyWithId], [t0].[Id], [t0].[AmmunitionType], [t0].[IsAutomatic], [t0].[Name], [t0].[OwnerFullName], [t0].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [w].[IsAutomatic] = CAST(1 AS bit) ) AS [t] ON [g].[FullName] = [t].[OwnerFullName] LEFT JOIN ( SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w0] WHERE [w0].[IsAutomatic] = CAST(0 AS bit) ) AS [t0] ON [g].[FullName] = [t0].[OwnerFullName] ORDER BY [g].[Rank], [g].[Nickname], [g].[SquadId], [t].[OwnerFullName], [t].[Id], [t0].[IsAutomatic]"); } public override async Task Correlated_collections_different_collections_projected(bool async) { await base.Correlated_collections_different_collections_projected(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Name], [t].[IsAutomatic], [t].[Id], [t0].[Nickname], [t0].[Rank], [t0].[SquadId] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w].[Name], [w].[IsAutomatic], [w].[Id], [w].[OwnerFullName] FROM [Weapons] AS [w] WHERE [w].[IsAutomatic] = CAST(1 AS bit) ) AS [t] ON [g].[FullName] = [t].[OwnerFullName] LEFT JOIN ( SELECT [g0].[Nickname], [g0].[Rank], [g0].[SquadId], [g0].[FullName], [g0].[LeaderNickname], [g0].[LeaderSquadId] FROM [Gears] AS [g0] ) AS [t0] ON ([g].[Nickname] = [t0].[LeaderNickname]) AND ([g].[SquadId] = [t0].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[FullName], [g].[Nickname], [g].[SquadId], [t].[Id], [t0].[FullName], [t0].[Nickname]"); } public override async Task Multiple_orderby_with_navigation_expansion_on_one_of_the_order_bys(bool async) { await base.Multiple_orderby_with_navigation_expansion_on_one_of_the_order_bys(async); AssertSql( @"SELECT [g].[FullName] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) WHERE ([g].[Discriminator] = N'Officer') AND EXISTS ( SELECT 1 FROM [Gears] AS [g0] WHERE ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId])) ORDER BY [g].[HasSoulPatch] DESC, [t].[Note]"); } public override async Task Multiple_orderby_with_navigation_expansion_on_one_of_the_order_bys_inside_subquery(bool async) { await base.Multiple_orderby_with_navigation_expansion_on_one_of_the_order_bys_inside_subquery(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t].[Id], [g1].[Nickname], [g1].[SquadId], [t0].[Id], [t0].[AmmunitionType], [t0].[IsAutomatic], [t0].[Name], [t0].[OwnerFullName], [t0].[SynergyWithId], [t0].[Nickname], [t0].[SquadId] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) LEFT JOIN [Gears] AS [g1] ON ([t].[GearNickName] = [g1].[Nickname]) AND ([t].[GearSquadId] = [g1].[SquadId]) LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId], [g2].[Nickname], [g2].[SquadId] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g2] ON [w].[OwnerFullName] = [g2].[FullName] ) AS [t0] ON [g1].[FullName] = [t0].[OwnerFullName] WHERE ([g].[Discriminator] = N'Officer') AND EXISTS ( SELECT 1 FROM [Gears] AS [g0] WHERE ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId])) ORDER BY [g].[HasSoulPatch] DESC, [t].[Note], [g].[Nickname], [g].[SquadId], [t].[Id], [g1].[Nickname], [g1].[SquadId], [t0].[IsAutomatic], [t0].[Nickname] DESC, [t0].[Id]"); } public override async Task Multiple_orderby_with_navigation_expansion_on_one_of_the_order_bys_inside_subquery_duplicated_orderings( bool async) { await base.Multiple_orderby_with_navigation_expansion_on_one_of_the_order_bys_inside_subquery_duplicated_orderings(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t].[Id], [g1].[Nickname], [g1].[SquadId], [t0].[Id], [t0].[AmmunitionType], [t0].[IsAutomatic], [t0].[Name], [t0].[OwnerFullName], [t0].[SynergyWithId], [t0].[Nickname], [t0].[SquadId] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) LEFT JOIN [Gears] AS [g1] ON ([t].[GearNickName] = [g1].[Nickname]) AND ([t].[GearSquadId] = [g1].[SquadId]) LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId], [g2].[Nickname], [g2].[SquadId] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g2] ON [w].[OwnerFullName] = [g2].[FullName] ) AS [t0] ON [g1].[FullName] = [t0].[OwnerFullName] WHERE ([g].[Discriminator] = N'Officer') AND EXISTS ( SELECT 1 FROM [Gears] AS [g0] WHERE ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId])) ORDER BY [g].[HasSoulPatch] DESC, [t].[Note], [g].[Nickname], [g].[SquadId], [t].[Id], [g1].[Nickname], [g1].[SquadId], [t0].[IsAutomatic], [t0].[Nickname] DESC, [t0].[Id]"); } public override async Task Multiple_orderby_with_navigation_expansion_on_one_of_the_order_bys_inside_subquery_complex_orderings( bool async) { await base.Multiple_orderby_with_navigation_expansion_on_one_of_the_order_bys_inside_subquery_complex_orderings(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t].[Id], [g1].[Nickname], [g1].[SquadId], [t0].[Id], [t0].[AmmunitionType], [t0].[IsAutomatic], [t0].[Name], [t0].[OwnerFullName], [t0].[SynergyWithId], [t0].[Nickname], [t0].[SquadId] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) LEFT JOIN [Gears] AS [g1] ON ([t].[GearNickName] = [g1].[Nickname]) AND ([t].[GearSquadId] = [g1].[SquadId]) LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId], [g2].[Nickname], [g2].[SquadId], ( SELECT COUNT(*) FROM [Weapons] AS [w0] WHERE [g2].[FullName] IS NOT NULL AND ([g2].[FullName] = [w0].[OwnerFullName])) AS [c] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g2] ON [w].[OwnerFullName] = [g2].[FullName] ) AS [t0] ON [g1].[FullName] = [t0].[OwnerFullName] WHERE ([g].[Discriminator] = N'Officer') AND EXISTS ( SELECT 1 FROM [Gears] AS [g0] WHERE ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId])) ORDER BY [g].[HasSoulPatch] DESC, [t].[Note], [g].[Nickname], [g].[SquadId], [t].[Id], [g1].[Nickname], [g1].[SquadId], [t0].[Id] DESC, [t0].[c], [t0].[Nickname]"); } public override async Task Correlated_collections_multiple_nested_complex_collections(bool async) { await base.Correlated_collections_multiple_nested_complex_collections(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t].[Id], [g1].[Nickname], [g1].[SquadId], [t1].[FullName], [t1].[Nickname], [t1].[SquadId], [t1].[Id], [t1].[Nickname0], [t1].[SquadId0], [t1].[Id0], [t1].[Name], [t1].[IsAutomatic], [t1].[Id1], [t1].[Nickname00], [t1].[HasSoulPatch], [t1].[SquadId00], [t3].[Id], [t3].[AmmunitionType], [t3].[IsAutomatic], [t3].[Name], [t3].[OwnerFullName], [t3].[SynergyWithId], [t3].[Nickname], [t3].[SquadId] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) LEFT JOIN [Gears] AS [g1] ON ([t].[GearNickName] = [g1].[Nickname]) AND ([t].[GearSquadId] = [g1].[SquadId]) LEFT JOIN ( SELECT [g2].[FullName], [g2].[Nickname], [g2].[SquadId], [t0].[Id], [t0].[Nickname] AS [Nickname0], [t0].[SquadId] AS [SquadId0], [t0].[Id0], [t0].[Name], [t0].[IsAutomatic], [t0].[Id1], [t0].[Nickname0] AS [Nickname00], [t0].[HasSoulPatch], [t0].[SquadId0] AS [SquadId00], [g2].[Rank], [t0].[IsAutomatic0], [g2].[LeaderNickname], [g2].[LeaderSquadId] FROM [Gears] AS [g2] LEFT JOIN ( SELECT [w].[Id], [g3].[Nickname], [g3].[SquadId], [s].[Id] AS [Id0], [w0].[Name], [w0].[IsAutomatic], [w0].[Id] AS [Id1], [t2].[Nickname] AS [Nickname0], [t2].[HasSoulPatch], [t2].[SquadId] AS [SquadId0], [w].[IsAutomatic] AS [IsAutomatic0], [w].[OwnerFullName] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g3] ON [w].[OwnerFullName] = [g3].[FullName] LEFT JOIN [Squads] AS [s] ON [g3].[SquadId] = [s].[Id] LEFT JOIN [Weapons] AS [w0] ON [g3].[FullName] = [w0].[OwnerFullName] LEFT JOIN ( SELECT [g4].[Nickname], [g4].[HasSoulPatch], [g4].[SquadId] FROM [Gears] AS [g4] ) AS [t2] ON [s].[Id] = [t2].[SquadId] WHERE ([w].[Name] <> N'Bar') OR [w].[Name] IS NULL ) AS [t0] ON [g2].[FullName] = [t0].[OwnerFullName] WHERE [g2].[FullName] <> N'Foo' ) AS [t1] ON ([g].[Nickname] = [t1].[LeaderNickname]) AND ([g].[SquadId] = [t1].[LeaderSquadId]) LEFT JOIN ( SELECT [w1].[Id], [w1].[AmmunitionType], [w1].[IsAutomatic], [w1].[Name], [w1].[OwnerFullName], [w1].[SynergyWithId], [g5].[Nickname], [g5].[SquadId] FROM [Weapons] AS [w1] LEFT JOIN [Gears] AS [g5] ON [w1].[OwnerFullName] = [g5].[FullName] ) AS [t3] ON [g1].[FullName] = [t3].[OwnerFullName] WHERE ([g].[Discriminator] = N'Officer') AND EXISTS ( SELECT 1 FROM [Gears] AS [g0] WHERE ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId])) ORDER BY [g].[HasSoulPatch] DESC, [t].[Note], [g].[Nickname], [g].[SquadId], [t].[Id], [g1].[Nickname], [g1].[SquadId], [t1].[Rank], [t1].[Nickname], [t1].[SquadId], [t1].[IsAutomatic0], [t1].[Id], [t1].[Nickname0], [t1].[SquadId0], [t1].[Id0], [t1].[Id1], [t1].[Nickname00], [t1].[SquadId00], [t3].[IsAutomatic], [t3].[Nickname] DESC, [t3].[Id]"); } public override async Task Correlated_collections_inner_subquery_selector_references_outer_qsre(bool async) { await base.Correlated_collections_inner_subquery_selector_references_outer_qsre(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t].[ReportName], [t].[OfficerName], [t].[Nickname], [t].[SquadId] FROM [Gears] AS [g] OUTER APPLY ( SELECT [g0].[FullName] AS [ReportName], [g].[FullName] AS [OfficerName], [g0].[Nickname], [g0].[SquadId] FROM [Gears] AS [g0] WHERE ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId]) ) AS [t] WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[Nickname], [g].[SquadId], [t].[Nickname]"); } public override async Task Correlated_collections_inner_subquery_predicate_references_outer_qsre(bool async) { await base.Correlated_collections_inner_subquery_predicate_references_outer_qsre(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t].[ReportName], [t].[Nickname], [t].[SquadId] FROM [Gears] AS [g] OUTER APPLY ( SELECT [g0].[FullName] AS [ReportName], [g0].[Nickname], [g0].[SquadId] FROM [Gears] AS [g0] WHERE ([g].[FullName] <> N'Foo') AND (([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId])) ) AS [t] WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[Nickname], [g].[SquadId], [t].[Nickname]"); } public override async Task Correlated_collections_nested_inner_subquery_references_outer_qsre_one_level_up(bool async) { await base.Correlated_collections_nested_inner_subquery_references_outer_qsre_one_level_up(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t0].[FullName], [t0].[Nickname], [t0].[SquadId], [t0].[Name], [t0].[Nickname0], [t0].[Id] FROM [Gears] AS [g] LEFT JOIN ( SELECT [g0].[FullName], [g0].[Nickname], [g0].[SquadId], [t].[Name], [t].[Nickname] AS [Nickname0], [t].[Id], [g0].[LeaderNickname], [g0].[LeaderSquadId] FROM [Gears] AS [g0] OUTER APPLY ( SELECT [w].[Name], [g0].[Nickname], [w].[Id] FROM [Weapons] AS [w] WHERE (([w].[Name] <> N'Bar') OR [w].[Name] IS NULL) AND ([g0].[FullName] = [w].[OwnerFullName]) ) AS [t] WHERE [g0].[FullName] <> N'Foo' ) AS [t0] ON ([g].[Nickname] = [t0].[LeaderNickname]) AND ([g].[SquadId] = [t0].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[Nickname], [g].[SquadId], [t0].[Nickname], [t0].[SquadId]"); } public override async Task Correlated_collections_nested_inner_subquery_references_outer_qsre_two_levels_up(bool async) { await base.Correlated_collections_nested_inner_subquery_references_outer_qsre_two_levels_up(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t0].[FullName], [t0].[Nickname], [t0].[SquadId], [t0].[Name], [t0].[Nickname0], [t0].[Id] FROM [Gears] AS [g] OUTER APPLY ( SELECT [g0].[FullName], [g0].[Nickname], [g0].[SquadId], [t].[Name], [t].[Nickname] AS [Nickname0], [t].[Id] FROM [Gears] AS [g0] LEFT JOIN ( SELECT [w].[Name], [g].[Nickname], [w].[Id], [w].[OwnerFullName] FROM [Weapons] AS [w] WHERE ([w].[Name] <> N'Bar') OR [w].[Name] IS NULL ) AS [t] ON [g0].[FullName] = [t].[OwnerFullName] WHERE ([g0].[FullName] <> N'Foo') AND (([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId])) ) AS [t0] WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[Nickname], [g].[SquadId], [t0].[Nickname], [t0].[SquadId]"); } public override async Task Correlated_collections_on_select_many(bool async) { await base.Correlated_collections_on_select_many(async); AssertSql( @"SELECT [g].[Nickname], [s].[Name], [g].[SquadId], [s].[Id], [t].[Id], [t].[AmmunitionType], [t].[IsAutomatic], [t].[Name], [t].[OwnerFullName], [t].[SynergyWithId], [t0].[Nickname], [t0].[SquadId], [t0].[AssignedCityName], [t0].[CityOfBirthName], [t0].[Discriminator], [t0].[FullName], [t0].[HasSoulPatch], [t0].[LeaderNickname], [t0].[LeaderSquadId], [t0].[Rank] FROM [Gears] AS [g] CROSS JOIN [Squads] AS [s] LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[IsAutomatic] = CAST(1 AS bit)) OR (([w].[Name] <> N'foo') OR [w].[Name] IS NULL) ) AS [t] ON [g].[FullName] = [t].[OwnerFullName] LEFT JOIN ( SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g0] WHERE [g0].[HasSoulPatch] = CAST(0 AS bit) ) AS [t0] ON [s].[Id] = [t0].[SquadId] WHERE [g].[HasSoulPatch] = CAST(1 AS bit) ORDER BY [g].[Nickname], [s].[Id] DESC, [g].[SquadId], [t].[Id], [t0].[Nickname]"); } public override async Task Correlated_collections_with_Skip(bool async) { await base.Correlated_collections_with_Skip(async); AssertSql( @"SELECT [s].[Id] FROM [Squads] AS [s] ORDER BY [s].[Name]", // @"@_outer_Id='1' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE @_outer_Id = [g].[SquadId] ORDER BY [g].[Nickname] OFFSET 1 ROWS", // @"@_outer_Id='2' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE @_outer_Id = [g].[SquadId] ORDER BY [g].[Nickname] OFFSET 1 ROWS"); } public override async Task Correlated_collections_with_Take(bool async) { await base.Correlated_collections_with_Take(async); AssertSql( @"SELECT [s].[Id] FROM [Squads] AS [s] ORDER BY [s].[Name]", // @"@_outer_Id='1' SELECT TOP(2) [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE @_outer_Id = [g].[SquadId] ORDER BY [g].[Nickname]", // @"@_outer_Id='2' SELECT TOP(2) [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE @_outer_Id = [g].[SquadId] ORDER BY [g].[Nickname]"); } public override async Task Correlated_collections_with_Distinct(bool async) { await base.Correlated_collections_with_Distinct(async); AssertSql( @"SELECT [s].[Id], [t0].[Nickname], [t0].[SquadId], [t0].[AssignedCityName], [t0].[CityOfBirthName], [t0].[Discriminator], [t0].[FullName], [t0].[HasSoulPatch], [t0].[LeaderNickname], [t0].[LeaderSquadId], [t0].[Rank] FROM [Squads] AS [s] OUTER APPLY ( SELECT DISTINCT [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank] FROM ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [s].[Id] = [g].[SquadId] ORDER BY [g].[Nickname] OFFSET 0 ROWS ) AS [t] ) AS [t0] ORDER BY [s].[Name], [s].[Id], [t0].[Nickname]"); } public override async Task Correlated_collections_with_FirstOrDefault(bool async) { await base.Correlated_collections_with_FirstOrDefault(async); AssertSql( @"SELECT ( SELECT TOP(1) [g].[FullName] FROM [Gears] AS [g] WHERE [s].[Id] = [g].[SquadId] ORDER BY [g].[Nickname]) FROM [Squads] AS [s] ORDER BY [s].[Name]"); } public override async Task Correlated_collections_on_left_join_with_predicate(bool async) { await base.Correlated_collections_on_left_join_with_predicate(async); AssertSql( @"SELECT [g].[Nickname], [t].[Id], [g].[SquadId], [w].[Name], [w].[Id] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON [t].[GearNickName] = [g].[Nickname] LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] WHERE [g].[HasSoulPatch] = CAST(0 AS bit) ORDER BY [t].[Id], [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collections_on_left_join_with_null_value(bool async) { await base.Correlated_collections_on_left_join_with_null_value(async); AssertSql( @"SELECT [t].[Id], [g].[Nickname], [g].[SquadId], [w].[Name], [w].[Id] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON [t].[GearNickName] = [g].[Nickname] LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] ORDER BY [t].[Note], [t].[Id], [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collections_left_join_with_self_reference(bool async) { await base.Correlated_collections_left_join_with_self_reference(async); AssertSql( @"SELECT [t].[Note], [t].[Id], [t0].[Nickname], [t0].[SquadId], [g0].[FullName], [g0].[Nickname], [g0].[SquadId] FROM [Tags] AS [t] LEFT JOIN ( SELECT [g].[Nickname], [g].[SquadId] FROM [Gears] AS [g] WHERE [g].[Discriminator] = N'Officer' ) AS [t0] ON [t].[GearNickName] = [t0].[Nickname] LEFT JOIN [Gears] AS [g0] ON (([t0].[Nickname] = [g0].[LeaderNickname]) OR ([t0].[Nickname] IS NULL AND [g0].[LeaderNickname] IS NULL)) AND ([t0].[SquadId] = [g0].[LeaderSquadId]) ORDER BY [t].[Id], [t0].[Nickname], [t0].[SquadId], [g0].[Nickname]"); } public override async Task Correlated_collections_deeply_nested_left_join(bool async) { await base.Correlated_collections_deeply_nested_left_join(async); AssertSql( @"SELECT [t].[Id], [g].[Nickname], [g].[SquadId], [s].[Id], [t0].[Nickname], [t0].[SquadId], [t0].[Id], [t0].[AmmunitionType], [t0].[IsAutomatic], [t0].[Name], [t0].[OwnerFullName], [t0].[SynergyWithId] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON [t].[GearNickName] = [g].[Nickname] LEFT JOIN [Squads] AS [s] ON [g].[SquadId] = [s].[Id] LEFT JOIN ( SELECT [g0].[Nickname], [g0].[SquadId], [t1].[Id], [t1].[AmmunitionType], [t1].[IsAutomatic], [t1].[Name], [t1].[OwnerFullName], [t1].[SynergyWithId] FROM [Gears] AS [g0] LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [w].[IsAutomatic] = CAST(1 AS bit) ) AS [t1] ON [g0].[FullName] = [t1].[OwnerFullName] WHERE [g0].[HasSoulPatch] = CAST(1 AS bit) ) AS [t0] ON [s].[Id] = [t0].[SquadId] ORDER BY [t].[Note], [g].[Nickname] DESC, [t].[Id], [g].[SquadId], [s].[Id], [t0].[Nickname], [t0].[SquadId]"); } public override async Task Correlated_collections_from_left_join_with_additional_elements_projected_of_that_join(bool async) { await base.Correlated_collections_from_left_join_with_additional_elements_projected_of_that_join(async); AssertSql( @"SELECT [w].[Id], [g].[Nickname], [g].[SquadId], [s].[Id], [t0].[Nickname], [t0].[SquadId], [t0].[Id], [t0].[AmmunitionType], [t0].[IsAutomatic], [t0].[Name], [t0].[OwnerFullName], [t0].[SynergyWithId], [t0].[Rank] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g] ON [w].[OwnerFullName] = [g].[FullName] LEFT JOIN [Squads] AS [s] ON [g].[SquadId] = [s].[Id] LEFT JOIN ( SELECT [g0].[Nickname], [g0].[SquadId], [t].[Id], [t].[AmmunitionType], [t].[IsAutomatic], [t].[Name], [t].[OwnerFullName], [t].[SynergyWithId], [g0].[Rank], [g0].[FullName] FROM [Gears] AS [g0] LEFT JOIN ( SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w0] WHERE [w0].[IsAutomatic] = CAST(0 AS bit) ) AS [t] ON [g0].[FullName] = [t].[OwnerFullName] ) AS [t0] ON [s].[Id] = [t0].[SquadId] ORDER BY [w].[Name], [w].[Id], [g].[Nickname], [g].[SquadId], [s].[Id], [t0].[FullName] DESC, [t0].[Nickname], [t0].[SquadId], [t0].[Id]"); } public override async Task Correlated_collections_complex_scenario1(bool async) { await base.Correlated_collections_complex_scenario1(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t0].[Id], [t0].[Nickname], [t0].[SquadId], [t0].[Id0], [t0].[Nickname0], [t0].[HasSoulPatch], [t0].[SquadId0] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w].[Id], [g0].[Nickname], [g0].[SquadId], [s].[Id] AS [Id0], [t].[Nickname] AS [Nickname0], [t].[HasSoulPatch], [t].[SquadId] AS [SquadId0], [w].[OwnerFullName] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g0] ON [w].[OwnerFullName] = [g0].[FullName] LEFT JOIN [Squads] AS [s] ON [g0].[SquadId] = [s].[Id] LEFT JOIN ( SELECT [g1].[Nickname], [g1].[HasSoulPatch], [g1].[SquadId] FROM [Gears] AS [g1] ) AS [t] ON [s].[Id] = [t].[SquadId] ) AS [t0] ON [g].[FullName] = [t0].[OwnerFullName] ORDER BY [g].[Nickname], [g].[SquadId], [t0].[Id], [t0].[Nickname], [t0].[SquadId], [t0].[Id0], [t0].[Nickname0]"); } public override async Task Correlated_collections_complex_scenario2(bool async) { await base.Correlated_collections_complex_scenario2(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t1].[FullName], [t1].[Nickname], [t1].[SquadId], [t1].[Id], [t1].[Nickname0], [t1].[SquadId0], [t1].[Id0], [t1].[Nickname00], [t1].[HasSoulPatch], [t1].[SquadId00] FROM [Gears] AS [g] LEFT JOIN ( SELECT [g0].[FullName], [g0].[Nickname], [g0].[SquadId], [t0].[Id], [t0].[Nickname] AS [Nickname0], [t0].[SquadId] AS [SquadId0], [t0].[Id0], [t0].[Nickname0] AS [Nickname00], [t0].[HasSoulPatch], [t0].[SquadId0] AS [SquadId00], [g0].[LeaderNickname], [g0].[LeaderSquadId] FROM [Gears] AS [g0] LEFT JOIN ( SELECT [w].[Id], [g1].[Nickname], [g1].[SquadId], [s].[Id] AS [Id0], [t].[Nickname] AS [Nickname0], [t].[HasSoulPatch], [t].[SquadId] AS [SquadId0], [w].[OwnerFullName] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g1] ON [w].[OwnerFullName] = [g1].[FullName] LEFT JOIN [Squads] AS [s] ON [g1].[SquadId] = [s].[Id] LEFT JOIN ( SELECT [g2].[Nickname], [g2].[HasSoulPatch], [g2].[SquadId] FROM [Gears] AS [g2] ) AS [t] ON [s].[Id] = [t].[SquadId] ) AS [t0] ON [g0].[FullName] = [t0].[OwnerFullName] ) AS [t1] ON ([g].[Nickname] = [t1].[LeaderNickname]) AND ([g].[SquadId] = [t1].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[Nickname], [g].[SquadId], [t1].[Nickname], [t1].[SquadId], [t1].[Id], [t1].[Nickname0], [t1].[SquadId0], [t1].[Id0], [t1].[Nickname00]"); } public override async Task Correlated_collections_with_funky_orderby_complex_scenario1(bool async) { await base.Correlated_collections_with_funky_orderby_complex_scenario1(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t0].[Id], [t0].[Nickname], [t0].[SquadId], [t0].[Id0], [t0].[Nickname0], [t0].[HasSoulPatch], [t0].[SquadId0] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w].[Id], [g0].[Nickname], [g0].[SquadId], [s].[Id] AS [Id0], [t].[Nickname] AS [Nickname0], [t].[HasSoulPatch], [t].[SquadId] AS [SquadId0], [w].[OwnerFullName] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g0] ON [w].[OwnerFullName] = [g0].[FullName] LEFT JOIN [Squads] AS [s] ON [g0].[SquadId] = [s].[Id] LEFT JOIN ( SELECT [g1].[Nickname], [g1].[HasSoulPatch], [g1].[SquadId] FROM [Gears] AS [g1] ) AS [t] ON [s].[Id] = [t].[SquadId] ) AS [t0] ON [g].[FullName] = [t0].[OwnerFullName] ORDER BY [g].[FullName], [g].[Nickname] DESC, [g].[SquadId], [t0].[Id], [t0].[Nickname], [t0].[SquadId], [t0].[Id0], [t0].[Nickname0]"); } public override async Task Correlated_collections_with_funky_orderby_complex_scenario2(bool async) { await base.Correlated_collections_with_funky_orderby_complex_scenario2(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t1].[FullName], [t1].[Nickname], [t1].[SquadId], [t1].[Id], [t1].[Nickname0], [t1].[SquadId0], [t1].[Id0], [t1].[Nickname00], [t1].[HasSoulPatch], [t1].[SquadId00] FROM [Gears] AS [g] LEFT JOIN ( SELECT [g0].[FullName], [g0].[Nickname], [g0].[SquadId], [t0].[Id], [t0].[Nickname] AS [Nickname0], [t0].[SquadId] AS [SquadId0], [t0].[Id0], [t0].[Nickname0] AS [Nickname00], [t0].[HasSoulPatch], [t0].[SquadId0] AS [SquadId00], [g0].[HasSoulPatch] AS [HasSoulPatch0], [t0].[IsAutomatic], [t0].[Name], [g0].[LeaderNickname], [g0].[LeaderSquadId] FROM [Gears] AS [g0] LEFT JOIN ( SELECT [w].[Id], [g1].[Nickname], [g1].[SquadId], [s].[Id] AS [Id0], [t].[Nickname] AS [Nickname0], [t].[HasSoulPatch], [t].[SquadId] AS [SquadId0], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g1] ON [w].[OwnerFullName] = [g1].[FullName] LEFT JOIN [Squads] AS [s] ON [g1].[SquadId] = [s].[Id] LEFT JOIN ( SELECT [g2].[Nickname], [g2].[HasSoulPatch], [g2].[SquadId] FROM [Gears] AS [g2] ) AS [t] ON [s].[Id] = [t].[SquadId] ) AS [t0] ON [g0].[FullName] = [t0].[OwnerFullName] ) AS [t1] ON ([g].[Nickname] = [t1].[LeaderNickname]) AND ([g].[SquadId] = [t1].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[HasSoulPatch], [g].[LeaderNickname], [g].[FullName], [g].[Nickname], [g].[SquadId], [t1].[FullName], [t1].[HasSoulPatch0] DESC, [t1].[Nickname], [t1].[SquadId], [t1].[IsAutomatic], [t1].[Name] DESC, [t1].[Id], [t1].[Nickname0], [t1].[SquadId0], [t1].[Id0], [t1].[Nickname00]"); } public override async Task Correlated_collection_with_top_level_FirstOrDefault(bool async) { await base.Correlated_collection_with_top_level_FirstOrDefault(async); AssertSql( @"SELECT [t].[Nickname], [t].[SquadId], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM ( SELECT TOP(1) [g].[Nickname], [g].[SquadId], [g].[FullName] FROM [Gears] AS [g] ORDER BY [g].[Nickname] ) AS [t] LEFT JOIN [Weapons] AS [w] ON [t].[FullName] = [w].[OwnerFullName] ORDER BY [t].[Nickname], [t].[SquadId]"); } public override async Task Correlated_collection_with_top_level_Count(bool async) { await base.Correlated_collection_with_top_level_Count(async); AssertSql( @"SELECT COUNT(*) FROM [Gears] AS [g]"); } public override async Task Correlated_collection_with_top_level_Last_with_orderby_on_outer(bool async) { await base.Correlated_collection_with_top_level_Last_with_orderby_on_outer(async); AssertSql( @"SELECT [t].[Nickname], [t].[SquadId], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM ( SELECT TOP(1) [g].[Nickname], [g].[SquadId], [g].[FullName] FROM [Gears] AS [g] ORDER BY [g].[FullName] ) AS [t] LEFT JOIN [Weapons] AS [w] ON [t].[FullName] = [w].[OwnerFullName] ORDER BY [t].[FullName], [t].[Nickname], [t].[SquadId]"); } public override async Task Correlated_collection_with_top_level_Last_with_order_by_on_inner(bool async) { await base.Correlated_collection_with_top_level_Last_with_order_by_on_inner(async); AssertSql( @"SELECT [t].[Nickname], [t].[SquadId], [t0].[Id], [t0].[AmmunitionType], [t0].[IsAutomatic], [t0].[Name], [t0].[OwnerFullName], [t0].[SynergyWithId] FROM ( SELECT TOP(1) [g].[Nickname], [g].[SquadId], [g].[FullName] FROM [Gears] AS [g] ORDER BY [g].[FullName] DESC ) AS [t] LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] ) AS [t0] ON [t].[FullName] = [t0].[OwnerFullName] ORDER BY [t].[FullName] DESC, [t].[Nickname], [t].[SquadId], [t0].[Name]"); } public override async Task Null_semantics_on_nullable_bool_from_inner_join_subquery_is_fully_applied(bool async) { await base.Null_semantics_on_nullable_bool_from_inner_join_subquery_is_fully_applied(async); AssertSql( @"SELECT [t].[Id], [t].[CapitalName], [t].[Discriminator], [t].[Name], [t].[ServerAddress], [t].[CommanderName], [t].[Eradicated] FROM [LocustLeaders] AS [l] INNER JOIN ( SELECT [f].[Id], [f].[CapitalName], [f].[Discriminator], [f].[Name], [f].[ServerAddress], [f].[CommanderName], [f].[Eradicated] FROM [Factions] AS [f] WHERE [f].[Name] = N'Swarm' ) AS [t] ON [l].[Name] = [t].[CommanderName] WHERE ([t].[Eradicated] <> CAST(1 AS bit)) OR ([t].[Eradicated] IS NULL)"); } public override async Task Null_semantics_on_nullable_bool_from_left_join_subquery_is_fully_applied(bool async) { await base.Null_semantics_on_nullable_bool_from_left_join_subquery_is_fully_applied(async); AssertSql( @"SELECT [t].[Id], [t].[CapitalName], [t].[Discriminator], [t].[Name], [t].[ServerAddress], [t].[CommanderName], [t].[Eradicated] FROM [LocustLeaders] AS [l] LEFT JOIN ( SELECT [f].[Id], [f].[CapitalName], [f].[Discriminator], [f].[Name], [f].[ServerAddress], [f].[CommanderName], [f].[Eradicated] FROM [Factions] AS [f] WHERE [f].[Name] = N'Swarm' ) AS [t] ON [l].[Name] = [t].[CommanderName] WHERE ([t].[Eradicated] <> CAST(1 AS bit)) OR ([t].[Eradicated] IS NULL)"); } public override async Task Include_on_derived_type_with_order_by_and_paging(bool async) { await base.Include_on_derived_type_with_order_by_and_paging(async); AssertSql( @"@__p_0='10' SELECT [t0].[Name], [t0].[Discriminator], [t0].[LocustHordeId], [t0].[ThreatLevel], [t0].[ThreatLevelByte], [t0].[ThreatLevelNullableByte], [t0].[DefeatedByNickname], [t0].[DefeatedBySquadId], [t0].[HighCommandId], [t0].[Nickname], [t0].[SquadId], [t0].[AssignedCityName], [t0].[CityOfBirthName], [t0].[Discriminator0], [t0].[FullName], [t0].[HasSoulPatch], [t0].[LeaderNickname], [t0].[LeaderSquadId], [t0].[Rank], [t0].[Id], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM ( SELECT TOP(@__p_0) [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator] AS [Discriminator0], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Id], [t].[Note] FROM [LocustLeaders] AS [l] LEFT JOIN [Gears] AS [g] ON ([l].[DefeatedByNickname] = [g].[Nickname]) AND ([l].[DefeatedBySquadId] = [g].[SquadId]) LEFT JOIN [Tags] AS [t] ON (([g].[Nickname] = [t].[GearNickName]) OR ([g].[Nickname] IS NULL AND [t].[GearNickName] IS NULL)) AND (([g].[SquadId] = [t].[GearSquadId]) OR ([g].[SquadId] IS NULL AND [t].[GearSquadId] IS NULL)) ORDER BY [t].[Note] ) AS [t0] LEFT JOIN [Weapons] AS [w] ON [t0].[FullName] = [w].[OwnerFullName] ORDER BY [t0].[Note], [t0].[Name], [t0].[Nickname], [t0].[SquadId], [t0].[Id]"); } public override async Task Select_required_navigation_on_derived_type(bool async) { await base.Select_required_navigation_on_derived_type(async); AssertSql( @"SELECT [l0].[Name] FROM [LocustLeaders] AS [l] LEFT JOIN [LocustHighCommands] AS [l0] ON [l].[HighCommandId] = [l0].[Id]"); } public override async Task Select_required_navigation_on_the_same_type_with_cast(bool async) { await base.Select_required_navigation_on_the_same_type_with_cast(async); AssertSql( @"SELECT [c].[Name] FROM [Gears] AS [g] INNER JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name]"); } public override async Task Where_required_navigation_on_derived_type(bool async) { await base.Where_required_navigation_on_derived_type(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] LEFT JOIN [LocustHighCommands] AS [l0] ON [l].[HighCommandId] = [l0].[Id] WHERE [l0].[IsOperational] = CAST(1 AS bit)"); } public override async Task Outer_parameter_in_join_key(bool async) { await base.Outer_parameter_in_join_key(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t0].[Note], [t0].[Id], [t0].[Nickname], [t0].[SquadId] FROM [Gears] AS [g] OUTER APPLY ( SELECT [t].[Note], [t].[Id], [g0].[Nickname], [g0].[SquadId] FROM [Tags] AS [t] INNER JOIN [Gears] AS [g0] ON [g].[FullName] = [g0].[FullName] ) AS [t0] WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[Nickname], [g].[SquadId], [t0].[Id], [t0].[Nickname]"); } public override async Task Outer_parameter_in_join_key_inner_and_outer(bool async) { await base.Outer_parameter_in_join_key_inner_and_outer(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t0].[Note], [t0].[Id], [t0].[Nickname], [t0].[SquadId] FROM [Gears] AS [g] OUTER APPLY ( SELECT [t].[Note], [t].[Id], [g0].[Nickname], [g0].[SquadId] FROM [Tags] AS [t] INNER JOIN [Gears] AS [g0] ON [g].[FullName] = [g].[Nickname] ) AS [t0] WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[Nickname], [g].[SquadId], [t0].[Id], [t0].[Nickname]"); } public override async Task Outer_parameter_in_group_join_with_DefaultIfEmpty(bool async) { await base.Outer_parameter_in_group_join_with_DefaultIfEmpty(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t0].[Note], [t0].[Id], [t0].[Nickname], [t0].[SquadId] FROM [Gears] AS [g] OUTER APPLY ( SELECT [t].[Note], [t].[Id], [g0].[Nickname], [g0].[SquadId] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g0] ON [g].[FullName] = [g0].[FullName] ) AS [t0] WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[Nickname], [g].[SquadId], [t0].[Id], [t0].[Nickname]"); } public override async Task Negated_bool_ternary_inside_anonymous_type_in_projection(bool async) { await base.Negated_bool_ternary_inside_anonymous_type_in_projection(async); AssertSql( @"SELECT CASE WHEN CASE WHEN [g].[HasSoulPatch] = CAST(1 AS bit) THEN CAST(1 AS bit) ELSE COALESCE([g].[HasSoulPatch], CAST(1 AS bit)) END = CAST(0 AS bit) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [c] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId])"); } public override async Task Order_by_entity_qsre(bool async) { await base.Order_by_entity_qsre(async); AssertSql( @"SELECT [g].[FullName] FROM [Gears] AS [g] LEFT JOIN [Cities] AS [c] ON [g].[AssignedCityName] = [c].[Name] ORDER BY [c].[Name], [g].[Nickname] DESC"); } public override async Task Order_by_entity_qsre_with_inheritance(bool async) { await base.Order_by_entity_qsre_with_inheritance(async); AssertSql( @"SELECT [l].[Name] FROM [LocustLeaders] AS [l] INNER JOIN [LocustHighCommands] AS [l0] ON [l].[HighCommandId] = [l0].[Id] WHERE [l].[Discriminator] = N'LocustCommander' ORDER BY [l0].[Id], [l].[Name]"); } public override async Task Order_by_entity_qsre_composite_key(bool async) { await base.Order_by_entity_qsre_composite_key(async); AssertSql( @"SELECT [w].[Name] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g] ON [w].[OwnerFullName] = [g].[FullName] ORDER BY [g].[Nickname], [g].[SquadId], [w].[Id]"); } public override async Task Order_by_entity_qsre_with_other_orderbys(bool async) { await base.Order_by_entity_qsre_with_other_orderbys(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g] ON [w].[OwnerFullName] = [g].[FullName] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id] ORDER BY [w].[IsAutomatic], [g].[Nickname] DESC, [g].[SquadId] DESC, [w0].[Id], [w].[Name]"); } public override async Task Join_on_entity_qsre_keys(bool async) { await base.Join_on_entity_qsre_keys(async); AssertSql( @"SELECT [w].[Name] AS [Name1], [w0].[Name] AS [Name2] FROM [Weapons] AS [w] INNER JOIN [Weapons] AS [w0] ON [w].[Id] = [w0].[Id]"); } public override async Task Join_on_entity_qsre_keys_composite_key(bool async) { await base.Join_on_entity_qsre_keys_composite_key(async); AssertSql( @"SELECT [g].[FullName] AS [GearName1], [g0].[FullName] AS [GearName2] FROM [Gears] AS [g] INNER JOIN [Gears] AS [g0] ON ([g].[Nickname] = [g0].[Nickname]) AND ([g].[SquadId] = [g0].[SquadId])"); } public override async Task Join_on_entity_qsre_keys_inheritance(bool async) { await base.Join_on_entity_qsre_keys_inheritance(async); AssertSql( @"SELECT [g].[FullName] AS [GearName], [t].[FullName] AS [OfficerName] FROM [Gears] AS [g] INNER JOIN ( SELECT [g0].[Nickname], [g0].[SquadId], [g0].[FullName] FROM [Gears] AS [g0] WHERE [g0].[Discriminator] = N'Officer' ) AS [t] ON ([g].[Nickname] = [t].[Nickname]) AND ([g].[SquadId] = [t].[SquadId])"); } public override async Task Join_on_entity_qsre_keys_outer_key_is_navigation(bool async) { await base.Join_on_entity_qsre_keys_outer_key_is_navigation(async); AssertSql( @"SELECT [w].[Name] AS [Name1], [w1].[Name] AS [Name2] FROM [Weapons] AS [w] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id] INNER JOIN [Weapons] AS [w1] ON [w0].[Id] = [w1].[Id]"); } public override async Task Join_on_entity_qsre_keys_inner_key_is_navigation(bool async) { await base.Join_on_entity_qsre_keys_inner_key_is_navigation(async); AssertSql( @"SELECT [c].[Name] AS [CityName], [t].[Nickname] AS [GearNickname] FROM [Cities] AS [c] INNER JOIN ( SELECT [g].[Nickname], [c0].[Name] FROM [Gears] AS [g] LEFT JOIN [Cities] AS [c0] ON [g].[AssignedCityName] = [c0].[Name] ) AS [t] ON [c].[Name] = [t].[Name]"); } public override async Task Join_on_entity_qsre_keys_inner_key_is_navigation_composite_key(bool async) { await base.Join_on_entity_qsre_keys_inner_key_is_navigation_composite_key(async); AssertSql( @"SELECT [g].[Nickname], [t0].[Note] FROM [Gears] AS [g] INNER JOIN ( SELECT [t].[Note], [g0].[Nickname], [g0].[SquadId] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g0] ON ([t].[GearNickName] = [g0].[Nickname]) AND ([t].[GearSquadId] = [g0].[SquadId]) WHERE [t].[Note] IN (N'Cole''s Tag', N'Dom''s Tag') ) AS [t0] ON ([g].[Nickname] = [t0].[Nickname]) AND ([g].[SquadId] = [t0].[SquadId])"); } public override async Task Join_on_entity_qsre_keys_inner_key_is_nested_navigation(bool async) { await base.Join_on_entity_qsre_keys_inner_key_is_nested_navigation(async); AssertSql( @"SELECT [s].[Name] AS [SquadName], [t].[Name] AS [WeaponName] FROM [Squads] AS [s] INNER JOIN ( SELECT [w].[Name], [s0].[Id] AS [Id0] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g] ON [w].[OwnerFullName] = [g].[FullName] LEFT JOIN [Squads] AS [s0] ON [g].[SquadId] = [s0].[Id] WHERE [w].[IsAutomatic] = CAST(1 AS bit) ) AS [t] ON [s].[Id] = [t].[Id0]"); } public override async Task GroupJoin_on_entity_qsre_keys_inner_key_is_nested_navigation(bool async) { await base.GroupJoin_on_entity_qsre_keys_inner_key_is_nested_navigation(async); AssertSql( @"SELECT [s].[Name] AS [SquadName], [t].[Name] AS [WeaponName] FROM [Squads] AS [s] LEFT JOIN ( SELECT [w].[Name], [s0].[Id] AS [Id0] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g] ON [w].[OwnerFullName] = [g].[FullName] LEFT JOIN [Squads] AS [s0] ON [g].[SquadId] = [s0].[Id] ) AS [t] ON [s].[Id] = [t].[Id0]"); } public override async Task Streaming_correlated_collection_issue_11403(bool async) { await base.Streaming_correlated_collection_issue_11403(async); AssertSql( @"SELECT [t].[Nickname], [t].[SquadId], [t0].[Id], [t0].[AmmunitionType], [t0].[IsAutomatic], [t0].[Name], [t0].[OwnerFullName], [t0].[SynergyWithId] FROM ( SELECT TOP(1) [g].[Nickname], [g].[SquadId], [g].[FullName] FROM [Gears] AS [g] ORDER BY [g].[Nickname] ) AS [t] LEFT JOIN ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [w].[IsAutomatic] = CAST(0 AS bit) ) AS [t0] ON [t].[FullName] = [t0].[OwnerFullName] ORDER BY [t].[Nickname], [t].[SquadId], [t0].[Id]"); } public override async Task Project_one_value_type_from_empty_collection(bool async) { await base.Project_one_value_type_from_empty_collection(async); AssertSql( @"SELECT [s].[Name], COALESCE(( SELECT TOP(1) [g].[SquadId] FROM [Gears] AS [g] WHERE ([s].[Id] = [g].[SquadId]) AND ([g].[HasSoulPatch] = CAST(1 AS bit))), 0) AS [SquadId] FROM [Squads] AS [s] WHERE [s].[Name] = N'Kilo'"); } public override async Task Project_one_value_type_converted_to_nullable_from_empty_collection(bool async) { await base.Project_one_value_type_converted_to_nullable_from_empty_collection(async); AssertSql( @"SELECT [s].[Name], ( SELECT TOP(1) [g].[SquadId] FROM [Gears] AS [g] WHERE ([s].[Id] = [g].[SquadId]) AND ([g].[HasSoulPatch] = CAST(1 AS bit))) AS [SquadId] FROM [Squads] AS [s] WHERE [s].[Name] = N'Kilo'"); } public override async Task Project_one_value_type_with_client_projection_from_empty_collection(bool async) { await base.Project_one_value_type_with_client_projection_from_empty_collection(async); AssertSql( @"SELECT [s].[Name], [t0].[SquadId], [t0].[LeaderSquadId], [t0].[c] FROM [Squads] AS [s] LEFT JOIN ( SELECT [t].[SquadId], [t].[LeaderSquadId], [t].[c] FROM ( SELECT [g].[SquadId], [g].[LeaderSquadId], 1 AS [c], ROW_NUMBER() OVER(PARTITION BY [g].[SquadId] ORDER BY [g].[Nickname], [g].[SquadId]) AS [row] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(1 AS bit) ) AS [t] WHERE [t].[row] <= 1 ) AS [t0] ON [s].[Id] = [t0].[SquadId] WHERE [s].[Name] = N'Kilo'"); } public override async Task Filter_on_subquery_projecting_one_value_type_from_empty_collection(bool async) { await base.Filter_on_subquery_projecting_one_value_type_from_empty_collection(async); AssertSql( @"SELECT [s].[Name] FROM [Squads] AS [s] WHERE ([s].[Name] = N'Kilo') AND (COALESCE(( SELECT TOP(1) [g].[SquadId] FROM [Gears] AS [g] WHERE ([g].[Discriminator] IN (N'Officer', N'Gear') AND ([s].[Id] = [g].[SquadId])) AND ([g].[HasSoulPatch] = CAST(1 AS bit)) ), 0) <> 0)"); } public override async Task Select_subquery_projecting_single_constant_int(bool async) { await base.Select_subquery_projecting_single_constant_int(async); AssertSql( @"SELECT [s].[Name], COALESCE(( SELECT TOP(1) 42 FROM [Gears] AS [g] WHERE ([s].[Id] = [g].[SquadId]) AND ([g].[HasSoulPatch] = CAST(1 AS bit))), 0) AS [Gear] FROM [Squads] AS [s]"); } public override async Task Select_subquery_projecting_single_constant_string(bool async) { await base.Select_subquery_projecting_single_constant_string(async); AssertSql( @"SELECT [s].[Name], ( SELECT TOP(1) N'Foo' FROM [Gears] AS [g] WHERE ([s].[Id] = [g].[SquadId]) AND ([g].[HasSoulPatch] = CAST(1 AS bit))) AS [Gear] FROM [Squads] AS [s]"); } public override async Task Select_subquery_projecting_single_constant_bool(bool async) { await base.Select_subquery_projecting_single_constant_bool(async); AssertSql( @"SELECT [s].[Name], COALESCE(( SELECT TOP(1) CAST(1 AS bit) FROM [Gears] AS [g] WHERE ([s].[Id] = [g].[SquadId]) AND ([g].[HasSoulPatch] = CAST(1 AS bit))), CAST(0 AS bit)) AS [Gear] FROM [Squads] AS [s]"); } public override async Task Select_subquery_projecting_single_constant_inside_anonymous(bool async) { await base.Select_subquery_projecting_single_constant_inside_anonymous(async); AssertSql( @"SELECT [s].[Name], [t0].[One] FROM [Squads] AS [s] LEFT JOIN ( SELECT [t].[One], [t].[SquadId] FROM ( SELECT 1 AS [One], [g].[SquadId], ROW_NUMBER() OVER(PARTITION BY [g].[SquadId] ORDER BY [g].[Nickname], [g].[SquadId]) AS [row] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(1 AS bit) ) AS [t] WHERE [t].[row] <= 1 ) AS [t0] ON [s].[Id] = [t0].[SquadId]"); } public override async Task Select_subquery_projecting_multiple_constants_inside_anonymous(bool async) { await base.Select_subquery_projecting_multiple_constants_inside_anonymous(async); AssertSql( @"SELECT [s].[Name], [t0].[True1], [t0].[False1], [t0].[c] FROM [Squads] AS [s] LEFT JOIN ( SELECT [t].[True1], [t].[False1], [t].[c], [t].[SquadId] FROM ( SELECT CAST(1 AS bit) AS [True1], CAST(0 AS bit) AS [False1], 1 AS [c], [g].[SquadId], ROW_NUMBER() OVER(PARTITION BY [g].[SquadId] ORDER BY [g].[Nickname], [g].[SquadId]) AS [row] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(1 AS bit) ) AS [t] WHERE [t].[row] <= 1 ) AS [t0] ON [s].[Id] = [t0].[SquadId]"); } public override async Task Include_with_order_by_constant(bool async) { await base.Include_with_order_by_constant(async); AssertSql( @"SELECT [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Squads] AS [s] LEFT JOIN [Gears] AS [g] ON [s].[Id] = [g].[SquadId] ORDER BY [s].[Id], [g].[Nickname]"); } public override async Task Correlated_collection_order_by_constant(bool async) { await base.Correlated_collection_order_by_constant(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [w].[Name], [w].[Id] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Select_subquery_projecting_single_constant_null_of_non_mapped_type(bool async) { await base.Select_subquery_projecting_single_constant_null_of_non_mapped_type(async); AssertSql( @"SELECT [s].[Name], [t0].[c] FROM [Squads] AS [s] LEFT JOIN ( SELECT [t].[c], [t].[SquadId] FROM ( SELECT 1 AS [c], [g].[SquadId], ROW_NUMBER() OVER(PARTITION BY [g].[SquadId] ORDER BY [g].[Nickname], [g].[SquadId]) AS [row] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(1 AS bit) ) AS [t] WHERE [t].[row] <= 1 ) AS [t0] ON [s].[Id] = [t0].[SquadId]"); } public override async Task Select_subquery_projecting_single_constant_of_non_mapped_type(bool async) { await base.Select_subquery_projecting_single_constant_of_non_mapped_type(async); AssertSql( @"SELECT [s].[Name], [t0].[c] FROM [Squads] AS [s] LEFT JOIN ( SELECT [t].[c], [t].[SquadId] FROM ( SELECT 1 AS [c], [g].[SquadId], ROW_NUMBER() OVER(PARTITION BY [g].[SquadId] ORDER BY [g].[Nickname], [g].[SquadId]) AS [row] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(1 AS bit) ) AS [t] WHERE [t].[row] <= 1 ) AS [t0] ON [s].[Id] = [t0].[SquadId]"); } public override async Task Include_collection_OrderBy_aggregate(bool async) { await base.Include_collection_OrderBy_aggregate(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY ( SELECT COUNT(*) FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName]), [g].[Nickname], [g].[SquadId], [g0].[Nickname]"); } public override async Task Include_collection_with_complex_OrderBy2(bool async) { await base.Include_collection_with_complex_OrderBy2(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY ( SELECT TOP(1) [w].[IsAutomatic] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ORDER BY [w].[Id]), [g].[Nickname], [g].[SquadId], [g0].[Nickname]"); } public override async Task Include_collection_with_complex_OrderBy3(bool async) { await base.Include_collection_with_complex_OrderBy3(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY COALESCE(( SELECT TOP(1) [w].[IsAutomatic] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ORDER BY [w].[Id]), CAST(0 AS bit)), [g].[Nickname], [g].[SquadId], [g0].[Nickname]"); } public override async Task Correlated_collection_with_complex_OrderBy(bool async) { await base.Correlated_collection_with_complex_OrderBy(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank] FROM [Gears] AS [g] LEFT JOIN ( SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g0] WHERE [g0].[HasSoulPatch] = CAST(0 AS bit) ) AS [t] ON ([g].[Nickname] = [t].[LeaderNickname]) AND ([g].[SquadId] = [t].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY ( SELECT COUNT(*) FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName]), [g].[Nickname], [g].[SquadId], [t].[Nickname]"); } public override async Task Correlated_collection_with_very_complex_order_by(bool async) { await base.Correlated_collection_with_very_complex_order_by(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank] FROM [Gears] AS [g] LEFT JOIN ( SELECT [g1].[Nickname], [g1].[SquadId], [g1].[AssignedCityName], [g1].[CityOfBirthName], [g1].[Discriminator], [g1].[FullName], [g1].[HasSoulPatch], [g1].[LeaderNickname], [g1].[LeaderSquadId], [g1].[Rank] FROM [Gears] AS [g1] WHERE [g1].[HasSoulPatch] = CAST(0 AS bit) ) AS [t] ON ([g].[Nickname] = [t].[LeaderNickname]) AND ([g].[SquadId] = [t].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY ( SELECT COUNT(*) FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[IsAutomatic] = COALESCE(( SELECT TOP(1) [g0].[HasSoulPatch] FROM [Gears] AS [g0] WHERE [g0].[Nickname] = N'Marcus'), CAST(0 AS bit)))), [g].[Nickname], [g].[SquadId], [t].[Nickname]"); } public override async Task Cast_to_derived_type_after_OfType_works(bool async) { await base.Cast_to_derived_type_after_OfType_works(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] = N'Officer'"); } public override async Task Select_subquery_boolean(bool async) { await base.Select_subquery_boolean(async); AssertSql( @"SELECT COALESCE(( SELECT TOP(1) [w].[IsAutomatic] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ORDER BY [w].[Id]), CAST(0 AS bit)) FROM [Gears] AS [g]"); } public override async Task Select_subquery_boolean_with_pushdown(bool async) { await base.Select_subquery_boolean_with_pushdown(async); AssertSql( @"SELECT ( SELECT TOP(1) [w].[IsAutomatic] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ORDER BY [w].[Id]) FROM [Gears] AS [g]"); } public override async Task Select_subquery_int_with_inside_cast_and_coalesce(bool async) { await base.Select_subquery_int_with_inside_cast_and_coalesce(async); AssertSql( @"SELECT COALESCE(( SELECT TOP(1) [w].[Id] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ORDER BY [w].[Id]), 42) FROM [Gears] AS [g]"); } public override async Task Select_subquery_int_with_outside_cast_and_coalesce(bool async) { await base.Select_subquery_int_with_outside_cast_and_coalesce(async); AssertSql( @"SELECT COALESCE(( SELECT TOP(1) [w].[Id] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ORDER BY [w].[Id]), 0, 42) FROM [Gears] AS [g]"); } public override async Task Select_subquery_int_with_pushdown_and_coalesce(bool async) { await base.Select_subquery_int_with_pushdown_and_coalesce(async); AssertSql( @"SELECT COALESCE(( SELECT TOP(1) [w].[Id] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ORDER BY [w].[Id]), 42) FROM [Gears] AS [g]"); } public override async Task Select_subquery_int_with_pushdown_and_coalesce2(bool async) { await base.Select_subquery_int_with_pushdown_and_coalesce2(async); AssertSql( @"SELECT COALESCE(( SELECT TOP(1) [w].[Id] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ORDER BY [w].[Id]), ( SELECT TOP(1) [w0].[Id] FROM [Weapons] AS [w0] WHERE [g].[FullName] = [w0].[OwnerFullName] ORDER BY [w0].[Id])) FROM [Gears] AS [g]"); } public override async Task Select_subquery_boolean_empty(bool async) { await base.Select_subquery_boolean_empty(async); AssertSql( @"SELECT COALESCE(( SELECT TOP(1) [w].[IsAutomatic] FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[Name] = N'BFG') ORDER BY [w].[Id]), CAST(0 AS bit)) FROM [Gears] AS [g]"); } public override async Task Select_subquery_boolean_empty_with_pushdown(bool async) { await base.Select_subquery_boolean_empty_with_pushdown(async); AssertSql( @"SELECT ( SELECT TOP(1) [w].[IsAutomatic] FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[Name] = N'BFG') ORDER BY [w].[Id]) FROM [Gears] AS [g]"); } public override async Task Select_subquery_distinct_singleordefault_boolean1(bool async) { await base.Select_subquery_distinct_singleordefault_boolean1(async); AssertSql( @"SELECT COALESCE(( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT DISTINCT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[Name] LIKE N'%Lancer%') ) AS [t]), CAST(0 AS bit)) FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(1 AS bit)"); } public override async Task Select_subquery_distinct_singleordefault_boolean2(bool async) { await base.Select_subquery_distinct_singleordefault_boolean2(async); AssertSql( @"SELECT COALESCE(( SELECT DISTINCT TOP(1) [w].[IsAutomatic] FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[Name] LIKE N'%Lancer%')), CAST(0 AS bit)) FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(1 AS bit)"); } public override async Task Select_subquery_distinct_singleordefault_boolean_with_pushdown(bool async) { await base.Select_subquery_distinct_singleordefault_boolean_with_pushdown(async); AssertSql( @"SELECT ( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT DISTINCT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[Name] LIKE N'%Lancer%') ) AS [t]) FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(1 AS bit)"); } public override async Task Select_subquery_distinct_singleordefault_boolean_empty1(bool async) { await base.Select_subquery_distinct_singleordefault_boolean_empty1(async); AssertSql( @"SELECT COALESCE(( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT DISTINCT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[Name] = N'BFG') ) AS [t]), CAST(0 AS bit)) FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(1 AS bit)"); } public override async Task Select_subquery_distinct_singleordefault_boolean_empty2(bool async) { await base.Select_subquery_distinct_singleordefault_boolean_empty2(async); AssertSql( @"SELECT COALESCE(( SELECT DISTINCT TOP(1) [w].[IsAutomatic] FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[Name] = N'BFG')), CAST(0 AS bit)) FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(1 AS bit)"); } public override async Task Select_subquery_distinct_singleordefault_boolean_empty_with_pushdown(bool async) { await base.Select_subquery_distinct_singleordefault_boolean_empty_with_pushdown(async); AssertSql( @"SELECT ( SELECT TOP(1) [t].[IsAutomatic] FROM ( SELECT DISTINCT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[Name] = N'BFG') ) AS [t]) FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] = CAST(1 AS bit)"); } public override async Task Cast_subquery_to_base_type_using_typed_ToList(bool async) { await base.Cast_subquery_to_base_type_using_typed_ToList(async); AssertSql( @"SELECT [c].[Name], [g].[CityOfBirthName], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Nickname], [g].[Rank], [g].[SquadId] FROM [Cities] AS [c] LEFT JOIN [Gears] AS [g] ON [c].[Name] = [g].[AssignedCityName] WHERE [c].[Name] = N'Ephyra' ORDER BY [c].[Name], [g].[Nickname]"); } public override async Task Cast_ordered_subquery_to_base_type_using_typed_ToArray(bool async) { await base.Cast_ordered_subquery_to_base_type_using_typed_ToArray(async); AssertSql( @"SELECT [c].[Name], [t].[CityOfBirthName], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Nickname], [t].[Rank], [t].[SquadId] FROM [Cities] AS [c] LEFT JOIN ( SELECT [g].[CityOfBirthName], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Nickname], [g].[Rank], [g].[SquadId], [g].[AssignedCityName] FROM [Gears] AS [g] ) AS [t] ON [c].[Name] = [t].[AssignedCityName] WHERE [c].[Name] = N'Ephyra' ORDER BY [c].[Name], [t].[Nickname] DESC"); } public override async Task Correlated_collection_with_complex_order_by_funcletized_to_constant_bool(bool async) { await base.Correlated_collection_with_complex_order_by_funcletized_to_constant_bool(async); AssertSql( @"SELECT [g].[Nickname], [g].[FullName] FROM [Gears] AS [g] WHERE [g].[Discriminator] IN (N'Officer', N'Gear') ORDER BY [g].[Nickname], [g].[SquadId], [g].[FullName]", // @"SELECT [t].[c], [t].[Nickname], [t].[SquadId], [t].[FullName], [g.Weapons].[Name], [g.Weapons].[OwnerFullName] FROM [Weapons] AS [g.Weapons] INNER JOIN ( SELECT CAST(0 AS bit) AS [c], [g0].[Nickname], [g0].[SquadId], [g0].[FullName] FROM [Gears] AS [g0] WHERE [g0].[Discriminator] IN (N'Officer', N'Gear') ) AS [t] ON [g.Weapons].[OwnerFullName] = [t].[FullName] ORDER BY [t].[c] DESC, [t].[Nickname], [t].[SquadId], [t].[FullName]"); } public override async Task Double_order_by_on_nullable_bool_coming_from_optional_navigation(bool async) { await base.Double_order_by_on_nullable_bool_coming_from_optional_navigation(async); AssertSql( @"SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id] ORDER BY [w0].[IsAutomatic], [w0].[Id]"); } public override async Task Double_order_by_on_Like(bool async) { await base.Double_order_by_on_Like(async); AssertSql( @"SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id] ORDER BY CASE WHEN [w0].[Name] LIKE N'%Lancer' THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END"); } public override async Task Double_order_by_on_is_null(bool async) { await base.Double_order_by_on_is_null(async); AssertSql( @"SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id] ORDER BY CASE WHEN [w0].[Name] IS NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END"); } public override async Task Double_order_by_on_string_compare(bool async) { await base.Double_order_by_on_string_compare(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] ORDER BY CASE WHEN ([w].[Name] = N'Marcus'' Lancer') AND [w].[Name] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, [w].[Id]"); } public override async Task Double_order_by_binary_expression(bool async) { await base.Double_order_by_binary_expression(async); AssertSql( @"SELECT [w].[Id] + 2 AS [Binary] FROM [Weapons] AS [w] ORDER BY [w].[Id] + 2"); } public override async Task String_compare_with_null_conditional_argument(bool async) { await base.String_compare_with_null_conditional_argument(async); AssertSql( @"SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id] ORDER BY CASE WHEN ([w0].[Name] = N'Marcus'' Lancer') AND [w0].[Name] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END"); } public override async Task String_compare_with_null_conditional_argument2(bool async) { await base.String_compare_with_null_conditional_argument2(async); AssertSql( @"SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id] ORDER BY CASE WHEN (N'Marcus'' Lancer' = [w0].[Name]) AND [w0].[Name] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END"); } public override async Task String_concat_with_null_conditional_argument(bool async) { await base.String_concat_with_null_conditional_argument(async); AssertSql( @"SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id] ORDER BY COALESCE([w0].[Name], N'') + CAST(5 AS nvarchar(max))"); } public override async Task String_concat_with_null_conditional_argument2(bool async) { await base.String_concat_with_null_conditional_argument2(async); AssertSql( @"SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id] ORDER BY COALESCE([w0].[Name], N'') + N'Marcus'' Lancer'"); } public override async Task String_concat_on_various_types(bool async) { await base.String_concat_on_various_types(async); AssertSql( ""); } public override async Task Time_of_day_datetimeoffset(bool async) { await base.Time_of_day_datetimeoffset(async); AssertSql( @"SELECT CONVERT(time, [m].[Timeline]) FROM [Missions] AS [m]"); } public override async Task GroupBy_Property_Include_Select_Average(bool async) { await base.GroupBy_Property_Include_Select_Average(async); AssertSql( @"SELECT AVG(CAST([g].[SquadId] AS float)) FROM [Gears] AS [g] GROUP BY [g].[Rank]"); } public override async Task GroupBy_Property_Include_Select_Sum(bool async) { await base.GroupBy_Property_Include_Select_Sum(async); AssertSql( @"SELECT COALESCE(SUM([g].[SquadId]), 0) FROM [Gears] AS [g] GROUP BY [g].[Rank]"); } public override async Task GroupBy_Property_Include_Select_Count(bool async) { await base.GroupBy_Property_Include_Select_Count(async); AssertSql( @"SELECT COUNT(*) FROM [Gears] AS [g] GROUP BY [g].[Rank]"); } public override async Task GroupBy_Property_Include_Select_LongCount(bool async) { await base.GroupBy_Property_Include_Select_LongCount(async); AssertSql( @"SELECT COUNT_BIG(*) FROM [Gears] AS [g] GROUP BY [g].[Rank]"); } public override async Task GroupBy_Property_Include_Select_Min(bool async) { await base.GroupBy_Property_Include_Select_Min(async); AssertSql( @"SELECT MIN([g].[SquadId]) FROM [Gears] AS [g] GROUP BY [g].[Rank]"); } public override async Task GroupBy_Property_Include_Aggregate_with_anonymous_selector(bool async) { await base.GroupBy_Property_Include_Aggregate_with_anonymous_selector(async); AssertSql( @"SELECT [g].[Nickname] AS [Key], COUNT(*) AS [c] FROM [Gears] AS [g] GROUP BY [g].[Nickname] ORDER BY [g].[Nickname]"); } public override async Task Group_by_with_include_with_entity_in_result_selector(bool async) { await base.Group_by_with_include_with_entity_in_result_selector(async); AssertSql( @"SELECT [t].[Rank], [t].[c], [t0].[Nickname], [t0].[SquadId], [t0].[AssignedCityName], [t0].[CityOfBirthName], [t0].[Discriminator], [t0].[FullName], [t0].[HasSoulPatch], [t0].[LeaderNickname], [t0].[LeaderSquadId], [t0].[Rank], [t0].[Name], [t0].[Location], [t0].[Nation] FROM ( SELECT [g].[Rank], COUNT(*) AS [c] FROM [Gears] AS [g] GROUP BY [g].[Rank] ) AS [t] LEFT JOIN ( SELECT [t1].[Nickname], [t1].[SquadId], [t1].[AssignedCityName], [t1].[CityOfBirthName], [t1].[Discriminator], [t1].[FullName], [t1].[HasSoulPatch], [t1].[LeaderNickname], [t1].[LeaderSquadId], [t1].[Rank], [t1].[Name], [t1].[Location], [t1].[Nation] FROM ( SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank], [c].[Name], [c].[Location], [c].[Nation], ROW_NUMBER() OVER(PARTITION BY [g0].[Rank] ORDER BY [g0].[Nickname]) AS [row] FROM [Gears] AS [g0] INNER JOIN [Cities] AS [c] ON [g0].[CityOfBirthName] = [c].[Name] ) AS [t1] WHERE [t1].[row] <= 1 ) AS [t0] ON [t].[Rank] = [t0].[Rank] ORDER BY [t].[Rank]"); } public override async Task GroupBy_Property_Include_Select_Max(bool async) { await base.GroupBy_Property_Include_Select_Max(async); AssertSql( @"SELECT MAX([g].[SquadId]) FROM [Gears] AS [g] GROUP BY [g].[Rank]"); } public override async Task Include_with_group_by_and_FirstOrDefault_gets_properly_applied(bool async) { await base.Include_with_group_by_and_FirstOrDefault_gets_properly_applied(async); AssertSql( @"SELECT [t0].[Nickname], [t0].[SquadId], [t0].[AssignedCityName], [t0].[CityOfBirthName], [t0].[Discriminator], [t0].[FullName], [t0].[HasSoulPatch], [t0].[LeaderNickname], [t0].[LeaderSquadId], [t0].[Rank], [t0].[Name], [t0].[Location], [t0].[Nation] FROM ( SELECT [g].[Rank] FROM [Gears] AS [g] GROUP BY [g].[Rank] ) AS [t] LEFT JOIN ( SELECT [t1].[Nickname], [t1].[SquadId], [t1].[AssignedCityName], [t1].[CityOfBirthName], [t1].[Discriminator], [t1].[FullName], [t1].[HasSoulPatch], [t1].[LeaderNickname], [t1].[LeaderSquadId], [t1].[Rank], [t1].[Name], [t1].[Location], [t1].[Nation] FROM ( SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank], [c].[Name], [c].[Location], [c].[Nation], ROW_NUMBER() OVER(PARTITION BY [g0].[Rank] ORDER BY [g0].[Nickname], [g0].[SquadId], [c].[Name]) AS [row] FROM [Gears] AS [g0] INNER JOIN [Cities] AS [c] ON [g0].[CityOfBirthName] = [c].[Name] WHERE [g0].[HasSoulPatch] = CAST(1 AS bit) ) AS [t1] WHERE [t1].[row] <= 1 ) AS [t0] ON [t].[Rank] = [t0].[Rank]"); } public override async Task Include_collection_with_Cast_to_base(bool async) { await base.Include_collection_with_Cast_to_base(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Include_with_client_method_and_member_access_still_applies_includes(bool async) { await base.Include_with_client_method_and_member_access_still_applies_includes(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId])"); } public override async Task Include_with_projection_of_unmapped_property_still_gets_applied(bool async) { await base.Include_with_projection_of_unmapped_property_still_gets_applied(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Multiple_includes_with_client_method_around_entity_and_also_projecting_included_collection() { await base.Multiple_includes_with_client_method_around_entity_and_also_projecting_included_collection(); AssertSql( @"SELECT [s].[Name], [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank], [t].[Id], [t].[AmmunitionType], [t].[IsAutomatic], [t].[Name], [t].[OwnerFullName], [t].[SynergyWithId] FROM [Squads] AS [s] LEFT JOIN ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] ) AS [t] ON [s].[Id] = [t].[SquadId] WHERE [s].[Name] = N'Delta' ORDER BY [s].[Id], [t].[Nickname], [t].[SquadId]"); } public override async Task OrderBy_same_expression_containing_IsNull_correctly_deduplicates_the_ordering(bool async) { await base.OrderBy_same_expression_containing_IsNull_correctly_deduplicates_the_ordering(async); AssertSql( @"SELECT CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN CASE WHEN CAST(LEN([g].[Nickname]) AS int) = 5 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END ELSE NULL END FROM [Gears] AS [g] ORDER BY CASE WHEN CASE WHEN [g].[LeaderNickname] IS NOT NULL THEN CASE WHEN CAST(LEN([g].[Nickname]) AS int) = 5 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END ELSE NULL END IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END"); } public override async Task GetValueOrDefault_in_projection(bool async) { await base.GetValueOrDefault_in_projection(async); AssertSql( @"SELECT COALESCE([w].[SynergyWithId], 0) FROM [Weapons] AS [w]"); } public override async Task GetValueOrDefault_in_filter(bool async) { await base.GetValueOrDefault_in_filter(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE COALESCE([w].[SynergyWithId], 0) = 0"); } public override async Task GetValueOrDefault_in_filter_non_nullable_column(bool async) { await base.GetValueOrDefault_in_filter_non_nullable_column(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE COALESCE([w].[Id], 0) = 0"); } public override async Task GetValueOrDefault_in_order_by(bool async) { await base.GetValueOrDefault_in_order_by(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] ORDER BY COALESCE([w].[SynergyWithId], 0), [w].[Id]"); } public override async Task GetValueOrDefault_with_argument(bool async) { await base.GetValueOrDefault_with_argument(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE COALESCE([w].[SynergyWithId], [w].[Id]) = 1"); } public override async Task GetValueOrDefault_with_argument_complex(bool async) { await base.GetValueOrDefault_with_argument_complex(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE COALESCE([w].[SynergyWithId], CAST(LEN([w].[Name]) AS int) + 42) > 10"); } public override async Task Filter_with_complex_predicate_containing_subquery(bool async) { await base.Filter_with_complex_predicate_containing_subquery(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[FullName] <> N'Dom') AND EXISTS ( SELECT 1 FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[IsAutomatic] = CAST(1 AS bit)))"); } public override async Task Query_with_complex_let_containing_ordering_and_filter_projecting_firstOrDefault_element_of_let( bool async) { await base.Query_with_complex_let_containing_ordering_and_filter_projecting_firstOrDefault_element_of_let(async); AssertSql( @"SELECT [g].[Nickname], ( SELECT TOP(1) [w].[Name] FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[IsAutomatic] = CAST(1 AS bit)) ORDER BY [w].[AmmunitionType] DESC) AS [WeaponName] FROM [Gears] AS [g] WHERE [g].[Nickname] <> N'Dom'"); } public override async Task Null_semantics_is_correctly_applied_for_function_comparisons_that_take_arguments_from_optional_navigation(bool async) { await base.Null_semantics_is_correctly_applied_for_function_comparisons_that_take_arguments_from_optional_navigation(async); AssertSql( @""); } public override async Task Null_semantics_is_correctly_applied_for_function_comparisons_that_take_arguments_from_optional_navigation_complex(bool async) { await base.Null_semantics_is_correctly_applied_for_function_comparisons_that_take_arguments_from_optional_navigation_complex( async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) LEFT JOIN [Squads] AS [s] ON [g].[SquadId] = [s].[Id] WHERE (SUBSTRING([t].[Note], 0 + 1, CAST(LEN([s].[Name]) AS int)) = [t].[GearNickName]) OR (([t].[Note] IS NULL OR [s].[Name] IS NULL) AND [t].[GearNickName] IS NULL)"); } public override async Task Filter_with_new_Guid(bool async) { await base.Filter_with_new_Guid(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note] FROM [Tags] AS [t] WHERE [t].[Id] = 'df36f493-463f-4123-83f9-6b135deeb7ba'"); } public override async Task Filter_with_new_Guid_closure(bool async) { await base.Filter_with_new_Guid_closure(async); AssertSql( @"@__p_0='df36f493-463f-4123-83f9-6b135deeb7bd' SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[Note] FROM [Tags] AS [t] WHERE [t].[Id] = @__p_0", // @"@__p_0='b39a6fba-9026-4d69-828e-fd7068673e57' SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[Note] FROM [Tags] AS [t] WHERE [t].[Id] = @__p_0"); } public override async Task OfTypeNav1(bool async) { await base.OfTypeNav1(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) LEFT JOIN [Tags] AS [t0] ON ([g].[Nickname] = [t0].[GearNickName]) AND ([g].[SquadId] = [t0].[GearSquadId]) WHERE ((([t].[Note] <> N'Foo') OR [t].[Note] IS NULL) AND ([g].[Discriminator] = N'Officer')) AND (([t0].[Note] <> N'Bar') OR [t0].[Note] IS NULL)"); } public override async Task OfTypeNav2(bool async) { await base.OfTypeNav2(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) LEFT JOIN [Cities] AS [c] ON [g].[AssignedCityName] = [c].[Name] WHERE ((([t].[Note] <> N'Foo') OR [t].[Note] IS NULL) AND ([g].[Discriminator] = N'Officer')) AND (([c].[Location] <> 'Bar') OR [c].[Location] IS NULL)"); } public override async Task OfTypeNav3(bool async) { await base.OfTypeNav3(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) INNER JOIN [Weapons] AS [w] ON [g].[FullName] = [w].[OwnerFullName] LEFT JOIN [Tags] AS [t0] ON ([g].[Nickname] = [t0].[GearNickName]) AND ([g].[SquadId] = [t0].[GearSquadId]) WHERE ((([t].[Note] <> N'Foo') OR [t].[Note] IS NULL) AND ([g].[Discriminator] = N'Officer')) AND (([t0].[Note] <> N'Bar') OR [t0].[Note] IS NULL)"); } public override void Nav_rewrite_Distinct_with_convert() { base.Nav_rewrite_Distinct_with_convert(); AssertSql( @""); } public override void Nav_rewrite_Distinct_with_convert_anonymous() { base.Nav_rewrite_Distinct_with_convert_anonymous(); AssertSql( @""); } public override async Task Nav_rewrite_with_convert1(bool async) { await base.Nav_rewrite_with_convert1(async); AssertSql( @"SELECT [t].[Name], [t].[Discriminator], [t].[LocustHordeId], [t].[ThreatLevel], [t].[ThreatLevelByte], [t].[ThreatLevelNullableByte], [t].[DefeatedByNickname], [t].[DefeatedBySquadId], [t].[HighCommandId] FROM [Factions] AS [f] LEFT JOIN [Cities] AS [c] ON [f].[CapitalName] = [c].[Name] LEFT JOIN ( SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name] WHERE ([c].[Name] <> N'Foo') OR [c].[Name] IS NULL"); } public override async Task Nav_rewrite_with_convert2(bool async) { await base.Nav_rewrite_with_convert2(async); AssertSql( @"SELECT [f].[Id], [f].[CapitalName], [f].[Discriminator], [f].[Name], [f].[ServerAddress], [f].[CommanderName], [f].[Eradicated] FROM [Factions] AS [f] LEFT JOIN [Cities] AS [c] ON [f].[CapitalName] = [c].[Name] LEFT JOIN ( SELECT [l].[Name] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name] WHERE (([c].[Name] <> N'Foo') OR [c].[Name] IS NULL) AND (([t].[Name] <> N'Bar') OR [t].[Name] IS NULL)"); } public override async Task Nav_rewrite_with_convert3(bool async) { await base.Nav_rewrite_with_convert3(async); AssertSql( @"SELECT [f].[Id], [f].[CapitalName], [f].[Discriminator], [f].[Name], [f].[ServerAddress], [f].[CommanderName], [f].[Eradicated] FROM [Factions] AS [f] LEFT JOIN [Cities] AS [c] ON [f].[CapitalName] = [c].[Name] LEFT JOIN ( SELECT [l].[Name] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name] WHERE (([c].[Name] <> N'Foo') OR [c].[Name] IS NULL) AND (([t].[Name] <> N'Bar') OR [t].[Name] IS NULL)"); } public override async Task Where_contains_on_navigation_with_composite_keys(bool async) { await base.Where_contains_on_navigation_with_composite_keys(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[Discriminator] IN (N'Gear', N'Officer') AND EXISTS ( SELECT 1 FROM [Cities] AS [c] WHERE EXISTS ( SELECT 1 FROM [Gears] AS [g0] WHERE ([g0].[Discriminator] IN (N'Gear', N'Officer') AND ([c].[Name] = [g0].[CityOfBirthName])) AND (([g0].[Nickname] = [g].[Nickname]) AND ([g0].[SquadId] = [g].[SquadId]))))"); } public override async Task Include_with_complex_order_by(bool async) { await base.Include_with_complex_order_by(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w0] ON [g].[FullName] = [w0].[OwnerFullName] ORDER BY ( SELECT TOP(1) [w].[Name] FROM [Weapons] AS [w] WHERE ([g].[FullName] = [w].[OwnerFullName]) AND ([w].[Name] LIKE N'%Gnasher%')), [g].[Nickname], [g].[SquadId]"); } public override async Task Anonymous_projection_take_followed_by_projecting_single_element_from_collection_navigation(bool async) { await base.Anonymous_projection_take_followed_by_projecting_single_element_from_collection_navigation(async); AssertSql( @""); } public override async Task Bool_projection_from_subquery_treated_appropriately_in_where(bool async) { await base.Bool_projection_from_subquery_treated_appropriately_in_where(async); AssertSql( @"SELECT [c].[Name], [c].[Location], [c].[Nation] FROM [Cities] AS [c] WHERE ( SELECT TOP(1) [g].[HasSoulPatch] FROM [Gears] AS [g] ORDER BY [g].[Nickname], [g].[SquadId]) = CAST(1 AS bit)"); } public override async Task DateTimeOffset_Contains_Less_than_Greater_than(bool async) { await base.DateTimeOffset_Contains_Less_than_Greater_than(async); AssertSql( @"@__start_0='1902-01-01T10:00:00.1234567+01:30' @__end_1='1902-01-03T10:00:00.1234567+01:30' SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE ((@__start_0 <= CAST(CONVERT(date, [m].[Timeline]) AS datetimeoffset)) AND ([m].[Timeline] < @__end_1)) AND ([m].[Timeline] = '1902-01-02T10:00:00.1234567+01:30')"); } public override async Task Navigation_inside_interpolated_string_expanded(bool async) { await base.Navigation_inside_interpolated_string_expanded(async); AssertSql( @"SELECT CASE WHEN [w].[SynergyWithId] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, [w0].[OwnerFullName] FROM [Weapons] AS [w] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id]"); } public override async Task Left_join_projection_using_coalesce_tracking(bool async) { await base.Left_join_projection_using_coalesce_tracking(async); AssertSql( @"SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON [g].[LeaderNickname] = [g0].[Nickname]"); } public override async Task Left_join_projection_using_conditional_tracking(bool async) { await base.Left_join_projection_using_conditional_tracking(async); AssertSql( @"SELECT CASE WHEN [g0].[Nickname] IS NULL OR [g0].[SquadId] IS NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g] LEFT JOIN [Gears] AS [g0] ON [g].[LeaderNickname] = [g0].[Nickname]"); } public override async Task Project_collection_navigation_nested_with_take_composite_key(bool async) { await base.Project_collection_navigation_nested_with_take_composite_key(async); AssertSql( @"SELECT [t].[Id], [g].[Nickname], [g].[SquadId], [t0].[Nickname], [t0].[SquadId], [t0].[AssignedCityName], [t0].[CityOfBirthName], [t0].[Discriminator], [t0].[FullName], [t0].[HasSoulPatch], [t0].[LeaderNickname], [t0].[LeaderSquadId], [t0].[Rank] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) LEFT JOIN ( SELECT [t1].[Nickname], [t1].[SquadId], [t1].[AssignedCityName], [t1].[CityOfBirthName], [t1].[Discriminator], [t1].[FullName], [t1].[HasSoulPatch], [t1].[LeaderNickname], [t1].[LeaderSquadId], [t1].[Rank] FROM ( SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank], ROW_NUMBER() OVER(PARTITION BY [g0].[LeaderNickname], [g0].[LeaderSquadId] ORDER BY [g0].[Nickname], [g0].[SquadId]) AS [row] FROM [Gears] AS [g0] ) AS [t1] WHERE [t1].[row] <= 50 ) AS [t0] ON (([g].[Nickname] = [t0].[LeaderNickname]) OR ([g].[Nickname] IS NULL AND [t0].[LeaderNickname] IS NULL)) AND ([g].[SquadId] = [t0].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY [t].[Id], [g].[Nickname], [g].[SquadId], [t0].[LeaderNickname], [t0].[LeaderSquadId], [t0].[Nickname], [t0].[SquadId]"); } public override async Task Project_collection_navigation_nested_composite_key(bool async) { await base.Project_collection_navigation_nested_composite_key(async); AssertSql( @"SELECT [t].[Id], [g].[Nickname], [g].[SquadId], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) LEFT JOIN [Gears] AS [g0] ON (([g].[Nickname] = [g0].[LeaderNickname]) OR ([g].[Nickname] IS NULL AND [g0].[LeaderNickname] IS NULL)) AND ([g].[SquadId] = [g0].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer' ORDER BY [t].[Id], [g].[Nickname], [g].[SquadId], [g0].[Nickname]"); } public override async Task Null_checks_in_correlated_predicate_are_correctly_translated(bool async) { await base.Null_checks_in_correlated_predicate_are_correctly_translated(async); AssertSql( @"SELECT [t].[Id], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) ORDER BY [t].[Id], [g].[Nickname]"); } public override async Task SelectMany_Where_DefaultIfEmpty_with_navigation_in_the_collection_selector(bool async) { await base.SelectMany_Where_DefaultIfEmpty_with_navigation_in_the_collection_selector(async); AssertSql( @"@__isAutomatic_0='True' SELECT [g].[Nickname], [g].[FullName], CASE WHEN [t].[Id] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [Collection] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w].[Id], [w].[OwnerFullName] FROM [Weapons] AS [w] WHERE [w].[IsAutomatic] = @__isAutomatic_0 ) AS [t] ON [g].[FullName] = [t].[OwnerFullName]"); } public override async Task SelectMany_Where_DefaultIfEmpty_with_navigation_in_the_collection_selector_not_equal(bool async) { await base.SelectMany_Where_DefaultIfEmpty_with_navigation_in_the_collection_selector_not_equal(async); AssertSql( @"@__isAutomatic_0='True' SELECT [g].[Nickname], [g].[FullName], CASE WHEN [t].[Id] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [Collection] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w].[Id], [w].[OwnerFullName] FROM [Weapons] AS [w] WHERE [w].[IsAutomatic] <> @__isAutomatic_0 ) AS [t] ON [g].[FullName] = [t].[OwnerFullName]"); } public override async Task SelectMany_Where_DefaultIfEmpty_with_navigation_in_the_collection_selector_order_comparison(bool async) { await base.SelectMany_Where_DefaultIfEmpty_with_navigation_in_the_collection_selector_order_comparison(async); AssertSql( @"@__prm_0='1' SELECT [g].[Nickname], [g].[FullName], CASE WHEN [t].[Id] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [Collection] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w].[Id], [w].[OwnerFullName] FROM [Weapons] AS [w] WHERE [w].[Id] > @__prm_0 ) AS [t] ON [g].[FullName] = [t].[OwnerFullName]"); } public override async Task Join_with_inner_being_a_subquery_projecting_single_property(bool async) { await base.Join_with_inner_being_a_subquery_projecting_single_property(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] INNER JOIN [Gears] AS [g0] ON [g].[Nickname] = [g0].[Nickname]"); } public override async Task Join_with_inner_being_a_subquery_projecting_anonymous_type_with_single_property(bool async) { await base.Join_with_inner_being_a_subquery_projecting_anonymous_type_with_single_property(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] INNER JOIN [Gears] AS [g0] ON [g].[Nickname] = [g0].[Nickname]"); } public override async Task Navigation_based_on_complex_expression1(bool async) { await base.Navigation_based_on_complex_expression1(async); AssertSql( @""); } public override async Task Navigation_based_on_complex_expression2(bool async) { await base.Navigation_based_on_complex_expression2(async); AssertSql( @"SELECT [f].[Id], [f].[CapitalName], [f].[Discriminator], [f].[Name], [f].[ServerAddress], [f].[CommanderName], [f].[Eradicated] FROM [Factions] AS [f] LEFT JOIN ( SELECT [l].[Name] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name] WHERE [t].[Name] IS NOT NULL"); } public override async Task Navigation_based_on_complex_expression3(bool async) { await base.Navigation_based_on_complex_expression3(async); AssertSql( @"SELECT [t].[Name], [t].[Discriminator], [t].[LocustHordeId], [t].[ThreatLevel], [t].[ThreatLevelByte], [t].[ThreatLevelNullableByte], [t].[DefeatedByNickname], [t].[DefeatedBySquadId], [t].[HighCommandId] FROM [Factions] AS [f] LEFT JOIN ( SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander' ) AS [t] ON [f].[CommanderName] = [t].[Name]"); } public override async Task Navigation_based_on_complex_expression4(bool async) { await base.Navigation_based_on_complex_expression4(async); AssertSql( @""); } public override async Task Navigation_based_on_complex_expression5(bool async) { await base.Navigation_based_on_complex_expression5(async); AssertSql( @""); } public override async Task Navigation_based_on_complex_expression6(bool async) { await base.Navigation_based_on_complex_expression6(async); AssertSql( @""); } public override async Task Select_as_operator(bool async) { await base.Select_as_operator(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l]"); } public override async Task Select_datetimeoffset_comparison_in_projection(bool async) { await base.Select_datetimeoffset_comparison_in_projection(async); AssertSql( @"SELECT CASE WHEN [m].[Timeline] > SYSDATETIMEOFFSET() THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END FROM [Missions] AS [m]"); } public override async Task OfType_in_subquery_works(bool async) { await base.OfType_in_subquery_works(async); AssertSql( @"SELECT [t].[Name], [t].[Location], [t].[Nation] FROM [Gears] AS [g] INNER JOIN ( SELECT [c].[Name], [c].[Location], [c].[Nation], [g0].[LeaderNickname], [g0].[LeaderSquadId] FROM [Gears] AS [g0] LEFT JOIN [Cities] AS [c] ON [g0].[AssignedCityName] = [c].[Name] WHERE [g0].[Discriminator] = N'Officer' ) AS [t] ON ([g].[Nickname] = [t].[LeaderNickname]) AND ([g].[SquadId] = [t].[LeaderSquadId]) WHERE [g].[Discriminator] = N'Officer'"); } public override async Task Nullable_bool_comparison_is_translated_to_server(bool async) { await base.Nullable_bool_comparison_is_translated_to_server(async); AssertSql( @"SELECT CASE WHEN ([f].[Eradicated] = CAST(1 AS bit)) AND ([f].[Eradicated] IS NOT NULL) THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [IsEradicated] FROM [Factions] AS [f]"); } public override async Task Accessing_reference_navigation_collection_composition_generates_single_query(bool async) { await base.Accessing_reference_navigation_collection_composition_generates_single_query(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Id], [t].[IsAutomatic], [t].[Name], [t].[Id0] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w].[Id], [w].[IsAutomatic], [w0].[Name], [w0].[Id] AS [Id0], [w].[OwnerFullName] FROM [Weapons] AS [w] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id] ) AS [t] ON [g].[FullName] = [t].[OwnerFullName] ORDER BY [g].[Nickname], [g].[SquadId], [t].[Id]"); } public override async Task Reference_include_chain_loads_correctly_when_middle_is_null(bool async) { await base.Reference_include_chain_loads_correctly_when_middle_is_null(async); AssertSql( @"SELECT [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) LEFT JOIN [Squads] AS [s] ON [g].[SquadId] = [s].[Id] ORDER BY [t].[Note]"); } public override async Task Accessing_property_of_optional_navigation_in_child_projection_works(bool async) { await base.Accessing_property_of_optional_navigation_in_child_projection_works(async); AssertSql( @"SELECT CASE WHEN [g].[Nickname] IS NOT NULL AND [g].[SquadId] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, [t].[Id], [g].[Nickname], [g].[SquadId], [t0].[Nickname], [t0].[Id], [t0].[SquadId] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) LEFT JOIN ( SELECT [g0].[Nickname], [w].[Id], [g0].[SquadId], [w].[OwnerFullName] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g0] ON [w].[OwnerFullName] = [g0].[FullName] ) AS [t0] ON [g].[FullName] = [t0].[OwnerFullName] ORDER BY [t].[Note], [t].[Id], [g].[Nickname], [g].[SquadId], [t0].[Id], [t0].[Nickname]"); } public override async Task Collection_navigation_ofType_filter_works(bool async) { await base.Collection_navigation_ofType_filter_works(async); AssertSql( @"SELECT [c].[Name], [c].[Location], [c].[Nation] FROM [Cities] AS [c] WHERE EXISTS ( SELECT 1 FROM [Gears] AS [g] WHERE (([c].[Name] = [g].[CityOfBirthName]) AND ([g].[Discriminator] = N'Officer')) AND ([g].[Nickname] = N'Marcus'))"); } public override async Task Query_reusing_parameter_doesnt_declare_duplicate_parameter(bool async) { await base.Query_reusing_parameter_doesnt_declare_duplicate_parameter(async); AssertSql( @"@__prm_Inner_Nickname_0='Marcus' (Size = 450) SELECT [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank] FROM ( SELECT DISTINCT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Nickname] <> @__prm_Inner_Nickname_0) AND ([g].[Nickname] <> @__prm_Inner_Nickname_0) ) AS [t] ORDER BY [t].[FullName]"); } public override async Task Query_reusing_parameter_with_inner_query_doesnt_declare_duplicate_parameter(bool async) { await base.Query_reusing_parameter_with_inner_query_doesnt_declare_duplicate_parameter(async); AssertSql( @"@__squadId_0='1' SELECT [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank] FROM ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] INNER JOIN [Squads] AS [s] ON [g].[SquadId] = [s].[Id] WHERE EXISTS ( SELECT 1 FROM [Squads] AS [s0] WHERE ([s0].[Id] = @__squadId_0) AND ([s0].[Id] = [s].[Id])) UNION ALL SELECT [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g0] INNER JOIN [Squads] AS [s1] ON [g0].[SquadId] = [s1].[Id] WHERE EXISTS ( SELECT 1 FROM [Squads] AS [s2] WHERE ([s2].[Id] = @__squadId_0) AND ([s2].[Id] = [s1].[Id])) ) AS [t] ORDER BY [t].[FullName]"); } public override async Task Query_reusing_parameter_with_inner_query_expression_doesnt_declare_duplicate_parameter(bool async) { await base.Query_reusing_parameter_with_inner_query_expression_doesnt_declare_duplicate_parameter(async); AssertSql( @"@__gearId_0='1' SELECT [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Squads] AS [s] WHERE EXISTS ( SELECT 1 FROM [Gears] AS [g] WHERE (([s].[Id] = [g].[SquadId]) AND ([g].[SquadId] = @__gearId_0)) AND ([g].[SquadId] = @__gearId_0))"); } public override async Task Query_reusing_parameter_doesnt_declare_duplicate_parameter_complex(bool async) { await base.Query_reusing_parameter_doesnt_declare_duplicate_parameter_complex(async); AssertSql( @"@__entity_equality_prm_Inner_Squad_0_Id='1' (Nullable = true) SELECT [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank] FROM ( SELECT DISTINCT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] INNER JOIN [Squads] AS [s] ON [g].[SquadId] = [s].[Id] WHERE [s].[Id] = @__entity_equality_prm_Inner_Squad_0_Id ) AS [t] INNER JOIN [Squads] AS [s0] ON [t].[SquadId] = [s0].[Id] WHERE [s0].[Id] = @__entity_equality_prm_Inner_Squad_0_Id ORDER BY [t].[FullName]"); } public override async Task Complex_GroupBy_after_set_operator(bool async) { await base.Complex_GroupBy_after_set_operator(async); AssertSql( @"SELECT [t].[Name], [t].[Count], COALESCE(SUM([t].[Count]), 0) AS [Sum] FROM ( SELECT [c].[Name], ( SELECT COUNT(*) FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName]) AS [Count] FROM [Gears] AS [g] LEFT JOIN [Cities] AS [c] ON [g].[AssignedCityName] = [c].[Name] UNION ALL SELECT [c0].[Name], ( SELECT COUNT(*) FROM [Weapons] AS [w0] WHERE [g0].[FullName] = [w0].[OwnerFullName]) AS [Count] FROM [Gears] AS [g0] INNER JOIN [Cities] AS [c0] ON [g0].[CityOfBirthName] = [c0].[Name] ) AS [t] GROUP BY [t].[Name], [t].[Count]"); } public override async Task Complex_GroupBy_after_set_operator_using_result_selector(bool async) { await base.Complex_GroupBy_after_set_operator_using_result_selector(async); AssertSql( @"SELECT [t].[Name], [t].[Count], COALESCE(SUM([t].[Count]), 0) AS [Sum] FROM ( SELECT [c].[Name], ( SELECT COUNT(*) FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName]) AS [Count] FROM [Gears] AS [g] LEFT JOIN [Cities] AS [c] ON [g].[AssignedCityName] = [c].[Name] UNION ALL SELECT [c0].[Name], ( SELECT COUNT(*) FROM [Weapons] AS [w0] WHERE [g0].[FullName] = [w0].[OwnerFullName]) AS [Count] FROM [Gears] AS [g0] INNER JOIN [Cities] AS [c0] ON [g0].[CityOfBirthName] = [c0].[Name] ) AS [t] GROUP BY [t].[Name], [t].[Count]"); } public override async Task Left_join_with_GroupBy_with_composite_group_key(bool async) { await base.Left_join_with_GroupBy_with_composite_group_key(async); AssertSql( @"SELECT [g].[CityOfBirthName], [g].[HasSoulPatch] FROM [Gears] AS [g] INNER JOIN [Squads] AS [s] ON [g].[SquadId] = [s].[Id] LEFT JOIN [Tags] AS [t] ON [g].[Nickname] = [t].[GearNickName] GROUP BY [g].[CityOfBirthName], [g].[HasSoulPatch]"); } public override async Task GroupBy_with_boolean_grouping_key(bool async) { await base.GroupBy_with_boolean_grouping_key(async); AssertSql( @"SELECT [g].[CityOfBirthName], [g].[HasSoulPatch], CASE WHEN [g].[Nickname] = N'Marcus' THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [IsMarcus], COUNT(*) AS [Count] FROM [Gears] AS [g] GROUP BY [g].[CityOfBirthName], [g].[HasSoulPatch], CASE WHEN [g].[Nickname] = N'Marcus' THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END"); } public override async Task GroupBy_with_boolean_groupin_key_thru_navigation_access(bool async) { await base.GroupBy_with_boolean_groupin_key_thru_navigation_access(async); AssertSql( @"SELECT [g].[HasSoulPatch], LOWER([s].[Name]) AS [Name] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) LEFT JOIN [Squads] AS [s] ON [g].[SquadId] = [s].[Id] GROUP BY [g].[HasSoulPatch], [s].[Name]"); } public override async Task Group_by_over_projection_with_multiple_properties_accessed_thru_navigation(bool async) { await base.Group_by_over_projection_with_multiple_properties_accessed_thru_navigation(async); AssertSql( @"SELECT [c].[Name] FROM [Gears] AS [g] INNER JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name] GROUP BY [c].[Name]"); } public override async Task Group_by_on_StartsWith_with_null_parameter_as_argument(bool async) { await base.Group_by_on_StartsWith_with_null_parameter_as_argument(async); AssertSql( @"SELECT CAST(0 AS bit) FROM [Gears] AS [g]"); } public override async Task Group_by_with_having_StartsWith_with_null_parameter_as_argument(bool async) { await base.Group_by_with_having_StartsWith_with_null_parameter_as_argument(async); AssertSql( @"SELECT [g].[FullName] FROM [Gears] AS [g] GROUP BY [g].[FullName] HAVING 0 = 1"); } public override async Task Select_StartsWith_with_null_parameter_as_argument(bool async) { await base.Select_StartsWith_with_null_parameter_as_argument(async); AssertSql( @"SELECT CAST(0 AS bit) FROM [Gears] AS [g]"); } public override async Task Select_null_parameter_is_not_null(bool async) { await base.Select_null_parameter_is_not_null(async); AssertSql( @"@__p_0='False' SELECT @__p_0 FROM [Gears] AS [g]"); } public override async Task Where_null_parameter_is_not_null(bool async) { await base.Where_null_parameter_is_not_null(async); AssertSql( @"@__p_0='False' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE @__p_0 = CAST(1 AS bit)"); } public override async Task OrderBy_StartsWith_with_null_parameter_as_argument(bool async) { await base.OrderBy_StartsWith_with_null_parameter_as_argument(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] ORDER BY [g].[Nickname]"); } public override async Task OrderBy_Contains_empty_list(bool async) { await base.OrderBy_Contains_empty_list(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g]"); } public override async Task Where_with_enum_flags_parameter(bool async) { await base.Where_with_enum_flags_parameter(async); AssertSql( @"@__rank_0='1' (Nullable = true) SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Rank] & @__rank_0) = @__rank_0", // @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g]", // @"@__rank_0='2' (Nullable = true) SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Rank] | @__rank_0) <> @__rank_0", // @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE 0 = 1"); } public override async Task FirstOrDefault_navigation_access_entity_equality_in_where_predicate_apply_peneding_selector(bool async) { await base.FirstOrDefault_navigation_access_entity_equality_in_where_predicate_apply_peneding_selector(async); AssertSql( @"SELECT [f].[Id], [f].[CapitalName], [f].[Discriminator], [f].[Name], [f].[ServerAddress], [f].[CommanderName], [f].[Eradicated] FROM [Factions] AS [f] LEFT JOIN [Cities] AS [c] ON [f].[CapitalName] = [c].[Name] WHERE ([c].[Name] = ( SELECT TOP(1) [c0].[Name] FROM [Gears] AS [g] INNER JOIN [Cities] AS [c0] ON [g].[CityOfBirthName] = [c0].[Name] ORDER BY [g].[Nickname])) OR ([c].[Name] IS NULL AND ( SELECT TOP(1) [c0].[Name] FROM [Gears] AS [g] INNER JOIN [Cities] AS [c0] ON [g].[CityOfBirthName] = [c0].[Name] ORDER BY [g].[Nickname]) IS NULL)"); } public override async Task Bitwise_operation_with_non_null_parameter_optimizes_null_checks(bool async) { await base.Bitwise_operation_with_non_null_parameter_optimizes_null_checks(async); AssertSql( @"@__ranks_0='134' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE ([g].[Rank] & @__ranks_0) <> 0", // @"@__ranks_0='134' SELECT CASE WHEN ([g].[Rank] | @__ranks_0) = @__ranks_0 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END FROM [Gears] AS [g]", // @"@__ranks_0='134' SELECT CASE WHEN ([g].[Rank] | ([g].[Rank] | (@__ranks_0 | ([g].[Rank] | @__ranks_0)))) = @__ranks_0 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END FROM [Gears] AS [g]"); } public override async Task Bitwise_operation_with_null_arguments(bool async) { await base.Bitwise_operation_with_null_arguments(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [w].[AmmunitionType] IS NULL", // @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [w].[AmmunitionType] IS NULL", // @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [w].[AmmunitionType] IS NULL", // @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w]", // @"@__prm_0='2' (Nullable = true) SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE (([w].[AmmunitionType] & @__prm_0) <> 0) OR [w].[AmmunitionType] IS NULL", // @"@__prm_0='1' (Nullable = true) SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[AmmunitionType] & @__prm_0) = @__prm_0"); } public override async Task Logical_operation_with_non_null_parameter_optimizes_null_checks(bool async) { await base.Logical_operation_with_non_null_parameter_optimizes_null_checks(async); AssertSql( @"@__prm_0='True' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] <> @__prm_0", // @"@__prm_0='False' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE [g].[HasSoulPatch] <> @__prm_0"); } public override async Task Cast_OfType_works_correctly(bool async) { await base.Cast_OfType_works_correctly(async); AssertSql( @"SELECT [g].[FullName] FROM [Gears] AS [g] WHERE [g].[Discriminator] = N'Officer'"); } public override async Task Join_inner_source_custom_projection_followed_by_filter(bool async) { await base.Join_inner_source_custom_projection_followed_by_filter(async); AssertSql( @"SELECT CASE WHEN [f].[Name] = N'Locust' THEN CAST(1 AS bit) ELSE NULL END AS [IsEradicated], [f].[CommanderName], [f].[Name] FROM [LocustLeaders] AS [l] INNER JOIN [Factions] AS [f] ON [l].[Name] = [f].[CommanderName] WHERE (CASE WHEN [f].[Name] = N'Locust' THEN CAST(1 AS bit) ELSE NULL END <> CAST(1 AS bit)) OR (CASE WHEN [f].[Name] = N'Locust' THEN CAST(1 AS bit) ELSE NULL END IS NULL)"); } public override async Task Byte_array_contains_literal(bool async) { await base.Byte_array_contains_literal(async); AssertSql( @"SELECT [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Squads] AS [s] WHERE CHARINDEX(0x01, [s].[Banner]) > 0"); } public override async Task Byte_array_filter_by_length_literal(bool async) { await base.Byte_array_filter_by_length_literal(async); AssertSql( @"SELECT [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Squads] AS [s] WHERE CAST(DATALENGTH([s].[Banner]) AS int) = 1"); } public override async Task Byte_array_filter_by_length_parameter(bool async) { await base.Byte_array_filter_by_length_parameter(async); AssertSql( @"@__p_0='1' SELECT [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Squads] AS [s] WHERE CAST(DATALENGTH([s].[Banner]) AS int) = @__p_0"); } public override void Byte_array_filter_by_length_parameter_compiled() { base.Byte_array_filter_by_length_parameter_compiled(); AssertSql( @"@__byteArrayParam='0x2A80' (Size = 8000) SELECT COUNT(*) FROM [Squads] AS [s] WHERE CAST(DATALENGTH([s].[Banner]) AS int) = CAST(DATALENGTH(@__byteArrayParam) AS int)"); } public override async Task Byte_array_contains_parameter(bool async) { await base.Byte_array_contains_parameter(async); AssertSql( @"@__someByte_0='1' (Size = 1) SELECT [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Squads] AS [s] WHERE CHARINDEX(CAST(@__someByte_0 AS varbinary(max)), [s].[Banner]) > 0"); } public override async Task Byte_array_filter_by_length_literal_does_not_cast_on_varbinary_n(bool async) { await base.Byte_array_filter_by_length_literal_does_not_cast_on_varbinary_n(async); AssertSql( @"SELECT [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Squads] AS [s] WHERE DATALENGTH([s].[Banner5]) = 5"); } public override async Task Conditional_expression_with_test_being_simplified_to_constant_simple(bool isAsync) { await base.Conditional_expression_with_test_being_simplified_to_constant_simple(isAsync); AssertSql( @"@__prm_0='True' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE CASE WHEN [g].[HasSoulPatch] = @__prm_0 THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END = CAST(1 AS bit)"); } public override async Task Conditional_expression_with_test_being_simplified_to_constant_complex(bool isAsync) { await base.Conditional_expression_with_test_being_simplified_to_constant_complex(isAsync); AssertSql( @"@__prm_0='True' @__prm2_1='Dom's Lancer' (Size = 4000) SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE CASE WHEN [g].[HasSoulPatch] = @__prm_0 THEN CASE WHEN (( SELECT TOP(1) [w].[Name] FROM [Weapons] AS [w] WHERE [w].[Id] = [g].[SquadId]) = @__prm2_1) AND ( SELECT TOP(1) [w].[Name] FROM [Weapons] AS [w] WHERE [w].[Id] = [g].[SquadId]) IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END ELSE CAST(0 AS bit) END = CAST(1 AS bit)"); } public override async Task OrderBy_bool_coming_from_optional_navigation(bool async) { await base.OrderBy_bool_coming_from_optional_navigation(async); AssertSql( @"SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id] ORDER BY [w0].[IsAutomatic]"); } public override async Task DateTimeOffset_Date_returns_datetime(bool async) { await base.DateTimeOffset_Date_returns_datetime(async); AssertSql( @"@__dateTimeOffset_Date_0='0002-03-01T00:00:00.0000000' SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE CONVERT(date, [m].[Timeline]) >= @__dateTimeOffset_Date_0"); } public override async Task Conditional_with_conditions_evaluating_to_false_gets_optimized(bool async) { await base.Conditional_with_conditions_evaluating_to_false_gets_optimized(async); AssertSql( @"SELECT [g].[FullName] FROM [Gears] AS [g]"); } public override async Task Conditional_with_conditions_evaluating_to_true_gets_optimized(bool async) { await base.Conditional_with_conditions_evaluating_to_true_gets_optimized(async); AssertSql( @"SELECT [g].[CityOfBirthName] FROM [Gears] AS [g]"); } public override async Task Projecting_required_string_column_compared_to_null_parameter(bool async) { await base.Projecting_required_string_column_compared_to_null_parameter(async); AssertSql( @"SELECT CAST(0 AS bit) FROM [Gears] AS [g]"); } public override async Task Byte_array_filter_by_SequenceEqual(bool isAsync) { await base.Byte_array_filter_by_SequenceEqual(isAsync); AssertSql( @"@__byteArrayParam_0='0x0405060708' (Size = 5) SELECT [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Squads] AS [s] WHERE [s].[Banner5] = @__byteArrayParam_0"); } public override async Task Group_by_nullable_property_HasValue_and_project_the_grouping_key(bool async) { await base.Group_by_nullable_property_HasValue_and_project_the_grouping_key(async); AssertSql( @"SELECT CASE WHEN [w].[SynergyWithId] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END FROM [Weapons] AS [w] GROUP BY CASE WHEN [w].[SynergyWithId] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END"); } public override async Task Group_by_nullable_property_and_project_the_grouping_key_HasValue(bool async) { await base.Group_by_nullable_property_and_project_the_grouping_key_HasValue(async); AssertSql( @"SELECT CASE WHEN [w].[SynergyWithId] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END FROM [Weapons] AS [w] GROUP BY [w].[SynergyWithId]"); } public override async Task Checked_context_with_cast_does_not_fail(bool isAsync) { await base.Checked_context_with_cast_does_not_fail(isAsync); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] WHERE CAST([l].[ThreatLevel] AS tinyint) >= CAST(5 AS tinyint)"); } public override async Task Checked_context_with_addition_does_not_fail(bool isAsync) { await base.Checked_context_with_addition_does_not_fail(isAsync); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] WHERE CAST([l].[ThreatLevel] AS bigint) >= (CAST(5 AS bigint) + CAST([l].[ThreatLevel] AS bigint))"); } public override async Task TimeSpan_Hours(bool async) { await base.TimeSpan_Hours(async); AssertSql( @"SELECT DATEPART(hour, [m].[Duration]) FROM [Missions] AS [m]"); } public override async Task TimeSpan_Minutes(bool async) { await base.TimeSpan_Minutes(async); AssertSql( @"SELECT DATEPART(minute, [m].[Duration]) FROM [Missions] AS [m]"); } public override async Task TimeSpan_Seconds(bool async) { await base.TimeSpan_Seconds(async); AssertSql( @"SELECT DATEPART(second, [m].[Duration]) FROM [Missions] AS [m]"); } public override async Task TimeSpan_Milliseconds(bool async) { await base.TimeSpan_Milliseconds(async); AssertSql( @"SELECT DATEPART(millisecond, [m].[Duration]) FROM [Missions] AS [m]"); } public override async Task Where_TimeSpan_Hours(bool async) { await base.Where_TimeSpan_Hours(async); AssertSql( @"SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE DATEPART(hour, [m].[Duration]) = 1"); } public override async Task Where_TimeSpan_Minutes(bool async) { await base.Where_TimeSpan_Minutes(async); AssertSql( @"SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE DATEPART(minute, [m].[Duration]) = 1"); } public override async Task Where_TimeSpan_Seconds(bool async) { await base.Where_TimeSpan_Seconds(async); AssertSql( @"SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE DATEPART(second, [m].[Duration]) = 1"); } public override async Task Where_TimeSpan_Milliseconds(bool async) { await base.Where_TimeSpan_Milliseconds(async); AssertSql( @"SELECT [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE DATEPART(millisecond, [m].[Duration]) = 1"); } public override async Task Contains_on_collection_of_byte_subquery(bool async) { await base.Contains_on_collection_of_byte_subquery(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] WHERE EXISTS ( SELECT 1 FROM [LocustLeaders] AS [l0] WHERE [l0].[ThreatLevelByte] = [l].[ThreatLevelByte])"); } public override async Task Contains_on_collection_of_nullable_byte_subquery(bool async) { await base.Contains_on_collection_of_nullable_byte_subquery(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] WHERE EXISTS ( SELECT 1 FROM [LocustLeaders] AS [l0] WHERE ([l0].[ThreatLevelNullableByte] = [l].[ThreatLevelNullableByte]) OR ([l0].[ThreatLevelNullableByte] IS NULL AND [l].[ThreatLevelNullableByte] IS NULL))"); } public override async Task Contains_on_collection_of_nullable_byte_subquery_null_constant(bool async) { await base.Contains_on_collection_of_nullable_byte_subquery_null_constant(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] WHERE EXISTS ( SELECT 1 FROM [LocustLeaders] AS [l0] WHERE [l0].[ThreatLevelNullableByte] IS NULL)"); } public override async Task Contains_on_collection_of_nullable_byte_subquery_null_parameter(bool async) { await base.Contains_on_collection_of_nullable_byte_subquery_null_parameter(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] WHERE EXISTS ( SELECT 1 FROM [LocustLeaders] AS [l0] WHERE [l0].[ThreatLevelNullableByte] IS NULL)"); } public override async Task Contains_on_byte_array_property_using_byte_column(bool async) { await base.Contains_on_byte_array_property_using_byte_column(async); AssertSql( @"SELECT [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name], [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [Squads] AS [s] CROSS JOIN [LocustLeaders] AS [l] WHERE CHARINDEX(CAST([l].[ThreatLevelByte] AS varbinary(max)), [s].[Banner]) > 0"); } public override async Task Subquery_projecting_non_nullable_scalar_contains_non_nullable_value_doesnt_need_null_expansion( bool async) { await base.Subquery_projecting_non_nullable_scalar_contains_non_nullable_value_doesnt_need_null_expansion(async); AssertSql( @"SELECT [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank] FROM [LocustLeaders] AS [l] CROSS APPLY ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE EXISTS ( SELECT 1 FROM [LocustLeaders] AS [l0] WHERE [l0].[ThreatLevelByte] = [l].[ThreatLevelByte]) ) AS [t]"); } public override async Task Subquery_projecting_non_nullable_scalar_contains_non_nullable_value_doesnt_need_null_expansion_negated( bool async) { await base.Subquery_projecting_non_nullable_scalar_contains_non_nullable_value_doesnt_need_null_expansion_negated(async); AssertSql( @"SELECT [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank] FROM [LocustLeaders] AS [l] CROSS APPLY ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE NOT (EXISTS ( SELECT 1 FROM [LocustLeaders] AS [l0] WHERE [l0].[ThreatLevelByte] = [l].[ThreatLevelByte])) ) AS [t]"); } public override async Task Subquery_projecting_nullable_scalar_contains_nullable_value_needs_null_expansion(bool async) { await base.Subquery_projecting_nullable_scalar_contains_nullable_value_needs_null_expansion(async); AssertSql( @"SELECT [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank] FROM [LocustLeaders] AS [l] CROSS APPLY ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE EXISTS ( SELECT 1 FROM [LocustLeaders] AS [l0] WHERE ([l0].[ThreatLevelNullableByte] = [l].[ThreatLevelNullableByte]) OR ([l0].[ThreatLevelNullableByte] IS NULL AND [l].[ThreatLevelNullableByte] IS NULL)) ) AS [t]"); } public override async Task Subquery_projecting_nullable_scalar_contains_nullable_value_needs_null_expansion_negated(bool async) { await base.Subquery_projecting_nullable_scalar_contains_nullable_value_needs_null_expansion_negated(async); AssertSql( @"SELECT [t].[Nickname], [t].[SquadId], [t].[AssignedCityName], [t].[CityOfBirthName], [t].[Discriminator], [t].[FullName], [t].[HasSoulPatch], [t].[LeaderNickname], [t].[LeaderSquadId], [t].[Rank] FROM [LocustLeaders] AS [l] CROSS APPLY ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE NOT (EXISTS ( SELECT 1 FROM [LocustLeaders] AS [l0] WHERE ([l0].[ThreatLevelNullableByte] = [l].[ThreatLevelNullableByte]) OR ([l0].[ThreatLevelNullableByte] IS NULL AND [l].[ThreatLevelNullableByte] IS NULL))) ) AS [t]"); } public override async Task Enum_closure_typed_as_underlying_type_generates_correct_parameter_type(bool async) { await base.Enum_closure_typed_as_underlying_type_generates_correct_parameter_type(async); AssertSql( @"@__prm_0='1' (Nullable = true) SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE @__prm_0 = [w].[AmmunitionType]"); } public override async Task Enum_flags_closure_typed_as_underlying_type_generates_correct_parameter_type(bool async) { await base.Enum_flags_closure_typed_as_underlying_type_generates_correct_parameter_type(async); AssertSql( @"@__prm_0='133' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE (@__prm_0 & [g].[Rank]) = [g].[Rank]"); } public override async Task Enum_flags_closure_typed_as_different_type_generates_correct_parameter_type(bool async) { await base.Enum_flags_closure_typed_as_different_type_generates_correct_parameter_type(async); AssertSql( @"@__prm_0='5' SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [Gears] AS [g] WHERE (@__prm_0 & CAST([g].[Rank] AS int)) = CAST([g].[Rank] AS int)"); } public override async Task Constant_enum_with_same_underlying_value_as_previously_parameterized_int(bool async) { await base.Constant_enum_with_same_underlying_value_as_previously_parameterized_int(async); AssertSql( @"@__p_0='1' SELECT TOP(@__p_0) [g].[Rank] & 1 FROM [Gears] AS [g] ORDER BY [g].[Nickname]"); } public override async Task Enum_array_contains(bool async) { await base.Enum_array_contains(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id] WHERE [w0].[Id] IS NOT NULL AND (([w0].[AmmunitionType] = 1) OR [w0].[AmmunitionType] IS NULL)"); } [ConditionalTheory] [MemberData(nameof(IsAsyncData))] public async Task DataLength_function_for_string_parameter(bool async) { await AssertQueryScalar( async, ss => ss.Set<Mission>().Select(m => EF.Functions.DataLength(m.CodeName)), ss => ss.Set<Mission>().Select(m => (int?)(m.CodeName.Length * 2))); AssertSql( @"SELECT CAST(DATALENGTH([m].[CodeName]) AS int) FROM [Missions] AS [m]"); } public override async Task CompareTo_used_with_non_unicode_string_column_and_constant(bool async) { await base.CompareTo_used_with_non_unicode_string_column_and_constant(async); AssertSql( @"SELECT [c].[Name], [c].[Location], [c].[Nation] FROM [Cities] AS [c] WHERE [c].[Location] = 'Unknown'"); } public override async Task Coalesce_used_with_non_unicode_string_column_and_constant(bool async) { await base.Coalesce_used_with_non_unicode_string_column_and_constant(async); AssertSql( @"SELECT COALESCE([c].[Location], 'Unknown') FROM [Cities] AS [c]"); } public override async Task Groupby_anonymous_type_with_navigations_followed_up_by_anonymous_projection_and_orderby(bool async) { await base.Groupby_anonymous_type_with_navigations_followed_up_by_anonymous_projection_and_orderby(async); AssertSql( @"SELECT [c].[Name], [c].[Location], COUNT(*) AS [Count] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g] ON [w].[OwnerFullName] = [g].[FullName] LEFT JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name] GROUP BY [c].[Name], [c].[Location] ORDER BY [c].[Location]"); } public override async Task SelectMany_predicate_with_non_equality_comparison_converted_to_inner_join(bool async) { await base.SelectMany_predicate_with_non_equality_comparison_converted_to_inner_join(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] INNER JOIN [Weapons] AS [w] ON ([g].[FullName] <> [w].[OwnerFullName]) OR [w].[OwnerFullName] IS NULL ORDER BY [g].[Nickname], [w].[Id]"); } public override async Task SelectMany_predicate_with_non_equality_comparison_DefaultIfEmpty_converted_to_left_join(bool async) { await base.SelectMany_predicate_with_non_equality_comparison_DefaultIfEmpty_converted_to_left_join(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON ([g].[FullName] <> [w].[OwnerFullName]) OR [w].[OwnerFullName] IS NULL ORDER BY [g].[Nickname], [w].[Id]"); } public override async Task SelectMany_predicate_after_navigation_with_non_equality_comparison_DefaultIfEmpty_converted_to_left_join( bool async) { await base.SelectMany_predicate_after_navigation_with_non_equality_comparison_DefaultIfEmpty_converted_to_left_join(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Id], [t].[AmmunitionType], [t].[IsAutomatic], [t].[Name], [t].[OwnerFullName], [t].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN ( SELECT [w0].[Id], [w0].[AmmunitionType], [w0].[IsAutomatic], [w0].[Name], [w0].[OwnerFullName], [w0].[SynergyWithId] FROM [Weapons] AS [w] LEFT JOIN [Weapons] AS [w0] ON [w].[SynergyWithId] = [w0].[Id] ) AS [t] ON ([g].[FullName] <> [t].[OwnerFullName]) OR [t].[OwnerFullName] IS NULL ORDER BY [g].[Nickname], [t].[Id]"); } public override async Task SelectMany_without_result_selector_and_non_equality_comparison_converted_to_join(bool async) { await base.SelectMany_without_result_selector_and_non_equality_comparison_converted_to_join(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON ([g].[FullName] <> [w].[OwnerFullName]) OR [w].[OwnerFullName] IS NULL"); } public override async Task Filtered_collection_projection_with_order_comparison_predicate_converted_to_join(bool async) { await base.Filtered_collection_projection_with_order_comparison_predicate_converted_to_join(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON ([g].[FullName] = [w].[OwnerFullName]) AND ([g].[SquadId] < [w].[Id]) ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Filtered_collection_projection_with_order_comparison_predicate_converted_to_join2(bool async) { await base.Filtered_collection_projection_with_order_comparison_predicate_converted_to_join2(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON ([g].[FullName] = [w].[OwnerFullName]) AND ([g].[SquadId] <= [w].[Id]) ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Filtered_collection_projection_with_order_comparison_predicate_converted_to_join3(bool async) { await base.Filtered_collection_projection_with_order_comparison_predicate_converted_to_join3(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Gears] AS [g] LEFT JOIN [Weapons] AS [w] ON ([g].[FullName] = [w].[OwnerFullName]) AND ([g].[SquadId] >= [w].[Id]) ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task SelectMany_predicate_with_non_equality_comparison_with_Take_doesnt_convert_to_join(bool async) { await base.SelectMany_predicate_with_non_equality_comparison_with_Take_doesnt_convert_to_join(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Id], [t].[AmmunitionType], [t].[IsAutomatic], [t].[Name], [t].[OwnerFullName], [t].[SynergyWithId] FROM [Gears] AS [g] CROSS APPLY ( SELECT TOP(3) [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE ([w].[OwnerFullName] <> [g].[FullName]) OR [w].[OwnerFullName] IS NULL ORDER BY [w].[Id] ) AS [t] ORDER BY [g].[Nickname], [t].[Id]"); } public override async Task FirstOrDefault_over_int_compared_to_zero(bool async) { await base.FirstOrDefault_over_int_compared_to_zero(async); AssertSql( @"SELECT [s].[Name] FROM [Squads] AS [s] WHERE ([s].[Name] = N'Kilo') AND (COALESCE(( SELECT TOP(1) [g].[SquadId] FROM [Gears] AS [g] WHERE ([s].[Id] = [g].[SquadId]) AND ([g].[HasSoulPatch] = CAST(1 AS bit))), 0) <> 0)"); } public override async Task Correlated_collection_with_inner_collection_references_element_two_levels_up(bool async) { await base.Correlated_collection_with_inner_collection_references_element_two_levels_up(async); AssertSql( @"SELECT [g].[FullName], [g].[Nickname], [g].[SquadId], [t].[ReportName], [t].[OfficerName], [t].[Nickname], [t].[SquadId] FROM [Gears] AS [g] OUTER APPLY ( SELECT [g0].[FullName] AS [ReportName], [g].[FullName] AS [OfficerName], [g0].[Nickname], [g0].[SquadId] FROM [Gears] AS [g0] WHERE ([g].[Nickname] = [g0].[LeaderNickname]) AND ([g].[SquadId] = [g0].[LeaderSquadId]) ) AS [t] WHERE [g].[Discriminator] = N'Officer' ORDER BY [g].[Nickname], [g].[SquadId], [t].[Nickname]"); } public override async Task Accessing_derived_property_using_hard_and_soft_cast(bool async) { await base.Accessing_derived_property_using_hard_and_soft_cast(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] WHERE ([l].[Discriminator] = N'LocustCommander') AND (([l].[HighCommandId] <> 0) OR [l].[HighCommandId] IS NULL)", // @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] WHERE ([l].[Discriminator] = N'LocustCommander') AND (([l].[HighCommandId] <> 0) OR [l].[HighCommandId] IS NULL)"); } public override async Task Cast_to_derived_followed_by_include_and_FirstOrDefault(bool async) { await base.Cast_to_derived_followed_by_include_and_FirstOrDefault(async); AssertSql( @"SELECT TOP(1) [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank] FROM [LocustLeaders] AS [l] LEFT JOIN [Gears] AS [g] ON ([l].[DefeatedByNickname] = [g].[Nickname]) AND ([l].[DefeatedBySquadId] = [g].[SquadId]) WHERE [l].[Name] LIKE N'%Queen%'"); } public override async Task Correlated_collection_take(bool async) { await base.Correlated_collection_take(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [c].[Name], [t0].[Id], [t0].[AmmunitionType], [t0].[IsAutomatic], [t0].[Name], [t0].[OwnerFullName], [t0].[SynergyWithId], [c].[Location], [c].[Nation] FROM [Gears] AS [g] INNER JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name] LEFT JOIN ( SELECT [t].[Id], [t].[AmmunitionType], [t].[IsAutomatic], [t].[Name], [t].[OwnerFullName], [t].[SynergyWithId] FROM ( SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId], ROW_NUMBER() OVER(PARTITION BY [w].[OwnerFullName] ORDER BY [w].[Id]) AS [row] FROM [Weapons] AS [w] ) AS [t] WHERE [t].[row] <= 10 ) AS [t0] ON [g].[FullName] = [t0].[OwnerFullName] ORDER BY [g].[Nickname], [g].[SquadId], [c].[Name], [t0].[OwnerFullName], [t0].[Id]"); } public override async Task FirstOrDefault_on_empty_collection_of_DateTime_in_subquery(bool async) { await base.FirstOrDefault_on_empty_collection_of_DateTime_in_subquery(async); AssertSql( @"SELECT [g].[Nickname], COALESCE(( SELECT TOP(1) [t1].[IssueDate] FROM [Tags] AS [t1] WHERE [t1].[GearNickName] = [g].[FullName] ORDER BY [t1].[Id]), '0001-01-01T00:00:00.0000000') AS [invalidTagIssueDate] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) WHERE [t].[IssueDate] > COALESCE(( SELECT TOP(1) [t0].[IssueDate] FROM [Tags] AS [t0] WHERE [t0].[GearNickName] = [g].[FullName] ORDER BY [t0].[Id]), '0001-01-01T00:00:00.0000000')"); } public override async Task First_on_byte_array(bool async) { await base.First_on_byte_array(async); AssertSql( @"SELECT [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Squads] AS [s] WHERE CAST(SUBSTRING([s].[Banner], 1, 1) AS tinyint) = CAST(2 AS tinyint)"); } public override async Task Array_access_on_byte_array(bool async) { await base.Array_access_on_byte_array(async); AssertSql( @"SELECT [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name] FROM [Squads] AS [s] WHERE CAST(SUBSTRING([s].[Banner5], 2 + 1, 1) AS tinyint) = CAST(6 AS tinyint)"); } public override async Task Project_shadow_properties(bool async) { await base.Project_shadow_properties(async); AssertSql( @"SELECT [g].[Nickname], [g].[AssignedCityName] FROM [Gears] AS [g]"); } public override async Task Project_discriminator_columns(bool async) { await base.Project_discriminator_columns(async); AssertSql( @"SELECT [g].[Nickname], [g].[Discriminator] FROM [Gears] AS [g]", // @"SELECT [g].[Nickname], [g].[Discriminator] FROM [Gears] AS [g] WHERE [g].[Discriminator] = N'Officer'", // @"SELECT [f].[Id], [f].[Discriminator] FROM [Factions] AS [f]", // @"SELECT [f].[Id], [f].[Discriminator] FROM [Factions] AS [f]", // @"SELECT [l].[Name], [l].[Discriminator] FROM [LocustLeaders] AS [l]", // @"SELECT [l].[Name], [l].[Discriminator] FROM [LocustLeaders] AS [l] WHERE [l].[Discriminator] = N'LocustCommander'"); } public override async Task Composite_key_entity_equal(bool async) { await base.Composite_key_entity_equal(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g] CROSS JOIN [Gears] AS [g0] WHERE ([g].[Nickname] = [g0].[Nickname]) AND ([g].[SquadId] = [g0].[SquadId])"); } public override async Task Composite_key_entity_not_equal(bool async) { await base.Composite_key_entity_not_equal(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [g0].[Nickname], [g0].[SquadId], [g0].[AssignedCityName], [g0].[CityOfBirthName], [g0].[Discriminator], [g0].[FullName], [g0].[HasSoulPatch], [g0].[LeaderNickname], [g0].[LeaderSquadId], [g0].[Rank] FROM [Gears] AS [g] CROSS JOIN [Gears] AS [g0] WHERE ([g].[Nickname] <> [g0].[Nickname]) OR ([g].[SquadId] <> [g0].[SquadId])"); } public override async Task Composite_key_entity_equal_null(bool async) { await base.Composite_key_entity_equal_null(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] LEFT JOIN [Gears] AS [g] ON ([l].[DefeatedByNickname] = [g].[Nickname]) AND ([l].[DefeatedBySquadId] = [g].[SquadId]) WHERE ([l].[Discriminator] = N'LocustCommander') AND ([g].[Nickname] IS NULL OR [g].[SquadId] IS NULL)"); } public override async Task Composite_key_entity_not_equal_null(bool async) { await base.Composite_key_entity_not_equal_null(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId] FROM [LocustLeaders] AS [l] LEFT JOIN [Gears] AS [g] ON ([l].[DefeatedByNickname] = [g].[Nickname]) AND ([l].[DefeatedBySquadId] = [g].[SquadId]) WHERE ([l].[Discriminator] = N'LocustCommander') AND ([g].[Nickname] IS NOT NULL AND [g].[SquadId] IS NOT NULL)"); } [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsFullTextSearch)] public async Task FreeText_with_binary_column() { using var context = CreateContext(); var result = await context.Missions.SingleAsync(e => EF.Functions.FreeText(EF.Property<byte[]>(e, "BriefingDocument"), "bombing")); Assert.Equal(1, result.Id); AssertSql( @"SELECT TOP(2) [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE FREETEXT([m].[BriefingDocument], N'bombing')"); } [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsFullTextSearch)] public async Task FreeText_with_binary_column_and_language_term() { using var context = CreateContext(); var result = await context.Missions.SingleAsync(e => EF.Functions.FreeText(EF.Property<byte[]>(e, "BriefingDocument"), "bombing", 1033)); Assert.Equal(1, result.Id); AssertSql( @"SELECT TOP(2) [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE FREETEXT([m].[BriefingDocument], N'bombing', LANGUAGE 1033)"); } [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsFullTextSearch)] public async Task Contains_with_binary_column() { using var context = CreateContext(); var result = await context.Missions.SingleAsync(e => EF.Functions.Contains(EF.Property<byte[]>(e, "BriefingDocument"), "bomb")); Assert.Equal(1, result.Id); AssertSql( @"SELECT TOP(2) [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE CONTAINS([m].[BriefingDocument], N'bomb')"); } [ConditionalFact] [SqlServerCondition(SqlServerCondition.SupportsFullTextSearch)] public async Task Contains_with_binary_column_and_language_term() { using var context = CreateContext(); var result = await context.Missions.SingleAsync(e => EF.Functions.Contains(EF.Property<byte[]>(e, "BriefingDocument"), "bomb", 1033)); Assert.Equal(1, result.Id); AssertSql( @"SELECT TOP(2) [m].[Id], [m].[BriefingDocument], [m].[BriefingDocumentFileExtension], [m].[CodeName], [m].[Duration], [m].[Rating], [m].[Timeline] FROM [Missions] AS [m] WHERE CONTAINS([m].[BriefingDocument], N'bomb', LANGUAGE 1033)"); } public override async Task Projecting_property_converted_to_nullable_with_comparison(bool async) { await base.Projecting_property_converted_to_nullable_with_comparison(async); AssertSql( @"SELECT [t].[Note], CASE WHEN [t].[GearNickName] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, [g].[Nickname], [g].[SquadId], [g].[HasSoulPatch] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[SquadId] ELSE NULL END = 1"); } public override async Task Projecting_property_converted_to_nullable_with_addition(bool async) { await base.Projecting_property_converted_to_nullable_with_addition(async); AssertSql( @"SELECT [t].[Note], CASE WHEN [t].[GearNickName] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, [g].[Nickname], [g].[SquadId], [g].[HasSoulPatch] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE (CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[SquadId] ELSE NULL END + 1) = 2"); } public override async Task Projecting_property_converted_to_nullable_with_addition_and_final_projection(bool async) { await base.Projecting_property_converted_to_nullable_with_addition_and_final_projection(async); AssertSql( @"SELECT [t].[Note], CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[SquadId] ELSE NULL END + 1 AS [Value] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[Nickname] ELSE NULL END IS NOT NULL"); } public override async Task Projecting_property_converted_to_nullable_with_conditional(bool async) { await base.Projecting_property_converted_to_nullable_with_conditional(async); AssertSql( @"SELECT CASE WHEN ([t].[Note] <> N'K.I.A.') OR [t].[Note] IS NULL THEN CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[SquadId] ELSE NULL END ELSE -1 END FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId])"); } public override async Task Projecting_property_converted_to_nullable_with_function_call(bool async) { await base.Projecting_property_converted_to_nullable_with_function_call(async); AssertSql( @"SELECT SUBSTRING(CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[Nickname] ELSE NULL END, 0 + 1, 3) FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId])"); } public override async Task Projecting_property_converted_to_nullable_with_function_call2(bool async) { await base.Projecting_property_converted_to_nullable_with_function_call2(async); AssertSql( @"SELECT [t].[Note], SUBSTRING([t].[Note], 0 + 1, CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[SquadId] ELSE NULL END) AS [Function] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[Nickname] ELSE NULL END IS NOT NULL"); } public override async Task Projecting_property_converted_to_nullable_into_element_init(bool async) { await base.Projecting_property_converted_to_nullable_into_element_init(async); AssertSql( @"SELECT CASE WHEN [t].[GearNickName] IS NOT NULL THEN CAST(LEN([g].[Nickname]) AS int) ELSE NULL END, CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[SquadId] ELSE NULL END, CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[SquadId] ELSE NULL END + 1 FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[Nickname] ELSE NULL END IS NOT NULL ORDER BY [t].[Note]"); } public override async Task Projecting_property_converted_to_nullable_into_member_assignment(bool async) { await base.Projecting_property_converted_to_nullable_into_member_assignment(async); AssertSql( @"SELECT CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[SquadId] ELSE NULL END AS [Id] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[Nickname] ELSE NULL END IS NOT NULL ORDER BY [t].[Note]"); } public override async Task Projecting_property_converted_to_nullable_into_new_array(bool async) { await base.Projecting_property_converted_to_nullable_into_new_array(async); AssertSql( @"SELECT CASE WHEN [t].[GearNickName] IS NOT NULL THEN CAST(LEN([g].[Nickname]) AS int) ELSE NULL END, CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[SquadId] ELSE NULL END, CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[SquadId] ELSE NULL END + 1 FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[Nickname] ELSE NULL END IS NOT NULL ORDER BY [t].[Note]"); } public override async Task Projecting_property_converted_to_nullable_into_unary(bool async) { await base.Projecting_property_converted_to_nullable_into_unary(async); AssertSql( @"SELECT [t].[Note] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[Nickname] ELSE NULL END IS NOT NULL AND (CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[HasSoulPatch] ELSE NULL END = CAST(0 AS bit)) ORDER BY [t].[Note]"); } public override async Task Projecting_property_converted_to_nullable_into_member_access(bool async) { await base.Projecting_property_converted_to_nullable_into_member_access(async); AssertSql( @"SELECT [g].[Nickname] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) WHERE (DATEPART(month, [t].[IssueDate]) <> 5) OR [t].[IssueDate] IS NULL ORDER BY [g].[Nickname]"); } public override async Task Projecting_property_converted_to_nullable_and_use_it_in_order_by(bool async) { await base.Projecting_property_converted_to_nullable_and_use_it_in_order_by(async); AssertSql( @"SELECT [t].[Note], CASE WHEN [t].[GearNickName] IS NOT NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END, [g].[Nickname], [g].[SquadId], [g].[HasSoulPatch] FROM [Tags] AS [t] LEFT JOIN [Gears] AS [g] ON ([t].[GearNickName] = [g].[Nickname]) AND ([t].[GearSquadId] = [g].[SquadId]) WHERE CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[Nickname] ELSE NULL END IS NOT NULL ORDER BY CASE WHEN [t].[GearNickName] IS NOT NULL THEN [g].[SquadId] ELSE NULL END, [t].[Note]"); } public override async Task Correlated_collection_with_distinct_projecting_identifier_column(bool async) { await base.Correlated_collection_with_distinct_projecting_identifier_column(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Id], [t].[Name] FROM [Gears] AS [g] OUTER APPLY ( SELECT DISTINCT [w].[Id], [w].[Name] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ) AS [t] ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collection_with_distinct_projecting_identifier_column_and_correlation_key(bool async) { await base.Correlated_collection_with_distinct_projecting_identifier_column_and_correlation_key(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Id], [t].[Name], [t].[OwnerFullName] FROM [Gears] AS [g] LEFT JOIN ( SELECT DISTINCT [w].[Id], [w].[Name], [w].[OwnerFullName] FROM [Weapons] AS [w] ) AS [t] ON [g].[FullName] = [t].[OwnerFullName] ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collection_with_distinct_projecting_identifier_column_composite_key(bool async) { await base.Correlated_collection_with_distinct_projecting_identifier_column_composite_key(async); AssertSql( @"SELECT [s].[Id], [t].[Nickname], [t].[SquadId], [t].[HasSoulPatch] FROM [Squads] AS [s] LEFT JOIN ( SELECT DISTINCT [g].[Nickname], [g].[SquadId], [g].[HasSoulPatch] FROM [Gears] AS [g] ) AS [t] ON [s].[Id] = [t].[SquadId] ORDER BY [s].[Id], [t].[Nickname]"); } public override async Task Correlated_collection_with_distinct_not_projecting_identifier_column(bool async) { await base.Correlated_collection_with_distinct_not_projecting_identifier_column(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Name], [t].[IsAutomatic] FROM [Gears] AS [g] OUTER APPLY ( SELECT DISTINCT [w].[Name], [w].[IsAutomatic] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] ) AS [t] ORDER BY [g].[Nickname], [g].[SquadId], [t].[Name]"); } public override async Task Correlated_collection_with_groupby_not_projecting_identifier_column_but_only_grouping_key_in_final_projection(bool async) { await base.Correlated_collection_with_groupby_not_projecting_identifier_column_but_only_grouping_key_in_final_projection(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Key] FROM [Gears] AS [g] OUTER APPLY ( SELECT [w].[IsAutomatic] AS [Key] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] GROUP BY [w].[IsAutomatic] ) AS [t] ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collection_with_groupby_not_projecting_identifier_column_with_group_aggregate_in_final_projection(bool async) { await base.Correlated_collection_with_groupby_not_projecting_identifier_column_with_group_aggregate_in_final_projection(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[Key], [t].[Count] FROM [Gears] AS [g] OUTER APPLY ( SELECT [w].[IsAutomatic] AS [Key], COUNT(*) AS [Count] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] GROUP BY [w].[IsAutomatic] ) AS [t] ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collection_with_groupby_not_projecting_identifier_column_with_group_aggregate_in_final_projection_multiple_grouping_keys(bool async) { await base.Correlated_collection_with_groupby_not_projecting_identifier_column_with_group_aggregate_in_final_projection_multiple_grouping_keys(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[IsAutomatic], [t].[Name], [t].[Count] FROM [Gears] AS [g] OUTER APPLY ( SELECT [w].[IsAutomatic], [w].[Name], COUNT(*) AS [Count] FROM [Weapons] AS [w] WHERE [g].[FullName] = [w].[OwnerFullName] GROUP BY [w].[IsAutomatic], [w].[Name] ) AS [t] ORDER BY [g].[Nickname], [g].[SquadId], [t].[IsAutomatic]"); } public override async Task Correlated_collection_via_SelectMany_with_Distinct_missing_indentifying_columns_in_projection(bool async) { await base.Correlated_collection_via_SelectMany_with_Distinct_missing_indentifying_columns_in_projection(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [t].[HasSoulPatch] FROM [Gears] AS [g] OUTER APPLY ( SELECT DISTINCT [g1].[HasSoulPatch] FROM [Weapons] AS [w] LEFT JOIN [Gears] AS [g0] ON [w].[OwnerFullName] = [g0].[FullName] LEFT JOIN [Cities] AS [c] ON [g0].[AssignedCityName] = [c].[Name] INNER JOIN [Gears] AS [g1] ON [c].[Name] = [g1].[CityOfBirthName] WHERE [g].[FullName] = [w].[OwnerFullName] ) AS [t] ORDER BY [g].[Nickname], [g].[SquadId]"); } public override async Task Correlated_collection_after_distinct_3_levels(bool async) { await base.Correlated_collection_after_distinct_3_levels(async); AssertSql( @"SELECT [t].[Id], [t].[Name], [t1].[Nickname], [t1].[FullName], [t1].[HasSoulPatch], [t1].[Id], [t1].[Name], [t1].[Nickname0], [t1].[FullName0], [t1].[HasSoulPatch0], [t1].[Id0] FROM ( SELECT DISTINCT [s].[Id], [s].[Name] FROM [Squads] AS [s] ) AS [t] OUTER APPLY ( SELECT [t0].[Nickname], [t0].[FullName], [t0].[HasSoulPatch], [t2].[Id], [t2].[Name], [t2].[Nickname] AS [Nickname0], [t2].[FullName] AS [FullName0], [t2].[HasSoulPatch] AS [HasSoulPatch0], [t2].[Id0] FROM ( SELECT DISTINCT [g].[Nickname], [g].[FullName], [g].[HasSoulPatch] FROM [Gears] AS [g] WHERE [g].[SquadId] = [t].[Id] ) AS [t0] OUTER APPLY ( SELECT [t].[Id], [t].[Name], [t0].[Nickname], [t0].[FullName], [t0].[HasSoulPatch], [w].[Id] AS [Id0] FROM [Weapons] AS [w] WHERE [t0].[FullName] = [w].[OwnerFullName] ) AS [t2] ) AS [t1] ORDER BY [t].[Id], [t1].[Nickname], [t1].[FullName], [t1].[HasSoulPatch]"); } public override async Task Correlated_collection_after_distinct_3_levels_without_original_identifiers(bool async) { await base.Correlated_collection_after_distinct_3_levels_without_original_identifiers(async); AssertSql( @"SELECT [t].[Length], [t2].[HasSoulPatch], [t2].[CityOfBirthName], [t2].[Id], [t2].[Length], [t2].[HasSoulPatch0] FROM ( SELECT DISTINCT CAST(LEN([s].[Name]) AS int) AS [Length] FROM [Squads] AS [s] ) AS [t] OUTER APPLY ( SELECT [t0].[HasSoulPatch], [t0].[CityOfBirthName], [t1].[Id], [t1].[Length], [t1].[HasSoulPatch] AS [HasSoulPatch0] FROM ( SELECT DISTINCT [g].[HasSoulPatch], [g].[CityOfBirthName] FROM [Gears] AS [g] WHERE CAST(LEN([g].[Nickname]) AS int) = [t].[Length] ) AS [t0] OUTER APPLY ( SELECT [w].[Id], [t].[Length], [t0].[HasSoulPatch] FROM [Weapons] AS [w] WHERE [t0].[CityOfBirthName] = [w].[OwnerFullName] ) AS [t1] ) AS [t2] ORDER BY [t].[Length], [t2].[HasSoulPatch], [t2].[CityOfBirthName], [t2].[Id]"); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_DateOnly_Year(bool async) { await base.Where_DateOnly_Year(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_DateOnly_Month(bool async) { await base.Where_DateOnly_Month(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_DateOnly_Day(bool async) { await base.Where_DateOnly_Day(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_DateOnly_DayOfYear(bool async) { await base.Where_DateOnly_DayOfYear(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_DateOnly_DayOfWeek(bool async) { await base.Where_DateOnly_DayOfWeek(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_DateOnly_AddYears(bool async) { await base.Where_DateOnly_AddYears(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_DateOnly_AddMonths(bool async) { await base.Where_DateOnly_AddMonths(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_DateOnly_AddDays(bool async) { await base.Where_DateOnly_AddDays(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_TimeOnly_Hour(bool async) { await base.Where_TimeOnly_Hour(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_TimeOnly_Minute(bool async) { await base.Where_TimeOnly_Minute(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_TimeOnly_Second(bool async) { await base.Where_TimeOnly_Second(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_TimeOnly_Millisecond(bool async) { await base.Where_TimeOnly_Millisecond(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_TimeOnly_AddHours(bool async) { await base.Where_TimeOnly_AddHours(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_TimeOnly_AddMinutes(bool async) { await base.Where_TimeOnly_AddMinutes(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_TimeOnly_Add_TimeSpan(bool async) { await base.Where_TimeOnly_Add_TimeSpan(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_TimeOnly_IsBetween(bool async) { await base.Where_TimeOnly_IsBetween(async); AssertSql(""); } [ConditionalTheory(Skip = "#24507")] [MemberData(nameof(IsAsyncData))] public override async Task Where_TimeOnly_subtract_TimeOnly(bool async) { await base.Where_TimeOnly_subtract_TimeOnly(async); AssertSql(""); } public override async Task Include_on_entity_that_is_not_present_in_final_projection_but_uses_TypeIs_instead(bool async) { await base.Include_on_entity_that_is_not_present_in_final_projection_but_uses_TypeIs_instead(async); AssertSql( @"SELECT [g].[Nickname], CASE WHEN [g].[Discriminator] = N'Officer' THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [IsOfficer] FROM [Gears] AS [g]"); } public override async Task Comparison_with_value_converted_subclass(bool async) { await base.Comparison_with_value_converted_subclass(async); AssertSql( @"SELECT [f].[Id], [f].[CapitalName], [f].[Discriminator], [f].[Name], [f].[ServerAddress], [f].[CommanderName], [f].[Eradicated] FROM [Factions] AS [f] WHERE [f].[ServerAddress] = CAST(N'127.0.0.1' AS nvarchar(45))"); } public override async Task Contains_on_readonly_enumerable(bool async) { await base.Contains_on_readonly_enumerable(async); AssertSql( @"SELECT [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM [Weapons] AS [w] WHERE [w].[AmmunitionType] = 1"); } public override async Task Project_navigation_defined_on_base_from_entity_with_inheritance_using_soft_cast(bool async) { await base.Project_navigation_defined_on_base_from_entity_with_inheritance_using_soft_cast(async); AssertSql( @"SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[Id], [t].[GearNickName], [t].[GearSquadId], [t].[IssueDate], [t].[Note], CASE WHEN [t].[Id] IS NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [IsNull], [c].[Name], [c].[Location], [c].[Nation], CASE WHEN [c].[Name] IS NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [IsNull], [s].[Id], [s].[Banner], [s].[Banner5], [s].[InternalNumber], [s].[Name], CASE WHEN [s].[Id] IS NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [IsNull] FROM [Gears] AS [g] LEFT JOIN [Tags] AS [t] ON ([g].[Nickname] = [t].[GearNickName]) AND ([g].[SquadId] = [t].[GearSquadId]) LEFT JOIN [Cities] AS [c] ON [g].[CityOfBirthName] = [c].[Name] LEFT JOIN [Squads] AS [s] ON [g].[SquadId] = [s].[Id]"); } public override async Task Project_navigation_defined_on_derived_from_entity_with_inheritance_using_soft_cast(bool async) { await base.Project_navigation_defined_on_derived_from_entity_with_inheritance_using_soft_cast(async); AssertSql( @"SELECT [l].[Name], [l].[Discriminator], [l].[LocustHordeId], [l].[ThreatLevel], [l].[ThreatLevelByte], [l].[ThreatLevelNullableByte], [l].[DefeatedByNickname], [l].[DefeatedBySquadId], [l].[HighCommandId], [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], CASE WHEN [g].[Nickname] IS NULL OR [g].[SquadId] IS NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [IsNull], [f].[Id], [f].[CapitalName], [f].[Discriminator], [f].[Name], [f].[ServerAddress], [f].[CommanderName], [f].[Eradicated], CASE WHEN [f].[Id] IS NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [IsNull], [l0].[Id], [l0].[IsOperational], [l0].[Name], CASE WHEN [l0].[Id] IS NULL THEN CAST(1 AS bit) ELSE CAST(0 AS bit) END AS [IsNull] FROM [LocustLeaders] AS [l] LEFT JOIN [Gears] AS [g] ON ([l].[DefeatedByNickname] = [g].[Nickname]) AND ([l].[DefeatedBySquadId] = [g].[SquadId]) LEFT JOIN [Factions] AS [f] ON [l].[Name] = [f].[CommanderName] LEFT JOIN [LocustHighCommands] AS [l0] ON [l].[HighCommandId] = [l0].[Id]"); } public override async Task Join_entity_with_itself_grouped_by_key_followed_by_include_skip_take(bool async) { await base.Join_entity_with_itself_grouped_by_key_followed_by_include_skip_take(async); AssertSql( @"@__p_0='0' @__p_1='10' SELECT [t0].[Nickname], [t0].[SquadId], [t0].[AssignedCityName], [t0].[CityOfBirthName], [t0].[Discriminator], [t0].[FullName], [t0].[HasSoulPatch], [t0].[LeaderNickname], [t0].[LeaderSquadId], [t0].[Rank], [t0].[HasSoulPatch0], [w].[Id], [w].[AmmunitionType], [w].[IsAutomatic], [w].[Name], [w].[OwnerFullName], [w].[SynergyWithId] FROM ( SELECT [g].[Nickname], [g].[SquadId], [g].[AssignedCityName], [g].[CityOfBirthName], [g].[Discriminator], [g].[FullName], [g].[HasSoulPatch], [g].[LeaderNickname], [g].[LeaderSquadId], [g].[Rank], [t].[HasSoulPatch] AS [HasSoulPatch0] FROM [Gears] AS [g] INNER JOIN ( SELECT MIN(CAST(LEN([g0].[Nickname]) AS int)) AS [c], [g0].[HasSoulPatch] FROM [Gears] AS [g0] WHERE [g0].[Nickname] <> N'Dom' GROUP BY [g0].[HasSoulPatch] ) AS [t] ON CAST(LEN([g].[Nickname]) AS int) = [t].[c] ORDER BY [g].[Nickname] OFFSET @__p_0 ROWS FETCH NEXT @__p_1 ROWS ONLY ) AS [t0] LEFT JOIN [Weapons] AS [w] ON [t0].[FullName] = [w].[OwnerFullName] ORDER BY [t0].[Nickname], [t0].[SquadId], [t0].[HasSoulPatch0]"); } private void AssertSql(params string[] expected) => Fixture.TestSqlLoggerFactory.AssertBaseline(expected); } }
45.988335
734
0.613114
[ "MIT" ]
NileshMoradiya/EntityFramework
test/EFCore.SqlServer.FunctionalTests/Query/GearsOfWarQuerySqlServerTest.cs
378,484
C#
namespace CustomizacaoMoradias.Data { internal class Element_RoomDM { public int RoomID { get; set; } public string ElementID { get; set; } public int Score { get; set; } } }
16.538462
45
0.595349
[ "MIT" ]
GBrunelli/CustomizacaoMoradias
Data/Element_RoomDM.cs
217
C#
#region License // Copyright (c) 2014 Tim Fischer // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the 'Software'), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. #endregion using System; using System.Configuration; using System.Linq; namespace Koden.Utils.REST.ConfigFileSections { /// <summary> /// /// </summary> /// <seealso cref="System.Configuration.ConfigurationElementCollection" /> [ConfigurationCollection(typeof(EndPointQueryElement))] public class QueryAppearanceCollection : ConfigurationElementCollection { internal const string PropertyName = "Query"; /// <summary> /// Gets the type of the <see cref="T:System.Configuration.ConfigurationElementCollection" />. /// </summary> public override ConfigurationElementCollectionType CollectionType { get { return ConfigurationElementCollectionType.BasicMapAlternate; } } /// <summary> /// Gets the name used to identify this collection of elements in the configuration file when overridden in a derived class. /// </summary> protected override string ElementName { get { return PropertyName; } } /// <summary> /// Indicates whether the specified <see cref="T:System.Configuration.ConfigurationElement" /> exists in the <see cref="T:System.Configuration.ConfigurationElementCollection" />. /// </summary> /// <param name="elementName">The name of the element to verify.</param> /// <returns> /// true if the element exists in the collection; otherwise, false. The default is false. /// </returns> protected override bool IsElementName(string elementName) { return elementName.Equals(PropertyName, StringComparison.InvariantCultureIgnoreCase); } /// <summary> /// Indicates whether the <see cref="T:System.Configuration.ConfigurationElementCollection" /> object is read only. /// </summary> /// <returns> /// true if the <see cref="T:System.Configuration.ConfigurationElementCollection" /> object is read only; otherwise, false. /// </returns> public override bool IsReadOnly() { return false; } /// <summary> /// When overridden in a derived class, creates a new <see cref="T:System.Configuration.ConfigurationElement" />. /// </summary> /// <returns> /// A newly created <see cref="T:System.Configuration.ConfigurationElement" />. /// </returns> protected override ConfigurationElement CreateNewElement() { return new EndPointQueryElement(); } /// <summary> /// Gets the element key for a specified configuration element when overridden in a derived class. /// </summary> /// <param name="element">The <see cref="T:System.Configuration.ConfigurationElement" /> to return the key for.</param> /// <returns> /// An <see cref="T:System.Object" /> that acts as the key for the specified <see cref="T:System.Configuration.ConfigurationElement" />. /// </returns> protected override object GetElementKey(ConfigurationElement element) { return ((EndPointQueryElement)(element)).name; } /// <summary> /// Gets the <see cref="EndPointQueryElement" /> with the specified index. /// </summary> /// <value> /// The <see cref="EndPointQueryElement" />. /// </value> /// <param name="idx">The index.</param> /// <returns></returns> public EndPointQueryElement this[int idx] => (EndPointQueryElement)BaseGet(idx); //public EndPointQueryElement this[string name] => (EndPointQueryElement)BaseGet(name); } }
39.015873
186
0.646257
[ "Unlicense" ]
TJF0700/Koden
Koden.Utils.REST/ConfigFileSections/QueryAppearanceCollection.cs
4,916
C#
namespace Poker.Test { using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class CardTest { [TestMethod] public void CardShouldCompareCardsCorrectly_EqualCard() { var cardA = new Card(CardFace.Jack, CardSuit.Spades); var cardB = new Card(CardFace.Jack, CardSuit.Spades); Assert.IsTrue(cardA.Equals(cardB)); } [TestMethod] public void CardShouldCompareCardsCorrectly_DifferentCards() { var cardA = new Card(CardFace.Jack, CardSuit.Spades); var cardB = new Card(CardFace.Queen, CardSuit.Hearts); Assert.IsFalse(cardA.Equals(cardB)); } [TestMethod] public void CardShouldReturnToStringCorrectly() { var card = new Card(CardFace.Jack, CardSuit.Spades); var expected = "Jack of Spades"; Assert.AreEqual(expected, card.ToString()); } } }
27.277778
68
0.601833
[ "MIT" ]
SimoPrG/HighQualityCodeHomework
TestDrivenDevelopment/Poker.Test/CardTest.cs
984
C#
using System.IO; using Microsoft.AspNetCore.Mvc; using SixLabors.ImageSharp; using SixLabors.ImageSharp.PixelFormats; namespace Daniel15.Web.Extensions { /// <summary> /// Extension methods for ImageSharp /// </summary> public static class ImageSharpExtensions { /// <summary> /// Wraps the specified image in an MVC ActionResult /// </summary> /// <param name="image">Image to return</param> /// <returns>ActionResult containing this image</returns> public static ActionResult ToActionResult<T>(this Image<T> image) where T : struct, IPixel<T> { // Must NOT dispose this stream - The MVC framework disposes it for us. var stream = new MemoryStream(); image.SaveAsPng(stream); stream.Seek(0, SeekOrigin.Begin); return new FileStreamResult(stream, "image/png"); } } }
28.892857
95
0.714462
[ "MIT", "Unlicense" ]
DLN-India/Website
Daniel15.Web/Extensions/ImageSharpExtensions.cs
811
C#
//----------------------------------------------------------------------- // <copyright file="ContextMenuTools.cs" company="Lost Signal LLC"> // Copyright (c) Lost Signal LLC. All rights reserved. // </copyright> //----------------------------------------------------------------------- namespace Lost { using System; using System.IO; using UnityEditor; public static class ContextMenuTools { [MenuItem("Assets/Lost/Copy GUID")] public static void PrintGuid() { if (Selection.assetGUIDs.Length == 1) { EditorGUIUtility.systemCopyBuffer = Selection.assetGUIDs[0]; } } [MenuItem("Assets/Lost/Regenerate All Folder Guids")] public static void DeleteAllFolderMetaFiles() { if (Selection.activeObject == null) { UnityEngine.Debug.LogError("You must select a directory for this option to work."); return; } string rootDirectoryAssetPath = AssetDatabase.GetAssetPath(Selection.activeObject.GetInstanceID()); if (Directory.Exists(rootDirectoryAssetPath) == false) { UnityEngine.Debug.LogError("You must select a directory for this option to work."); return; } foreach (var directory in Directory.GetDirectories(rootDirectoryAssetPath, "*", SearchOption.AllDirectories)) { var assetPath = directory.Replace("\\", "/"); var asset = AssetDatabase.LoadAssetAtPath(assetPath, typeof(UnityEngine.Object)); var assetGuid = AssetDatabase.AssetPathToGUID(assetPath); var newGuid = Guid.NewGuid().ToString("N"); string metaFilePath = assetPath + ".meta"; if (File.Exists(metaFilePath)) { // NOTE [bgish]: Not sure why, but this only seems to get half the folders // Provider.Checkout(asset, CheckoutMode.Both).Wait(); File.WriteAllText(metaFilePath, File.ReadAllText(metaFilePath).Replace(assetGuid, newGuid)); } } } [MenuItem("Assets/Lost/Get LoC")] public static void LinesOfCode() { if (Selection.activeObject == null) { UnityEngine.Debug.LogError("You must select a directory for this option to work."); return; } string rootDirectoryAssetPath = AssetDatabase.GetAssetPath(Selection.activeObject.GetInstanceID()); if (Directory.Exists(rootDirectoryAssetPath) == false) { UnityEngine.Debug.LogError("You must select a directory for this option to work."); return; } int linesOfCodeCount = 0; int fileCount = 0; foreach (var file in Directory.GetFiles(rootDirectoryAssetPath, "*.cs", SearchOption.AllDirectories)) { fileCount++; foreach (var line in File.ReadAllLines(file)) { string trimmedLine = line.Trim(); if (string.IsNullOrWhiteSpace(trimmedLine) || trimmedLine == "{" || trimmedLine == "}" || trimmedLine.StartsWith("//")) { continue; } linesOfCodeCount++; } } UnityEngine.Debug.Log("C# File Count: " + fileCount); UnityEngine.Debug.Log("Line Count: " + linesOfCodeCount); } } }
36.207921
139
0.525294
[ "Unlicense", "MIT" ]
LostSignal/Lost-Library
Lost/Lost.EditorTools/Editor/ContextMenu/ContextMenuTools.cs
3,659
C#
using System; using System.Collections.Generic; using System.IO; using BizHawk.Emulation.Common; namespace BizHawk.Client.Common { internal class BkmMovie { private readonly List<string> _log = new List<string>(); public BkmHeader Header { get; } = new BkmHeader(); public string Filename { get; set; } = ""; public bool Loaded { get; private set; } public int InputLogLength => Loaded ? _log.Count : 0; public BkmControllerAdapter GetInputState(int frame, ControllerDefinition definition, string sytemId) { if (frame < InputLogLength && frame >= 0) { var adapter = new BkmControllerAdapter(definition, sytemId); adapter.SetControllersAsMnemonic(_log[frame]); return adapter; } return null; } public SubtitleList Subtitles => Header.Subtitles; public IList<string> Comments => Header.Comments; public string SyncSettingsJson { get => Header[HeaderKeys.SyncSettings]; set => Header[HeaderKeys.SyncSettings] = value; } public byte[] BinarySavestate { get; set; } public bool Load() { var file = new FileInfo(Filename); if (file.Exists == false) { Loaded = false; return false; } Header.Clear(); _log.Clear(); using (var sr = file.OpenText()) { string line; while ((line = sr.ReadLine()) != null) { if (line == "") { } else if (Header.ParseLineFromFile(line)) { } else if (line.StartsWith("|")) { _log.Add(line); } else { Header.Comments.Add(line); } } } if (Header.SavestateBinaryBase64Blob != null) { BinarySavestate = Convert.FromBase64String(Header.SavestateBinaryBase64Blob); } Loaded = true; return true; } } }
20.209302
103
0.640391
[ "MIT" ]
CartoonFan/BizHawk
src/BizHawk.Client.Common/movie/import/bkm/BkmMovie.cs
1,740
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using System; using System.Linq; using System.Threading.Tasks; using Microsoft.CodeAnalysis.CodeFixes; using Microsoft.CodeAnalysis.CSharp.RemoveUnnecessaryParentheses; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.Diagnostics; using Microsoft.CodeAnalysis.Test.Utilities; using Microsoft.CodeAnalysis.Text; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.RemoveUnnecessaryParentheses { public partial class RemoveUnnecessaryParenthesesTests : AbstractCSharpDiagnosticProviderBasedUserDiagnosticTest { internal override (DiagnosticAnalyzer, CodeFixProvider) CreateDiagnosticProviderAndFixer(Workspace workspace) => (new CSharpRemoveUnnecessaryParenthesesDiagnosticAnalyzer(), new CSharpRemoveUnnecessaryParenthesesCodeFixProvider()); private async Task TestAsync(string initial, string expected, bool offeredWhenRequireForClarityIsEnabled, int index = 0) { await TestInRegularAndScriptAsync(initial, expected, options: RemoveAllUnnecessaryParentheses, index: index); if (offeredWhenRequireForClarityIsEnabled) { await TestInRegularAndScriptAsync(initial, expected, options: RequireAllParenthesesForClarity, index: index); } else { await TestMissingAsync(initial, parameters: new TestParameters(options: RequireAllParenthesesForClarity)); } } internal override bool ShouldSkipMessageDescriptionVerification(DiagnosticDescriptor descriptor) { return descriptor.CustomTags.Contains(WellKnownDiagnosticTags.Unnecessary) && descriptor.DefaultSeverity == DiagnosticSeverity.Hidden; } private DiagnosticDescription GetRemoveUnnecessaryParenthesesDiagnostic(string text, int line, int column) => TestHelpers.Diagnostic(IDEDiagnosticIds.RemoveUnnecessaryParenthesesDiagnosticId, text, startLocation: new LinePosition(line, column)); private DiagnosticDescription GetRemoveUnnecessaryParenthesesDiagnostic(string text, int line, int column, DiagnosticSeverity severity) => GetRemoveUnnecessaryParenthesesDiagnostic(text, line, column).WithEffectiveSeverity(severity); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestVariableInitializer_TestWithAllOptionsSetToIgnore() { await TestMissingAsync( @"class C { void M() { int x = $$(1); } }", new TestParameters(options: IgnoreAllParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] [WorkItem(29736, "https://github.com/dotnet/roslyn/issues/29736")] public async Task TestVariableInitializer_TestMissingParenthesis() { await TestMissingAsync( @"class C { void M() { int x = $$(1; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticRequiredForClarity1() { await TestMissingAsync( @"class C { void M() { int x = 1 + $$(2 * 3); } }", new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticRequiredForClarity2() { await TestInRegularAndScript1Async( @"class C { void M() { int x = a || $$(b && c); } }", @"class C { void M() { int x = a || b && c; } }", parameters: new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLogicalRequiredForClarity1() { await TestMissingAsync( @"class C { void M() { int x = a || $$(b && c); } }", new TestParameters(options: RequireOtherBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLogicalRequiredForClarity2() { await TestInRegularAndScript1Async( @"class C { void M() { int x = a + $$(b * c); } }", @"class C { void M() { int x = a + b * c; } }", parameters: new TestParameters(options: RequireOtherBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Integral1() { await TestAsync( @"class C { void M() { int x = 1 + $$(2 + 3); } }", @"class C { void M() { int x = 1 + 2 + 3; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Integral2() { await TestAsync( @"class C { void M() { int x = $$(1 + 2) + 3; } }", @"class C { void M() { int x = 1 + 2 + 3; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticRequiredForCorrectnessWhenPrecedenceStaysTheSameIfFloatingPoint() { await TestMissingAsync( @"class C { void M() { int x = 1.0 + $$(2.0 + 3.0); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArithmeticNotRequiredForClarityWhenPrecedenceStaysTheSame_Floating2() { await TestAsync( @"class C { void M() { int x = $$(1.0 + 2.0) + 3.0; } }", @"class C { void M() { int x = 1.0 + 2.0 + 3.0; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame1() { await TestAsync( @"class C { void M() { int x = a || $$(b || c); } }", @"class C { void M() { int x = a || b || c; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLogicalNotRequiredForClarityWhenPrecedenceStaysTheSame2() { await TestAsync( @"class C { void M() { int x = $$(a || b) || c; } }", @"class C { void M() { int x = a || b || c; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestVariableInitializer_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int x = $$(1); } }", @"class C { void M() { int x = 1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestReturnStatement_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { return $$(1 + 2); } }", @"class C { void M() { return 1 + 2; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestExpressionBody_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { int M() => $$(1 + 2); }", @"class C { int M() => 1 + 2; }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCheckedExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = checked($$(1 + 2)); } }", @"class C { void M() { int i = checked(1 + 2); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAssignment_TestAvailableWithAlwaysRemove_And_TestNotAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { i = $$(1 + 2); } }", @"class C { void M() { i = 1 + 2; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCompoundAssignment_TestAvailableWithAlwaysRemove_And_TestNotAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { i *= $$(1 + 2); } }", @"class C { void M() { i *= 1 + 2; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPimaryAssignment_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { i = $$(s.Length); } }", @"class C { void M() { i = s.Length; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNestedParenthesizedExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = ( $$(1 + 2) ); } }", @"class C { void M() { int i = ( 1 + 2 ); } }", offeredWhenRequireForClarityIsEnabled: true, index: 1); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestIncrementExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = $$(x++); } }", @"class C { void M() { int i = x++; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestLambdaBody_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { Func<int> i = () => $$(1); } }", @"class C { void M() { Func<int> i = () => 1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayElement_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int[] i = new int[] { $$(1) }; } }", @"class C { void M() { int[] i = new int[] { 1 }; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestWhereClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { var q = from c in customer where $$(c.Age > 21) select c; } }", @"class C { void M() { var q = from c in customer where c.Age > 21 select c; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = (int)$$(1); } }", @"class C { void M() { int i = (int)1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForConditionalAccess1() { await TestMissingAsync( @"class C { void M(string s) { var v = $$(s?.Length).ToString(); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(37046, "https://github.com/dotnet/roslyn/issues/37046")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForConditionalAccess2() { await TestMissingAsync( @"class C { void M(string s) { var v = $$(s?.Length)?.ToString(); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForConditionalAccessNotInExpression() { await TestInRegularAndScriptAsync( @"class C { void M(string s) { var v = $$(s?.Length); } }", @"class C { void M(string s) { var v = s?.Length; } }", options: RemoveAllUnnecessaryParentheses); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForConditionalIndex() { await TestMissingAsync( @"class C { void M(string s) { var v = $$(s?[0]).ToString(); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBinaryInCastExpression() { await TestMissingAsync( @"class C { void M() { int i = (int)$$(1 + 2); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAroundCastExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { int i = $$((int)1); } }", @"class C { void M() { int i = (int)1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalInInterpolation() { await TestMissingAsync( @"class C { void M() { var s = $""{ $$(a ? b : c) }""; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalInInterpolation_FixAll_1() { await TestAsync( @"class C { void M() { var s1 = $""{ {|FixAllInDocument:(|}(a ? b : c)) }""; var s2 = $""{ ((a ? b : c)) }""; } }", @"class C { void M() { var s1 = $""{ (a ? b : c) }""; var s2 = $""{ (a ? b : c) }""; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalInInterpolation_FixAll_2() { await TestAsync( @"class C { void M() { var s1 = $""{ ({|FixAllInDocument:(|}a ? b : c)) }""; var s2 = $""{ ((a ? b : c)) }""; } }", @"class C { void M() { var s1 = $""{ (a ? b : c) }""; var s2 = $""{ (a ? b : c) }""; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNonConditionalInInterpolation_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { var s = $""{ $$(true) }""; } }", @"class C { void M() { var s = $""{ true }""; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBinaryExpression_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_1() { await TestAsync( @"class C { void M() { var q = $$(a * b) + c; } }", @"class C { void M() { var q = a * b + c; } }", offeredWhenRequireForClarityIsEnabled: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBinaryExpression_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_2() { await TestAsync( @"class C { void M() { var q = c + $$(a * b); } }", @"class C { void M() { var q = c + a * b; } }", offeredWhenRequireForClarityIsEnabled: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestNotAvailableForComplexChildren1() { await TestMissingAsync( @"class C { void M() { var q = $$(a * b) ? (1 + 2) : (3 + 4); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestNotAvailableForComplexChildren2() { await TestMissingAsync( @"class C { void M() { var q = (a * b) ? $$(1 + 2) : (3 + 4); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestNotAvailableForComplexChildren3() { await TestMissingAsync( @"class C { void M() { var q = (a * b) ? (1 + 2) : $$(3 + 4); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestAvailableForPrimaryChildren1() { await TestAsync( @"class C { void M() { var q = $$(a.X()) ? (1 + 2) : (3 + 4); } }", @"class C { void M() { var q = a.X() ? (1 + 2) : (3 + 4); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestAvailableForPrimaryChildren2() { await TestAsync( @"class C { void M() { var q = (a.X()) ? $$(x.Length) : (3 + 4); } }", @"class C { void M() { var q = (a.X()) ? x.Length : (3 + 4); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpression_TestAvailableForPrimaryChildren3() { await TestAsync( @"class C { void M() { var q = (a.X()) ? (1 + 2) : $$(a[0]); } }", @"class C { void M() { var q = (a.X()) ? (1 + 2) : a[0]; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestIsPattern_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_1() { await TestAsync( @"class C { void M() { if ( $$(a[0]) is string s) { } } }", @"class C { void M() { if ( a[0] is string s) { } } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestIsPattern_TestAvailableWithAlwaysRemove_And_NotAvailableWhenRequiredForClarity_2() { await TestAsync( @"class C { void M() { if ( $$(a * b) is int i) { } } }", @"class C { void M() { if ( a * b is int i) { } } }", offeredWhenRequireForClarityIsEnabled: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForOverloadedOperatorOnLeft() { await TestInRegularAndScript1Async( @"class C { void M(C c1, C c2, C c3) { var x = $$(c1 + c2) + c3; } public static C operator +(C c1, C c2) => null; }", @"class C { void M(C c1, C c2, C c3) { var x = c1 + c2 + c3; } public static C operator +(C c1, C c2) => null; }", parameters: new TestParameters(options: RequireAllParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForOverloadedOperatorOnRight() { await TestMissingAsync( @"class C { void M(C c1, C c2, C c3) { var x = c1 + $$(c2 + c3); } public static C operator +(C c1, C c2) => null; }", parameters: new TestParameters(options: RequireAllParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestShiftRequiredForClarity1() { await TestMissingAsync( @"class C { void M() { int x = $$(1 + 2) << 3; } }", parameters: new TestParameters(options: RequireArithmeticBinaryParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestShiftRequiredForClarity2() { await TestMissingAsync( @"class C { void M() { int x = $$(1 + 2) << 3; } }", parameters: new TestParameters(options: RequireAllParenthesesForClarity)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestDoNotRemoveShiftAcrossPrecedence() { await TestMissingAsync( @"class C { void M() { int x = $$(1 + 2) << 3; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRemoveShiftIfNotNecessary2() { await TestInRegularAndScript1Async( @"class C { void M() { int x = $$(1 << 2) << 3; } }", @"class C { void M() { int x = 1 << 2 << 3; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestDoNotRemoveShiftAcrossSamePrecedenceIfValueWouldChange() { await TestMissingAsync( @"class C { void M() { int x = 1 << $$(2 << 3); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestDoNotRemoveShiftIfShiftKindDiffers() { await TestMissingAsync( @"class C { void M() { int x = $$(1 >> 2) << 3; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRemoveCoalesceIfNotNecessary1() { await TestMissingAsync( @"class C { void M() { int x = $$(a ?? b) ?? c; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestRemoveCoalesceIfNotNecessary2() { await TestInRegularAndScript1Async( @"class C { void M() { int x = a ?? $$(b ?? c); } }", @"class C { void M() { int x = a ?? b ?? c; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBitwiseExpression_TestMissingWithDifferencePrecedence1() { await TestMissingAsync( @"class C { void M() { var q = $$(a + b) & c; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBitwiseExpression_TestMissingWithDifferencePrecedence2() { await TestMissingAsync( @"class C { void M() { var q = $$(a | b) & c; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestBitwiseExpression_TestAvailableWithSamePrecedenceMissingWithDifferencePrecedence2() { await TestAsync( @"class C { void M() { var q = $$(a & b) & c; } }", @"class C { void M() { var q = a & b & c; } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestSwitchCase_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { switch (true) { case $$(default(bool)): } } }", @"class C { void M() { switch (true) { case default(bool): } } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestSwitchCase_WithWhenClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { switch (true) { case $$(default(bool)) when true: } } }", @"class C { void M() { switch (true) { case default(bool) when true: } } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestWhenClause_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { switch (true) { case true when $$(default(bool)): } } }", @"class C { void M() { switch (true) { case true when default(bool): } } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConstantPatternExpression_TestAvailableWithAlwaysRemove_And_TestAvailableWhenRequiredForClarity() { await TestAsync( @"class C { void M() { if (true is $$(default(bool))) { } } }", @"class C { void M() { if (true is default(bool)) { } } }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(25554, "https://github.com/dotnet/roslyn/issues/25554")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConstantPatternExpression_RequiredForPrecedence() { await TestMissingAsync( @"class C { void M(string s) { if (true is $$(true == true)) { } } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastAmbiguity1() { await TestMissingAsync( @"class C { void M() { int x = (X)$$(-1); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastAmbiguity2() { await TestMissingAsync( @"class C { void M() { int x = (X)$$(+1); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastAmbiguity3() { await TestMissingAsync( @"class C { void M() { int x = (X)$$(&1); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastAmbiguity4() { await TestMissingAsync( @"class C { void M() { int x = (X)$$(*1); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPrimitiveCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (int)$$(-1); } }", @"class C { void M() { int x = (int)-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPrimitiveCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (int)$$(+1); } }", @"class C { void M() { int x = (int)+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPrimitiveCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (int)$$(&x); } }", @"class C { void M() { int x = (int)&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPrimitiveCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (int)$$(*x); } }", @"class C { void M() { int x = (int)*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (T[])$$(-1); } }", @"class C { void M() { int x = (T[])-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (T[])$$(+1); } }", @"class C { void M() { int x = (T[])+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (T[])$$(&x); } }", @"class C { void M() { int x = (T[])&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestArrayCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (T[])$$(*x); } }", @"class C { void M() { int x = (T[])*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPointerCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (T*)$$(-1); } }", @"class C { void M() { int x = (T*)-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPointerCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (T*)$$(+1); } }", @"class C { void M() { int x = (T*)+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPointerCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (T*)$$(&x); } }", @"class C { void M() { int x = (T*)&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestPointerCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (T*)$$(*x); } }", @"class C { void M() { int x = (T*)*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNullableCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (T?)$$(-1); } }", @"class C { void M() { int x = (T?)-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNullableCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (T?)$$(+1); } }", @"class C { void M() { int x = (T?)+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNullableCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (T?)$$(&x); } }", @"class C { void M() { int x = (T?)&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNullableCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (T?)$$(*x); } }", @"class C { void M() { int x = (T?)*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAliasCastNoAmbiguity1() { await TestAsync( @"class C { void M() { int x = (e::N.T)$$(-1); } }", @"class C { void M() { int x = (e::N.T)-1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAliasCastNoAmbiguity2() { await TestAsync( @"class C { void M() { int x = (e::N.T)$$(+1); } }", @"class C { void M() { int x = (e::N.T)+1; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAliasCastNoAmbiguity3() { await TestAsync( @"class C { void M() { int x = (e::N.T)$$(&x); } }", @"class C { void M() { int x = (e::N.T)&x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestAliasCastNoAmbiguity4() { await TestAsync( @"class C { void M() { int x = (e::N.T)$$(*x); } }", @"class C { void M() { int x = (e::N.T)*x; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastOfPrimary() { await TestAsync( @"class C { void M() { int x = (X)$$(a); } }", @"class C { void M() { int x = (X)a; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastOfMemberAccess() { await TestAsync( @"class C { void M() { int x = (X)$$(a.b); } }", @"class C { void M() { int x = (X)a.b; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastOfNonAmbiguousUnary() { await TestAsync( @"class C { void M() { int x = (X)$$(!a); } }", @"class C { void M() { int x = (X)!a; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestCastOfCast() { await TestAsync( @"class C { void M() { int x = (X)$$((Y)a); } }", @"class C { void M() { int x = (X)(Y)a; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestIsPatternAndLogical_TestWithAllOptionsSetToIgnore() { await TestAsync( @"class C { void M(object expression) { if ($$(expression is bool b) && b) { } } }", @"class C { void M(object expression) { if (expression is bool b && b) { } } }", offeredWhenRequireForClarityIsEnabled: false); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestGuardPatternMissing() { await TestMissingAsync( @"class C { void M(object expression) { if (!$$(expression is bool b)) { } } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundLValueMemberAccess() { await TestAsync( @"class C { void M() { $$(this.Property) = Property; } }", @"class C { void M() { this.Property = Property; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundMultiplicationInAddEquals() { await TestAsync( @"class C { void M() { x += $$(y * z) } }", @"class C { void M() { x += y * z } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundAddInMultipleEquals() { await TestAsync( @"class C { void M() { x *= $$(y + z) } }", @"class C { void M() { x *= y + z } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNecessaryCast() { await TestMissingAsync( @"class C { void M() { $$((short)3).ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundChecked() { await TestAsync( @"class C { void M() { int x = 3 * $$(checked(5)); } }", @"class C { void M() { int x = 3 * checked(5); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundUnchecked() { await TestAsync( @"class C { void M() { int x = 3 * $$(unchecked(5)); } }", @"class C { void M() { int x = 3 * unchecked(5); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundNameof() { await TestAsync( @"class C { void M() { string property = ""My "" + $$(nameof(property)); } }", @"class C { void M() { string property = ""My "" + nameof(property); } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensIsCheck() { await TestAsync( @"class C { void M() { bool x = $$("""" is string); } }", @"class C { void M() { bool x = """" is string; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestNecessaryParensAroundIs() { await TestMissingAsync( @"class C { void M() { string x = $$("""" is string).ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundAssignmentInInitialization() { await TestAsync( @"class C { void M() { string y; string x = $$(y = ""text""); } }", @"class C { void M() { string y; string x = y = ""text""; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundLambda1() { await TestAsync( @"class C { void M() { Func<string, string> y2 = $$(v => v); } }", @"class C { void M() { Func<string, string> y2 = v => v; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundLambda2() { await TestAsync( @"class C { void M() { Func<string, string> y2 = $$((v) => v); } }", @"class C { void M() { Func<string, string> y2 = (v) => v; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundCastedLambda1() { await TestMissingAsync( @"class C { void M() { string y = ((Func<string, string>)$$((v) => v))(""text""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundCastedLambda2() { await TestMissingAsync( @"class C { void M() { string y = ($$(Func<string, string>)((v) => v))(""text""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundCastedLambda3() { await TestMissingAsync( @"class C { void M() { string y = $$((Func<string, string>)((v) => v))(""text""); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundReturnValue1() { await TestAsync( @"class C { void M() { return$$(value); } }", @"class C { void M() { return value; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundReturnValue2() { await TestAsync( @"class C { void M() { return $$(value); } }", @"class C { void M() { return value; } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundPPDirective1() { await TestAsync( @"class C { void M() { #if$$(A || B) #endif } }", @"class C { void M() { #ifA || B #endif } }", offeredWhenRequireForClarityIsEnabled: true); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestParensAroundPPDirective2() { // Currently producing broken code. await TestAsync( @"class C { void M() { #if( $$(A || B) || C) #endif } }", @"class C { void M() { #if( A || B || C) #endif } }", offeredWhenRequireForClarityIsEnabled: true, index: 1); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForPreIncrement() { await TestMissingAsync( @"class C { void M(int x) { var v = (byte)$$(++x); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForPreDecrement() { await TestMissingAsync( @"class C { void M(int x) { var v = (byte)$$(--x); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPostIncrement() { await TestInRegularAndScript1Async( @"class C { void M(int x) { var v = (byte)$$(x++); } }", @"class C { void M(int x) { var v = (byte)x++; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPostDecrement() { await TestInRegularAndScript1Async( @"class C { void M(int x) { var v = (byte)$$(x--); } }", @"class C { void M(int x) { var v = (byte)x--; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPreIncrementInLocalDeclaration() { await TestInRegularAndScript1Async( @"class C { void M(int x) { var v = $$(++x); } }", @"class C { void M(int x) { var v = ++x; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPreIncrementInSimpleAssignment() { await TestInRegularAndScript1Async( @"class C { void M(int x, int v) { v = $$(++x); } }", @"class C { void M(int x, int v) { v = ++x; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestForPreIncrementInArgument() { await TestInRegularAndScript1Async( @"class C { void M(int x) { M($$(++x)); } }", @"class C { void M(int x) { M(++x); } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForPreIncrementAfterAdd() { await TestMissingAsync( @"class C { void M(int x) { var v = x+$$(++x); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(29454, "https://github.com/dotnet/roslyn/issues/29454")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForUnaryPlusAfterAdd() { await TestMissingAsync( @"class C { void M(int x) { var v = x+$$(+x); } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(31103, "https://github.com/dotnet/roslyn/issues/31103")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForConditionalRefAsLeftHandSideValue() { await TestMissingAsync( @"class Bar { void Foo(bool cond, double a, double b) { [||](cond ? ref a : ref b) = 6.67e-11; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(31103, "https://github.com/dotnet/roslyn/issues/31103")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestConditionalExpressionAsRightHandSideValue() { await TestInRegularAndScript1Async( @"class Bar { void Foo(bool cond, double a, double b) { double c = $$(cond ? a : b); } }", @"class Bar { void Foo(bool cond, double a, double b) { double c = cond ? a : b; } }", parameters: new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(32085, "https://github.com/dotnet/roslyn/issues/32085")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestMissingForNestedConditionalExpressionInLambda() { await TestMissingAsync( @"class Bar { void Test(bool a) { Func<int, string> lambda = number => number + $""{ ($$a ? ""foo"" : ""bar"") }""; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses)); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/27925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisDiagnosticSingleLineExpression() { var parentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(1 + 2)", 4, 16); await TestDiagnosticsAsync( @"class C { void M() { int x = [|(1 + 2)|]; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses), parentheticalExpressionDiagnostic); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/27925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisDiagnosticInMultiLineExpression() { var firstLineParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(1 +", 4, 16); await TestDiagnosticsAsync( @"class C { void M() { int x = [|(1 + 2)|]; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses), firstLineParentheticalExpressionDiagnostic); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/27925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisDiagnosticInNestedExpression() { var outerParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(1 + (2 + 3) + 4)", 4, 16); var innerParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(2 + 3)", 4, 21); var expectedDiagnostics = new DiagnosticDescription[] { outerParentheticalExpressionDiagnostic, innerParentheticalExpressionDiagnostic }; await TestDiagnosticsAsync( @"class C { void M() { int x = [|(1 + (2 + 3) + 4)|]; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses), expectedDiagnostics); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/27925")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisDiagnosticInNestedMultiLineExpression() { var outerFirstLineParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(1 + 2 +", 4, 16); var innerParentheticalExpressionDiagnostic = GetRemoveUnnecessaryParenthesesDiagnostic("(3 + 4)", 5, 12); var expectedDiagnostics = new DiagnosticDescription[] { outerFirstLineParentheticalExpressionDiagnostic, innerParentheticalExpressionDiagnostic }; await TestDiagnosticsAsync( @"class C { void M() { int x = [|(1 + 2 + (3 + 4) + 5 + 6)|]; } }", new TestParameters(options: RemoveAllUnnecessaryParentheses), expectedDiagnostics); } [WorkItem(39529, "https://github.com/dotnet/roslyn/issues/39529")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesisIncludesFadeLocations() { var input = @"class C { void M() { int x = [|{|expression:{|fade:(|}1 + 2{|fade:)|}|}|]; } }"; var parameters = new TestParameters(options: RemoveAllUnnecessaryParentheses); using var workspace = CreateWorkspaceFromOptions(input, parameters); var expectedSpans = workspace.Documents.First().AnnotatedSpans; var diagnostics = await GetDiagnosticsAsync(workspace, parameters).ConfigureAwait(false); var diagnostic = diagnostics.Single(); Assert.Equal(3, diagnostic.AdditionalLocations.Count); Assert.Equal(expectedSpans["expression"].Single(), diagnostic.AdditionalLocations[0].SourceSpan); Assert.Equal(expectedSpans["fade"][0], diagnostic.AdditionalLocations[1].SourceSpan); Assert.Equal(expectedSpans["fade"][1], diagnostic.AdditionalLocations[2].SourceSpan); Assert.Equal("[1,2]", diagnostic.Properties[WellKnownDiagnosticTags.Unnecessary]); } [WorkItem(27925, "https://github.com/dotnet/roslyn/issues/39363")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesesInSwitchExpression() { await TestAsync( @"class C { void M(int x) { var result = x switch { 1 => $$(5), 2 => 10 + 5, _ => 100, } }; }", @"class C { void M(int x) { var result = x switch { 1 => 5, 2 => 10 + 5, _ => 100, } }; }", offeredWhenRequireForClarityIsEnabled: true); } [WorkItem(26311, "https://github.com/dotnet/roslyn/issues/26311")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsRemoveUnnecessaryParentheses)] public async Task TestUnnecessaryParenthesesAroundDefaultLiteral() { await TestAsync( @"class C { void M() { bool f = false; string s2 = f ? """" : $$(default); } }", @"class C { void M() { bool f = false; string s2 = f ? """" : default; } }", offeredWhenRequireForClarityIsEnabled: true); } } }
24.137223
158
0.599507
[ "Apache-2.0" ]
HenrikWM/roslyn
src/EditorFeatures/CSharpTest/RemoveUnnecessaryParentheses/RemoveUnnecessaryParenthesesTests.cs
59,983
C#
using System; using System.Collections.Generic; using System.Threading; using Amazon.Lambda.Core; using Microsoft.Extensions.Logging; namespace Logicality.Lambda.TestHost { public class LambdaTestHostSettings { private readonly Dictionary<string, LambdaFunctionInfo> _functions = new Dictionary<string, LambdaFunctionInfo>(); /// <summary> /// The URL the lambda test host will listen on. Default value is http://127.0.0.1:0 /// which will listen on a random free port. To get the URL to invoke lambdas, use /// LambdaTestHost.ServiceUrl. /// </summary> public string WebHostUrl { get; set; } = "http://*:0"; public LambdaTestHostSettings(Func<ILambdaContext> createContext) { CreateContext = createContext; } /// <summary> /// Gets or sets the maximum concurrency limit for all hosted lambdas. /// </summary> public uint AccountConcurrencyLimit { get; set; } = 1000; internal Func<ILambdaContext> CreateContext { get; } public Action<ILoggingBuilder> ConfigureLogging { get; set; } = _ => { }; public IReadOnlyDictionary<string, LambdaFunctionInfo> Functions => _functions; //Used in tests to signal the start of an invocation. internal AutoResetEvent InvocationOnStart => new AutoResetEvent(false); public void AddFunction(LambdaFunctionInfo lambdaFunctionInfo) { _functions.Add(lambdaFunctionInfo.Name, lambdaFunctionInfo); } } }
35.409091
122
0.664313
[ "MIT" ]
logicality-io/dotnet-libs
libs/lambda/src/Lambda.TestHost/LambdaTestHostSettings.cs
1,560
C#
// Copyright (c) 2019 .NET Foundation and Contributors. All rights reserved. // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for full license information. using System; using Splat.Tests.Mocks; using Xunit; namespace Splat.Tests.Logging { /// <summary> /// Tests associated with the <see cref="ActionLogger"/> class. /// </summary> public class ActionLoggerTests { /// <summary> /// Test to make sure the message writes. /// </summary> [Fact] public void Write_Should_Emit_Message() { string passedMessage = null; LogLevel? passedLevel = null; var logger = new ActionLogger( (message, level) => { passedMessage = message; passedLevel = level; }, null, null, null); var fullLogger = new WrappingFullLogger(logger); fullLogger.Write("This is a test.", LogLevel.Debug); Assert.Equal("This is a test.", passedMessage); Assert.Equal(LogLevel.Debug, passedLevel); } /// <summary> /// Test to make sure the generic type parameter is passed to the logger. /// </summary> [Fact] public void Debug_With_Generic_Type_Should_Emit_Message_And_Type() { string passedMessage = null; LogLevel? passedLevel = null; Type passedType = null; var logger = new ActionLogger( null, (message, type, level) => { passedMessage = message; passedType = type; passedLevel = level; }, null, null); var fullLogger = new WrappingFullLogger(logger); fullLogger.Debug<DummyObjectClass1>("This is a test."); Assert.Equal("This is a test.", passedMessage); Assert.Equal(LogLevel.Debug, passedLevel); Assert.Equal(typeof(DummyObjectClass1), passedType); } /// <summary> /// Test to make sure the generic type parameter is passed to the logger. /// </summary> [Fact] public void Debug_With_Generic_Type_Should_Emit_Message_And_Type_Provided() { string passedMessage = null; LogLevel? passedLevel = null; Type passedType = null; var logger = new ActionLogger( null, (message, type, level) => { passedMessage = message; passedType = type; passedLevel = level; }, null, null); var fullLogger = new WrappingFullLogger(logger); fullLogger.Debug<DummyObjectClass2>("This is a test."); Assert.Equal("This is a test.", passedMessage); Assert.Equal(LogLevel.Debug, passedLevel); Assert.Equal(typeof(DummyObjectClass2), passedType); } /// <summary> /// Test to make sure the generic type parameter is passed to the logger. /// </summary> [Fact] public void Info_With_Generic_Type_Should_Emit_Message_And_Type() { string passedMessage = null; LogLevel? passedLevel = null; Type passedType = null; var logger = new ActionLogger( null, (message, type, level) => { passedMessage = message; passedType = type; passedLevel = level; }, null, null); var fullLogger = new WrappingFullLogger(logger); fullLogger.Info<DummyObjectClass1>("This is a test."); Assert.Equal("This is a test.", passedMessage); Assert.Equal(LogLevel.Info, passedLevel); Assert.Equal(typeof(DummyObjectClass1), passedType); } /// <summary> /// Test to make sure the generic type parameter is passed to the logger. /// </summary> [Fact] public void Info_With_Generic_Type_Should_Emit_Message_And_Type_Provided() { string passedMessage = null; LogLevel? passedLevel = null; Type passedType = null; var logger = new ActionLogger( null, (message, type, level) => { passedMessage = message; passedType = type; passedLevel = level; }, null, null); var fullLogger = new WrappingFullLogger(logger); fullLogger.Info<DummyObjectClass2>("This is a test."); Assert.Equal("This is a test.", passedMessage); Assert.Equal(LogLevel.Info, passedLevel); Assert.Equal(typeof(DummyObjectClass2), passedType); } /// <summary> /// Test to make sure the generic type parameter is passed to the logger. /// </summary> [Fact] public void Warn_With_Generic_Type_Should_Emit_Message_And_Type() { string passedMessage = null; LogLevel? passedLevel = null; Type passedType = null; var logger = new ActionLogger( null, (message, type, level) => { passedMessage = message; passedType = type; passedLevel = level; }, null, null); var fullLogger = new WrappingFullLogger(logger); fullLogger.Warn<DummyObjectClass1>("This is a test."); Assert.Equal("This is a test.", passedMessage); Assert.Equal(LogLevel.Warn, passedLevel); Assert.Equal(typeof(DummyObjectClass1), passedType); } /// <summary> /// Test to make sure the generic type parameter is passed to the logger. /// </summary> [Fact] public void Warn_With_Generic_Type_Should_Emit_Message_And_Type_Provided() { string passedMessage = null; LogLevel? passedLevel = null; Type passedType = null; var logger = new ActionLogger( null, (message, type, level) => { passedMessage = message; passedType = type; passedLevel = level; }, null, null); var fullLogger = new WrappingFullLogger(logger); fullLogger.Warn<DummyObjectClass2>("This is a test."); Assert.Equal("This is a test.", passedMessage); Assert.Equal(LogLevel.Warn, passedLevel); Assert.Equal(typeof(DummyObjectClass2), passedType); } /// <summary> /// Test to make sure the generic type parameter is passed to the logger. /// </summary> [Fact] public void Error_With_Generic_Type_Should_Emit_Message_And_Type() { string passedMessage = null; LogLevel? passedLevel = null; Type passedType = null; var logger = new ActionLogger( null, (message, type, level) => { passedMessage = message; passedType = type; passedLevel = level; }, null, null); var fullLogger = new WrappingFullLogger(logger); fullLogger.Error<DummyObjectClass1>("This is a test."); Assert.Equal("This is a test.", passedMessage); Assert.Equal(LogLevel.Error, passedLevel); Assert.Equal(typeof(DummyObjectClass1), passedType); } /// <summary> /// Test to make sure the generic type parameter is passed to the logger. /// </summary> [Fact] public void Error_With_Generic_Type_Should_Emit_Message_And_Type_Provided() { string passedMessage = null; LogLevel? passedLevel = null; Type passedType = null; var logger = new ActionLogger( null, (message, type, level) => { passedMessage = message; passedType = type; passedLevel = level; }, null, null); var fullLogger = new WrappingFullLogger(logger); fullLogger.Error<DummyObjectClass2>("This is a test."); Assert.Equal("This is a test.", passedMessage); Assert.Equal(LogLevel.Error, passedLevel); Assert.Equal(typeof(DummyObjectClass2), passedType); } /// <summary> /// Test to make sure the generic type parameter is passed to the logger. /// </summary> [Fact] public void Fatal_With_Generic_Type_Should_Emit_Message_And_Type() { string passedMessage = null; LogLevel? passedLevel = null; Type passedType = null; var logger = new ActionLogger( null, (message, type, level) => { passedMessage = message; passedType = type; passedLevel = level; }, null, null); var fullLogger = new WrappingFullLogger(logger); fullLogger.Fatal<DummyObjectClass1>("This is a test."); Assert.Equal("This is a test.", passedMessage); Assert.Equal(LogLevel.Fatal, passedLevel); Assert.Equal(typeof(DummyObjectClass1), passedType); } /// <summary> /// Test to make sure the generic type parameter is passed to the logger. /// </summary> [Fact] public void Fatal_With_Generic_Type_Should_Emit_Message_And_Type_Provided() { string passedMessage = null; LogLevel? passedLevel = null; Type passedType = null; var logger = new ActionLogger( null, (message, type, level) => { passedMessage = message; passedType = type; passedLevel = level; }, null, null); var fullLogger = new WrappingFullLogger(logger); fullLogger.Fatal<DummyObjectClass2>("This is a test."); Assert.Equal("This is a test.", passedMessage); Assert.Equal(LogLevel.Fatal, passedLevel); Assert.Equal(typeof(DummyObjectClass2), passedType); } } }
32.397101
83
0.515523
[ "MIT" ]
RLittlesII/splat
src/Splat.Tests/Logging/ActionLoggerTests.cs
11,179
C#
//--------------------------------------------------------------------------------- // Microsoft (R) Windows Azure SDK // Software Development Kit // // Copyright (c) Microsoft Corporation. All rights reserved. // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY KIND, // EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE IMPLIED WARRANTIES // OF MERCHANTABILITY AND/OR FITNESS FOR A PARTICULAR PURPOSE. //--------------------------------------------------------------------------------- using System; using System.Collections.Generic; using System.Runtime.Serialization; using System.ServiceModel; using System.ServiceModel.Web; namespace DotNetNuke.Azure.Accelerator.Management { /// <summary> /// List of affinity groups. /// </summary> [CollectionDataContract(Name = "AffinityGroups", ItemName = "AffinityGroup", Namespace = Constants.WindowsAzureServiceManagementNS)] public class AffinityGroupList : List<AffinityGroup> { public AffinityGroupList() { } public AffinityGroupList(IEnumerable<AffinityGroup> affinityGroups) : base(affinityGroups) { } } /// <summary> /// Affinity Group data contract. /// </summary> [DataContract(Namespace = Constants.WindowsAzureServiceManagementNS)] public class AffinityGroup : IExtensibleDataObject { [DataMember(Order = 1, EmitDefaultValue = false)] public string Name { get; set;} [DataMember(Order = 2)] public string Label { get; set; } [DataMember(Order = 3)] public string Description { get; set; } [DataMember(Order = 4)] public string Location { get; set; } [DataMember(Order = 5, EmitDefaultValue = false)] public HostedServiceList HostedServices { get; set; } [DataMember(Order = 6, EmitDefaultValue = false)] public StorageServiceList StorageServices { get; set; } public ExtensionDataObject ExtensionData { get; set; } } /// <summary> /// The affinity group related part of the external API /// </summary> public partial interface IServiceManagement { /// <summary> /// Lists the affinity groups associated with the specified subscription. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/affinitygroups")] IAsyncResult BeginListAffinityGroups(string subscriptionId, AsyncCallback callback, object state); AffinityGroupList EndListAffinityGroups(IAsyncResult asyncResult); /// <summary> /// Get properties for the specified affinity group. /// </summary> [OperationContract(AsyncPattern = true)] [WebGet(UriTemplate = @"{subscriptionId}/affinitygroups/{affinityGroupName}")] IAsyncResult BeginGetAffinityGroup(string subscriptionId, string affinityGroupName, AsyncCallback callback, object state); AffinityGroup EndGetAffinityGroup(IAsyncResult asyncResult); } public static partial class ServiceManagementExtensionMethods { public static AffinityGroupList ListAffinityGroups(this IServiceManagement proxy, string subscriptionId) { return proxy.EndListAffinityGroups(proxy.BeginListAffinityGroups(subscriptionId, null, null)); } public static AffinityGroup GetAffinityGroup(this IServiceManagement proxy, string subscriptionId, string affinityGroupName) { return proxy.EndGetAffinityGroup(proxy.BeginGetAffinityGroup(subscriptionId, affinityGroupName, null, null)); } } }
38.10101
137
0.639979
[ "MIT" ]
davidjrh/dnn.azureaccelerator
DNNAzureSMB/DotNetNuke.Azure.Accelerator/Management/AffinityGroup.cs
3,774
C#
// c:\program files (x86)\windows kits\10\include\10.0.18362.0\um\devicetopology.h(3020,5) using System; using System.Runtime.InteropServices; namespace DirectN { [Guid("9c2c4058-23f5-41de-877a-df3af236a09e"), InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public partial interface IConnector { [PreserveSig] HRESULT GetType(/* [annotation][out] _Out_ */ out __MIDL___MIDL_itf_devicetopology_0000_0000_0013 pType); [PreserveSig] HRESULT GetDataFlow(/* [annotation][out] _Out_ */ out __MIDL___MIDL_itf_devicetopology_0000_0000_0011 pFlow); [PreserveSig] HRESULT ConnectTo(/* [annotation][in] _In_ */ IConnector pConnectTo); [PreserveSig] HRESULT Disconnect(); [PreserveSig] HRESULT IsConnected(/* [annotation][out] _Out_ */ out bool pbConnected); [PreserveSig] HRESULT GetConnectedTo(/* [annotation][out] _Out_ */ out IConnector ppConTo); [PreserveSig] HRESULT GetConnectorIdConnectedTo(/* [annotation][out] _Outptr_ */ out IntPtr ppwstrConnectorId); [PreserveSig] HRESULT GetDeviceIdConnectedTo(/* [annotation][out] _Outptr_ */ out IntPtr ppwstrDeviceId); } }
36.428571
117
0.661176
[ "MIT" ]
bbday/DirectN
DirectN/DirectN/Generated/IConnector.cs
1,277
C#
using System.Threading.Tasks; using Passion.Rover.Command.Services.Outbox; using Passion.Rover.Command.Services.Repository; namespace Passion.Rover.Command.Services { public class OutboxService : IOutboxService { private readonly IOutboxRepository _outboxRepository; public OutboxService(IOutboxRepository outboxRepository) { _outboxRepository = outboxRepository; } public async Task<bool> CreateOutboxMessage(OutboxMessage message) { await _outboxRepository.InsertAsync(message); return true; } } }
27.590909
74
0.693575
[ "MIT" ]
oktydag/passion
src/Passion.Rover.Command/Services/OutboxService.cs
609
C#
 namespace clinica_coimbra { partial class FormPrincipal { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.Windows.Forms.Calendar.CalendarHighlightRange calendarHighlightRange1 = new System.Windows.Forms.Calendar.CalendarHighlightRange(); System.Windows.Forms.Calendar.CalendarHighlightRange calendarHighlightRange2 = new System.Windows.Forms.Calendar.CalendarHighlightRange(); System.Windows.Forms.Calendar.CalendarHighlightRange calendarHighlightRange3 = new System.Windows.Forms.Calendar.CalendarHighlightRange(); System.Windows.Forms.Calendar.CalendarHighlightRange calendarHighlightRange4 = new System.Windows.Forms.Calendar.CalendarHighlightRange(); System.Windows.Forms.Calendar.CalendarHighlightRange calendarHighlightRange5 = new System.Windows.Forms.Calendar.CalendarHighlightRange(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(FormPrincipal)); this.Calendario = new System.Windows.Forms.Calendar.Calendar(); this.CalendarioMeses = new System.Windows.Forms.Calendar.MonthView(); this.menuStrip1 = new System.Windows.Forms.MenuStrip(); this.ficheiroToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.sairToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.dadosToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.pacientesToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.médicosToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.ajudaToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.acercaDaAplicacaoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.toolStrip1 = new System.Windows.Forms.ToolStrip(); this.BotaoNovaMarcacao = new System.Windows.Forms.ToolStripButton(); this.label1 = new System.Windows.Forms.Label(); this.LabelFundo = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.pictureBox1 = new System.Windows.Forms.PictureBox(); this.novaMarcacaoToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.menuStrip1.SuspendLayout(); this.toolStrip1.SuspendLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).BeginInit(); this.SuspendLayout(); // // Calendario // this.Calendario.Anchor = ((System.Windows.Forms.AnchorStyles)((((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.Calendario.Font = new System.Drawing.Font("Segoe UI", 9F); calendarHighlightRange1.DayOfWeek = System.DayOfWeek.Monday; calendarHighlightRange1.EndTime = System.TimeSpan.Parse("17:00:00"); calendarHighlightRange1.StartTime = System.TimeSpan.Parse("08:00:00"); calendarHighlightRange2.DayOfWeek = System.DayOfWeek.Tuesday; calendarHighlightRange2.EndTime = System.TimeSpan.Parse("17:00:00"); calendarHighlightRange2.StartTime = System.TimeSpan.Parse("08:00:00"); calendarHighlightRange3.DayOfWeek = System.DayOfWeek.Wednesday; calendarHighlightRange3.EndTime = System.TimeSpan.Parse("17:00:00"); calendarHighlightRange3.StartTime = System.TimeSpan.Parse("08:00:00"); calendarHighlightRange4.DayOfWeek = System.DayOfWeek.Thursday; calendarHighlightRange4.EndTime = System.TimeSpan.Parse("17:00:00"); calendarHighlightRange4.StartTime = System.TimeSpan.Parse("08:00:00"); calendarHighlightRange5.DayOfWeek = System.DayOfWeek.Friday; calendarHighlightRange5.EndTime = System.TimeSpan.Parse("17:00:00"); calendarHighlightRange5.StartTime = System.TimeSpan.Parse("08:00:00"); this.Calendario.HighlightRanges = new System.Windows.Forms.Calendar.CalendarHighlightRange[] { calendarHighlightRange1, calendarHighlightRange2, calendarHighlightRange3, calendarHighlightRange4, calendarHighlightRange5}; this.Calendario.Location = new System.Drawing.Point(227, 93); this.Calendario.Name = "Calendario"; this.Calendario.Size = new System.Drawing.Size(573, 430); this.Calendario.TabIndex = 1; this.Calendario.Text = "calendar1"; this.Calendario.LoadItems += new System.Windows.Forms.Calendar.Calendar.CalendarLoadEventHandler(this.Calendario_LoadItems); // // CalendarioMeses // this.CalendarioMeses.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Bottom) | System.Windows.Forms.AnchorStyles.Left))); this.CalendarioMeses.ArrowsColor = System.Drawing.SystemColors.Window; this.CalendarioMeses.ArrowsSelectedColor = System.Drawing.Color.Gold; this.CalendarioMeses.DayBackgroundColor = System.Drawing.Color.Empty; this.CalendarioMeses.DayGrayedText = System.Drawing.SystemColors.GrayText; this.CalendarioMeses.DayNamesLength = 3; this.CalendarioMeses.DaySelectedBackgroundColor = System.Drawing.SystemColors.Highlight; this.CalendarioMeses.DaySelectedColor = System.Drawing.SystemColors.WindowText; this.CalendarioMeses.DaySelectedTextColor = System.Drawing.SystemColors.HighlightText; this.CalendarioMeses.ItemPadding = new System.Windows.Forms.Padding(2); this.CalendarioMeses.Location = new System.Drawing.Point(0, 52); this.CalendarioMeses.MonthTitleColor = System.Drawing.SystemColors.ActiveCaption; this.CalendarioMeses.MonthTitleColorInactive = System.Drawing.SystemColors.InactiveCaption; this.CalendarioMeses.MonthTitleTextColor = System.Drawing.SystemColors.ActiveCaptionText; this.CalendarioMeses.MonthTitleTextColorInactive = System.Drawing.SystemColors.InactiveCaptionText; this.CalendarioMeses.Name = "CalendarioMeses"; this.CalendarioMeses.Size = new System.Drawing.Size(221, 471); this.CalendarioMeses.TabIndex = 2; this.CalendarioMeses.Text = "monthView1"; this.CalendarioMeses.TodayBorderColor = System.Drawing.Color.Maroon; this.CalendarioMeses.SelectionChanged += new System.EventHandler(this.CalendarioMeses_SelectionChanged); // // menuStrip1 // this.menuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.ficheiroToolStripMenuItem, this.dadosToolStripMenuItem, this.ajudaToolStripMenuItem}); this.menuStrip1.Location = new System.Drawing.Point(0, 0); this.menuStrip1.Name = "menuStrip1"; this.menuStrip1.Size = new System.Drawing.Size(800, 24); this.menuStrip1.TabIndex = 3; this.menuStrip1.Text = "menuStrip1"; // // ficheiroToolStripMenuItem // this.ficheiroToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.sairToolStripMenuItem}); this.ficheiroToolStripMenuItem.Name = "ficheiroToolStripMenuItem"; this.ficheiroToolStripMenuItem.Size = new System.Drawing.Size(61, 20); this.ficheiroToolStripMenuItem.Text = "&Ficheiro"; // // sairToolStripMenuItem // this.sairToolStripMenuItem.Name = "sairToolStripMenuItem"; this.sairToolStripMenuItem.Size = new System.Drawing.Size(93, 22); this.sairToolStripMenuItem.Text = "&Sair"; this.sairToolStripMenuItem.Click += new System.EventHandler(this.sairToolStripMenuItem_Click); // // dadosToolStripMenuItem // this.dadosToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.pacientesToolStripMenuItem, this.médicosToolStripMenuItem, this.novaMarcacaoToolStripMenuItem}); this.dadosToolStripMenuItem.Name = "dadosToolStripMenuItem"; this.dadosToolStripMenuItem.Size = new System.Drawing.Size(52, 20); this.dadosToolStripMenuItem.Text = "&Dados"; // // pacientesToolStripMenuItem // this.pacientesToolStripMenuItem.Name = "pacientesToolStripMenuItem"; this.pacientesToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.pacientesToolStripMenuItem.Text = "&Pacientes..."; this.pacientesToolStripMenuItem.Click += new System.EventHandler(this.pacientesToolStripMenuItem_Click); // // médicosToolStripMenuItem // this.médicosToolStripMenuItem.Name = "médicosToolStripMenuItem"; this.médicosToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.médicosToolStripMenuItem.Text = "&Médicos..."; this.médicosToolStripMenuItem.Click += new System.EventHandler(this.médicosToolStripMenuItem_Click); // // ajudaToolStripMenuItem // this.ajudaToolStripMenuItem.DropDownItems.AddRange(new System.Windows.Forms.ToolStripItem[] { this.acercaDaAplicacaoToolStripMenuItem}); this.ajudaToolStripMenuItem.Name = "ajudaToolStripMenuItem"; this.ajudaToolStripMenuItem.Size = new System.Drawing.Size(50, 20); this.ajudaToolStripMenuItem.Text = "&Ajuda"; // // acercaDaAplicacaoToolStripMenuItem // this.acercaDaAplicacaoToolStripMenuItem.Name = "acercaDaAplicacaoToolStripMenuItem"; this.acercaDaAplicacaoToolStripMenuItem.Size = new System.Drawing.Size(181, 22); this.acercaDaAplicacaoToolStripMenuItem.Text = "Ac&erca da Aplicação"; this.acercaDaAplicacaoToolStripMenuItem.Click += new System.EventHandler(this.acercaDaAplicacaoToolStripMenuItem_Click); // // toolStrip1 // this.toolStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.BotaoNovaMarcacao}); this.toolStrip1.Location = new System.Drawing.Point(0, 24); this.toolStrip1.Name = "toolStrip1"; this.toolStrip1.Size = new System.Drawing.Size(800, 25); this.toolStrip1.TabIndex = 4; this.toolStrip1.Text = "toolStrip1"; // // BotaoNovaMarcacao // this.BotaoNovaMarcacao.Image = global::clinica_coimbra.Properties.Resources.Calendar_16x; this.BotaoNovaMarcacao.ImageTransparentColor = System.Drawing.Color.Magenta; this.BotaoNovaMarcacao.Name = "BotaoNovaMarcacao"; this.BotaoNovaMarcacao.Size = new System.Drawing.Size(110, 22); this.BotaoNovaMarcacao.Text = "Nova Marcação"; this.BotaoNovaMarcacao.Click += new System.EventHandler(this.BotaoNovaMarcacao_Click); // // label1 // this.label1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.label1.AutoSize = true; this.label1.BackColor = System.Drawing.Color.SteelBlue; this.label1.Font = new System.Drawing.Font("Segoe UI Semibold", 12F, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label1.ForeColor = System.Drawing.Color.White; this.label1.Location = new System.Drawing.Point(583, 59); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(204, 21); this.label1.TabIndex = 5; this.label1.Text = "Clínica Médica de Coimbra"; // // LabelFundo // this.LabelFundo.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left) | System.Windows.Forms.AnchorStyles.Right))); this.LabelFundo.BackColor = System.Drawing.Color.SteelBlue; this.LabelFundo.Location = new System.Drawing.Point(224, 52); this.LabelFundo.Name = "LabelFundo"; this.LabelFundo.Size = new System.Drawing.Size(576, 38); this.LabelFundo.TabIndex = 6; // // label2 // this.label2.AutoSize = true; this.label2.BackColor = System.Drawing.Color.SteelBlue; this.label2.Font = new System.Drawing.Font("Segoe UI", 11.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.label2.ForeColor = System.Drawing.Color.White; this.label2.Location = new System.Drawing.Point(234, 59); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(158, 20); this.label2.TabIndex = 7; this.label2.Text = "Marcações da Semana"; // // pictureBox1 // this.pictureBox1.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right))); this.pictureBox1.BackColor = System.Drawing.Color.SteelBlue; this.pictureBox1.Image = global::clinica_coimbra.Properties.Resources.application_icon24; this.pictureBox1.Location = new System.Drawing.Point(561, 57); this.pictureBox1.Name = "pictureBox1"; this.pictureBox1.Size = new System.Drawing.Size(19, 24); this.pictureBox1.SizeMode = System.Windows.Forms.PictureBoxSizeMode.AutoSize; this.pictureBox1.TabIndex = 8; this.pictureBox1.TabStop = false; // // novaMarcacaoToolStripMenuItem // this.novaMarcacaoToolStripMenuItem.Name = "novaMarcacaoToolStripMenuItem"; this.novaMarcacaoToolStripMenuItem.Size = new System.Drawing.Size(180, 22); this.novaMarcacaoToolStripMenuItem.Text = "&Nova Marcação..."; this.novaMarcacaoToolStripMenuItem.Click += new System.EventHandler(this.novaMarcacaoToolStripMenuItem_Click); // // FormPrincipal // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 519); this.Controls.Add(this.pictureBox1); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.LabelFundo); this.Controls.Add(this.toolStrip1); this.Controls.Add(this.CalendarioMeses); this.Controls.Add(this.Calendario); this.Controls.Add(this.menuStrip1); this.Font = new System.Drawing.Font("Segoe UI", 8.25F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0))); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MainMenuStrip = this.menuStrip1; this.Name = "FormPrincipal"; this.Text = "Form1"; this.Load += new System.EventHandler(this.FormPrincipal_Load); this.menuStrip1.ResumeLayout(false); this.menuStrip1.PerformLayout(); this.toolStrip1.ResumeLayout(false); this.toolStrip1.PerformLayout(); ((System.ComponentModel.ISupportInitialize)(this.pictureBox1)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Calendar.Calendar Calendario; private System.Windows.Forms.Calendar.MonthView CalendarioMeses; private System.Windows.Forms.MenuStrip menuStrip1; private System.Windows.Forms.ToolStripMenuItem ficheiroToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem ajudaToolStripMenuItem; private System.Windows.Forms.ToolStrip toolStrip1; private System.Windows.Forms.ToolStripButton BotaoNovaMarcacao; private System.Windows.Forms.Label label1; private System.Windows.Forms.ToolStripMenuItem sairToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem acercaDaAplicacaoToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem dadosToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem pacientesToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem médicosToolStripMenuItem; private System.Windows.Forms.Label LabelFundo; private System.Windows.Forms.Label label2; private System.Windows.Forms.PictureBox pictureBox1; private System.Windows.Forms.ToolStripMenuItem novaMarcacaoToolStripMenuItem; } }
59.412338
163
0.663315
[ "MIT" ]
joaomartiniano/clinica-medica-coimbra
src/FormPrincipal.Designer.cs
18,322
C#
using System.Collections.Generic; using NGM.OpenAuthentication.Models; using Orchard; using Orchard.Data; using Orchard.Security; namespace NGM.OpenAuthentication.Services { public interface IUserProviderServices : IDependency { UserProviderRecord Get(string providerName, string providerUserId); void Create(string providerName, string providerUserId, IUser user); void Update(string providerName, string providerUserId, IUser user); IEnumerable<UserProviderRecord> Get(IUser user); } public class UserProviderServices : IUserProviderServices { private readonly IRepository<UserProviderRecord> _repository; public UserProviderServices(IRepository<UserProviderRecord> repository) { _repository = repository; } public UserProviderRecord Get(string providerName, string providerUserId) { return _repository.Get(o => o.ProviderName == providerName && o.ProviderUserId == providerUserId); } public IEnumerable<UserProviderRecord> Get(IUser user) { return _repository.Fetch(o => o.UserId == user.Id); } public void Create(string providerName, string providerUserId, IUser user) { var record = new UserProviderRecord { UserId = user.Id, ProviderName = providerName, ProviderUserId = providerUserId }; _repository.Create(record); } public void Update(string providerName, string providerUserId, IUser user) { var record = Get(providerName, providerUserId); record.UserId = user.Id; _repository.Update(record); } } }
35.571429
110
0.657487
[ "BSD-3-Clause" ]
sfmskywalker/Orchard-Pros
src/Orchard.Web/Modules/NGM.OpenAuthentication/Services/UserProviderServices.cs
1,745
C#
using System.Linq; using System.Text.RegularExpressions; using zgcwkj.Util.Common; using zgcwkj.Util.DbUtil; using zgcwkj.Util.Models; namespace zgcwkj.Util { /// <summary> /// 数据库操作对象 /// </summary> public static class DbProvider { /// <summary> /// 创建数据库命令 /// </summary> /// <returns></returns> public static DbAccess Create() { return new DbAccess(); } /// <summary> /// 清空准备的数据 /// </summary> /// <param name="cmdAccess">脚本模型</param> /// <returns>追加状态</returns> public static bool Clear(this DbAccess cmdAccess) { cmdAccess.dbModel = new SqlModel(); cmdAccess.dataBase = DataFactory.Db; return true; } /// <summary> /// 获取执行的脚本 /// </summary> /// <returns></returns> public static string GetSql(this DbAccess cmdAccess) { string sql = $"{cmdAccess.dbModel.Sql}"; //追加的脚本 if (!string.IsNullOrEmpty(cmdAccess.dbModel.AppendSql)) sql += $" {cmdAccess.dbModel.AppendSql}"; //排序的脚本 if (!string.IsNullOrEmpty(cmdAccess.dbModel.OrderBy)) sql += $" {cmdAccess.dbModel.OrderBy}"; //组合的脚本 if (!string.IsNullOrEmpty(cmdAccess.dbModel.GroupBy)) sql += $" {cmdAccess.dbModel.GroupBy}"; //结尾的脚本 if (!string.IsNullOrEmpty(cmdAccess.dbModel.EndSql)) sql += $" {cmdAccess.dbModel.EndSql}"; //数据库通用脚本 sql = GenericScript(sql); //返回脚本 return sql; } /// <summary> /// 设置CommandText /// </summary> /// <param name="cmdAccess">脚本模型</param> /// <param name="commandText">命令Text</param> /// <returns>设置状态</returns> public static bool SetCommandText(this DbAccess cmdAccess, string commandText) { //设置状态 bool setStatus = false; //防止空字符 if (!string.IsNullOrEmpty(commandText)) { setStatus = true; cmdAccess.dbModel.Sql = commandText; } return setStatus; } /// <summary> /// 设置CommandText /// </summary> /// <param name="cmdAccess">脚本模型</param> /// <param name="commandText">命令Text</param> /// <param name="commandValues">Sql命令的参数值</param> /// <returns>设置状态</returns> public static bool SetCommandText(this DbAccess cmdAccess, string commandText, params object[] commandValues) { //设置状态 bool setStatus = false; //得到脚本上的变量 MatchCollection matchCollection = GetMatchCollection(commandText); //循环变量 for (int i = 0; i < commandValues.Count(); i++) { setStatus = true; commandText = commandText.Replace(matchCollection[i].Value, $"'{commandValues[i].PreventInjection()}'"); } cmdAccess.dbModel.Sql = commandText; return setStatus; } /// <summary> /// 末尾追加字符串,并赋参数值 /// </summary> /// <param name="cmdAccess">脚本模型</param> /// <param name="filter">字段</param> /// <param name="values">值</param> /// <returns>追加状态</returns> public static bool Append(this DbAccess cmdAccess, string filter, params object[] values) { //添加状态 bool addStatus = false; //得到脚本上的变量 MatchCollection matchCollection = GetMatchCollection(filter); //循环变量 for (int i = 0; i < values.Count(); i++) { addStatus = true; filter = filter.Replace(matchCollection[i].Value, $"'{values[i].PreventInjection()}'"); } //判断是否需要加 Where if (!cmdAccess.dbModel.Sql.ToLower().Contains("where")) { if (string.IsNullOrEmpty(cmdAccess.dbModel.AppendSql)) { cmdAccess.dbModel.AppendSql += ExtraSpace($"where {filter}"); return addStatus; } } cmdAccess.dbModel.AppendSql += ExtraSpace($"{filter}"); //添加状态 return addStatus; } /// <summary> /// 末尾追加字符串,并赋参数值 /// 追加与条件 /// </summary> /// <param name="cmdAccess">脚本模型</param> /// <param name="filter">字段</param> /// <param name="values">值</param> /// <returns>追加状态</returns> public static bool AppendAnd(this DbAccess cmdAccess, string filter, params object[] values) { //添加状态 bool addStatus = false; //得到脚本上的变量 MatchCollection matchCollection = GetMatchCollection(filter); //循环变量 for (int i = 0; i < values.Count(); i++) { if (values[i] != null) { if (!string.IsNullOrEmpty(values[i].ToString())) { addStatus = true; filter = filter.Replace(matchCollection[i].Value, $"'{values[i].PreventInjection()}'"); } } } //是否添加 if (addStatus) { //判断是否需要加 Where if (!cmdAccess.dbModel.Sql.ToLower().Contains("where")) { if (string.IsNullOrEmpty(cmdAccess.dbModel.AppendSql)) { cmdAccess.dbModel.AppendSql += ExtraSpace($"where {filter}"); return addStatus; } } cmdAccess.dbModel.AppendSql += ExtraSpace($"and {filter}"); } //添加状态 return addStatus; } /// <summary> /// 末尾追加字符串,并赋参数值 /// 追加或条件 /// </summary> /// <param name="cmdAccess">脚本模型</param> /// <param name="filter">字段</param> /// <param name="values">值</param> /// <returns>追加状态</returns> public static bool AppendOr(this DbAccess cmdAccess, string filter, params object[] values) { //添加状态 bool addStatus = false; //得到脚本上的变量 MatchCollection matchCollection = GetMatchCollection(filter); //循环变量 for (int i = 0; i < values.Count(); i++) { if (values[i] != null) { if (!string.IsNullOrEmpty(values[i].ToString())) { addStatus = true; filter = filter.Replace(matchCollection[i].Value, $"'{values[i].PreventInjection()}'"); } } } //是否添加 if (addStatus) { //判断是否需要加 Where if (!cmdAccess.dbModel.Sql.ToLower().Contains("where")) { if (string.IsNullOrEmpty(cmdAccess.dbModel.AppendSql)) { cmdAccess.dbModel.AppendSql += ExtraSpace($"where {filter}"); return addStatus; } cmdAccess.dbModel.AppendSql += ExtraSpace($"or {filter}"); } } //添加状态 return addStatus; } /// <summary> /// 排序 /// </summary> /// <param name="cmdAccess">脚本模型</param> /// <param name="filter">字段(多字段用逗号分开)</param> /// <returns>追加状态</returns> public static bool OrderBy(this DbAccess cmdAccess, string filter) { if (!string.IsNullOrEmpty(filter)) { cmdAccess.dbModel.OrderBy = $"order by {filter}"; return true; } return false; } /// <summary> /// 分组 /// </summary> /// <param name="cmdAccess">脚本模型</param> /// <param name="filter">字段(多字段用逗号分开)</param> /// <returns>追加状态</returns> public static bool GroupBy(this DbAccess cmdAccess, string filter) { if (!string.IsNullOrEmpty(filter)) { cmdAccess.dbModel.GroupBy = $"group by {filter}"; return true; } return false; } /// <summary> /// 设置结尾脚本 /// </summary> /// <param name="cmdAccess">脚本模型</param> /// <param name="sqlStr">添加的字符串</param> /// <returns></returns> public static bool SetEndSql(this DbAccess cmdAccess, string sqlStr) { if (!string.IsNullOrEmpty(sqlStr)) { cmdAccess.dbModel.EndSql = $"{sqlStr}"; return true; } return false; } /// <summary> /// 事务开始 /// </summary> /// <param name="cmdAccess">脚本模型</param> public static void TransBegin(this DbAccess cmdAccess) { cmdAccess.dataBase.BeginTrans(); } /// <summary> /// 事务提交 /// </summary> /// <param name="cmdAccess">脚本模型</param> public static int TransCommit(this DbAccess cmdAccess) { return cmdAccess.dataBase.CommitTrans(); } /// <summary> /// 事务回滚 /// </summary> /// <param name="cmdAccess">脚本模型</param> public static void TransRollback(this DbAccess cmdAccess) { cmdAccess.dataBase.RollbackTrans(); } /// <summary> /// 获取对应的参数 /// </summary> /// <param name="sqlStr">脚本字符</param> /// <returns>匹配到的数据</returns> private static MatchCollection GetMatchCollection(string sqlStr) { return Regex.Matches(sqlStr, @"(?<=[^0-9a-zA-Z])@(?!@)[0-9a-zA-Z_$#@]+"); } /// <summary> /// 额外空格(决定是否需要添加) /// </summary> /// <param name="sqlStr">脚本字符</param> /// <returns>添加空格的脚本</returns> private static string ExtraSpace(string sqlStr) { if (sqlStr.Length > 0) { string startSql = sqlStr.Substring(0, 1); if (startSql != " ") { sqlStr = $" {sqlStr}"; } } return sqlStr; } /// <summary> /// 防止数据脚本的注入 /// </summary> /// <returns></returns> private static string PreventInjection(this object val) { string data = val.ToTrim(); data = data.ToTrim().Replace("\\", "\\\\"); data = data.ToTrim().Replace("'", "\\'"); return data; } /// <summary> /// 数据库通用脚本 /// </summary> /// <param name="sql">Sql脚本</param> /// <returns>脚本</returns> private static string GenericScript(string sql) { //转成通用脚本 var type = DbFactory.Type; if (type == Enum.DbType.MySql) { //时间函数 if (sql.Contains("getdate()")) { sql = sql.Replace("getdate()", "now()"); } //分页函数 int pageSql = sql.IndexOf("offset"); if (pageSql != -1 && sql.LastIndexOf("only") > pageSql) { string updSql = string.Empty; var page = Regex.Match(sql, @"(?<=offset).+(?=rows fetch next.+)").Value; var pageSize = Regex.Match(sql, @"(?<=rows fetch next.+).+(?=rows only)").Value; updSql += $" limit {page},{pageSize}"; sql = sql.Substring(0, pageSql) + updSql; } } else if (type == Enum.DbType.SqlServer) { //时间函数 if (sql.Contains("now()")) { sql = sql.Replace("now()", "getdate()"); } //是否为空函数 string isnullStr = Regex.Match(sql, @"isnull\(.+?\)").Value; if (!isnullStr.IsNull()) { string isnullStrB = Regex.Match(sql, @"(?<=isnull\().+?(?=\))").Value; sql = sql.Replace(isnullStr, $"{isnullStrB} is null"); } //分页函数 int pageSql = sql.IndexOf("limit"); if (pageSql != -1 && sql.LastIndexOf(",") > pageSql) { string updSql = string.Empty; if (!sql.ToLower().Contains("order")) updSql = "order by 1"; var page = Regex.Match(sql, @"(?<=limit).+(?=,.+)").Value; var pageSize = Regex.Match(sql, @"(?<=limit.+,)[0-9]+").Value; updSql += $" offset {page} rows fetch next {pageSize} rows only"; sql = sql.Substring(0, pageSql) + updSql; } } else if (type == Enum.DbType.PostgreSql) { //时间函数 if (sql.Contains("rand()")) { sql = sql.Replace("rand()", "random()"); } //是否为空函数 string isnullStr = Regex.Match(sql, @"isnull\(.+?\)").Value; if (!isnullStr.IsNull()) { string isnullStrB = Regex.Match(sql, @"(?<=isnull\().+?(?=\))").Value; sql = sql.Replace(isnullStr, $"{isnullStrB} is null"); } //分页函数 int pageSql = sql.IndexOf("limit"); if (pageSql != -1 && sql.LastIndexOf(",") > pageSql) { string updSql = string.Empty; var page = Regex.Match(sql, @"(?<=limit).+(?=,.+)").Value; var pageSize = Regex.Match(sql, @"(?<=limit.+,)[0-9]+").Value; updSql += $"limit {pageSize} offset {page}"; sql = sql.Substring(0, pageSql) + updSql; } } return sql; } } }
34.239808
120
0.453565
[ "MIT" ]
zgcwkj/zgcwkj.DotnetCore
zgcwkj.Util/DbProvider.cs
15,242
C#
using System; using System.Collections.Generic; using System.Linq; namespace BattlePlanPath { /// <summary> /// Bundle of information returned after searching for a path. /// </summary> public class PathResult<T> { /// <summary> /// The sequence of nodes to take to get to one of the destinations. The destination /// node is included in the path, but the starting node isn't. Null if no path /// could be found. /// </summary> public List<T> Path { get; set; } public T StartingNode { get; set; } /// <summary> /// Sum of all of the costs from one node to the next for this path, as given by IPathGraph. /// </summary> public double PathCost { get; set; } // -- Everything else is just performance data -- /// <summary> /// Amount of time it took to find this path. /// </summary> public int SolutionTimeMS { get; set; } /// <summary> /// The number of unique nodes considered while finding this path. Ideally this will be much lower /// than NodesInGraphCount, but that depends on the complexity of your graph and the quality of your /// heuristic. /// </summary> public int NodesTouchedCount { get; set; } /// <summary> /// The number of nodes that were previously "closed" but had to be re-opened. This can only happen /// if your EstimatedCost heuristic can sometimes exceed the true cost. (Watch out for floating point /// issues though.) It's not necessarily bad if this happens - it's a speed vs. quality balance. /// </summary> public int NodesReprocessedCount { get; set; } /// <summary> /// Number of nodes in the entire known graph (as built by PathSolver.BuildAdjacencyGraph) /// </summary> public int NodesInGraphCount { get; set; } /// <summary> /// Largest number of nodes waiting to be processed at any time during the algorithm. /// </summary> public int MaxQueueSize { get; set; } /// <summary> /// Returns a string based on the performance fields, intended for logging. /// </summary> public string PerformanceSummary() { string pathIds; if (Path == null) pathIds = $"Path not found from {this.StartingNode}:"; else if (Path.Count==0) pathIds = $"Zero-length path from {this.StartingNode}:"; else pathIds = $"Path from {this.StartingNode} to {this.Path[this.Path.Count-1]}: cost={this.PathCost.ToString("F2")}; steps={this.Path.Count}"; double pctGraphUsed = 100.0 * this.NodesTouchedCount / this.NodesInGraphCount; double pctReprocessed = 100.0 * this.NodesReprocessedCount / this.NodesTouchedCount; var msg = string.Format("{0} timeMS={1}; %nodesTouched={2:F2}; %nodesReprocessed={3:F2}; maxQueueSize={4}", pathIds, this.SolutionTimeMS, pctGraphUsed, pctReprocessed, this.MaxQueueSize); return msg; } } }
39.839506
155
0.588162
[ "MIT" ]
j-brooke/BattlePlanPath
BattlePlanPath/PathResult.cs
3,227
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DataLayer { public class RolesMetaData { [Key] public int RoleID { get; set; } [Display(Name = "عنوان نقش")] [Required(ErrorMessage = "لطفا {0} را وارد کنید")] public string RoleTitle { get; set; } [Display(Name = "عنوان سیستمی نقش")] [Required(ErrorMessage = "لطفا {0} را وارد کنید")] public string RoleName { get; set; } } [MetadataType(typeof(RolesMetaData))] public partial class Roles { } }
22.433333
58
0.627043
[ "MIT" ]
mahmoodghanbary/ASP.NetMVCproject
Data/MetaDataClasses/RolesMetaData.cs
725
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class Noun : Expression { public Enums.generalTypes type { get; private set; } //feature, person, thing, etc public string owner { get; private set; } //if it is a feature, this would be person or thing, if it is a thing held by person, owner would be person, and so on public Noun(string noun, Enums.generalTypes typ, string ownr) { expression = noun; type = typ; owner = ownr; } }
28.529412
163
0.721649
[ "MIT" ]
Millmoss/soapdragon
Assets/Scripts/Person/Dialogue/Expressions/Noun.cs
487
C#
using System; using System.Collections.Generic; using System.Text; using This.Namespace.Is.Waaaaaaaaaaay.Too.Long; using This.Namespace.Is.Also.Way.Too.Long; using This.Long; namespace This.Namespace.Is.Waaaaaaaaaaay.Too.Long { class Something { public static void Foo() { } } } namespace This.Namespace.Is.Also.Way.Too.Long { class Otherthing { public static void Bar() { } } } namespace This.Long { class NotSoLong { public static void HelloWorld() { } } } namespace Test { static class Test { static void TestMethod() { Something.Foo(); Otherthing.Bar(); NotSoLong.HelloWorld(); } } }
17.972222
52
0.680062
[ "Apache-2.0" ]
Drake53/CSharp.lua
CSharp.lua.Tests/Input/RuntimeBug/LongNamespace.cs
647
C#
using System.ComponentModel.Composition; using Microsoft.VisualStudio.Editor.Commanding; using Microsoft.VisualStudio.Text; using Microsoft.VisualStudio.Text.Editor; using Microsoft.VisualStudio.Text.Editor.Commanding; namespace $rootnamespace$ { [Export(typeof(CommandBindingDefinition))] [CommandBinding(CommandGuid, CommandID, typeof($safeitemname$))] public class $safeitemname$ : EditorCommandArgs { public const string CommandGuid = "<guid>"; public const int CommandID = 0x100; public $safeitemname$(ITextView textView, ITextBuffer textBuffer) : base(textView, textBuffer) { } } }
31.190476
73
0.729771
[ "Apache-2.0" ]
RobinsonMW/ExtensibilityTemplatePack
src/2019/ItemTemplates/EditorCommandBinding/EditorCommandBinding.cs
657
C#
using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using BinaryRecords.Delegates; using BinaryRecords.Enums; using BinaryRecords.Expressions; using BinaryRecords.Records; using BinaryRecords.Util; namespace BinaryRecords.Providers { public static class BufferExpressionGeneratorProviders { public static readonly IReadOnlyList<ExpressionGeneratorProvider> Builtin = CreateBuiltinProviders().ToList(); private delegate Expression SerializeBlittable(Expression buffer, Expression data); private delegate Expression DeserializeBlittable(Expression buffer); private static BlittableExpressionGeneratorProvider CreateBlittableBufferProvider<T>( SerializeBlittable serialize, DeserializeBlittable deserialize, SerializableDataTypes serializableDataType) { return new( Name: $"{typeof(T)}BlittableBufferProvider", Priority: ProviderPriority.Normal, IsInterested: (type, _) => type == typeof(T), GenerateSerializeExpression: (typingLibrary, type, buffer, data, versioning) => { var blockBuilder = new ExpressionBlockBuilder(); versioning?.Start(blockBuilder, buffer, typingLibrary.BitSize); blockBuilder += serialize(buffer, data); versioning?.Stop(blockBuilder, buffer, typingLibrary.BitSize); return blockBuilder; }, GenerateDeserializeExpression: (typingLibrary, type, buffer) => deserialize(buffer), GenerateTypeRecord: (_, _) => new PrimitiveTypeRecord(serializableDataType) ); } private static IEnumerable<ExpressionGeneratorProvider> CreateBuiltinProviders() { // Create the providers for each primitive type var bufferWriterType = typeof(BinaryBufferWriter); var bufferReaderType = typeof(BinaryBufferReader); // bool type yield return CreateBlittableBufferProvider<bool>( BufferWriterExpressions.WriteBool, BufferReaderExpressions.ReadBool, SerializableDataTypes.Bool ); // byte types yield return CreateBlittableBufferProvider<byte>( BufferWriterExpressions.WriteUInt8, BufferReaderExpressions.ReadUInt8, SerializableDataTypes.Byte ); yield return CreateBlittableBufferProvider<sbyte>( BufferWriterExpressions.WriteInt8, BufferReaderExpressions.ReadUInt8, SerializableDataTypes.SByte ); // short types yield return CreateBlittableBufferProvider<ushort>( BufferWriterExpressions.WriteUInt16, BufferReaderExpressions.ReadUInt16, SerializableDataTypes.UShort ); yield return CreateBlittableBufferProvider<short>( BufferWriterExpressions.WriteInt16, BufferReaderExpressions.ReadUInt16, SerializableDataTypes.Short ); // int types yield return CreateBlittableBufferProvider<uint>( BufferWriterExpressions.WriteUInt32, BufferReaderExpressions.ReadUInt32, SerializableDataTypes.UInt ); yield return CreateBlittableBufferProvider<int>( BufferWriterExpressions.WriteInt32, BufferReaderExpressions.ReadInt32, SerializableDataTypes.Int ); // long types yield return CreateBlittableBufferProvider<ulong>( BufferWriterExpressions.WriteUInt64, BufferReaderExpressions.ReadUInt64, SerializableDataTypes.ULong ); yield return CreateBlittableBufferProvider<long>( BufferWriterExpressions.WriteInt64, BufferReaderExpressions.ReadInt64, SerializableDataTypes.Long ); // float types yield return CreateBlittableBufferProvider<float>( BufferWriterExpressions.WriteSingle, BufferReaderExpressions.ReadSingle, SerializableDataTypes.Float ); yield return CreateBlittableBufferProvider<double>( BufferWriterExpressions.WriteDouble, BufferReaderExpressions.ReadDouble, SerializableDataTypes.Double ); // string type yield return new ExpressionGeneratorProvider( Name: "StringProvider", Priority: ProviderPriority.Normal, IsInterested: (type, _) => type == typeof(string), GenerateSerializeExpression: (typingLibrary, type, buffer, data, versioning) => { var blockBuilder = new ExpressionBlockBuilder(); versioning?.Start(blockBuilder, buffer, typingLibrary.BitSize); blockBuilder += BufferWriterExpressions.WriteUTF8String(buffer, data); versioning?.Stop(blockBuilder, buffer, typingLibrary.BitSize); return blockBuilder; }, GenerateDeserializeExpression: (typingLibrary, type, buffer) => BufferReaderExpressions.ReadUTF8String(buffer), GenerateTypeRecord: (typingLibrary, type) => new ListTypeRecord(typingLibrary.GetTypeRecord(typeof(byte))) ); } } }
43.721805
122
0.606019
[ "MIT" ]
chandler14362/BinaryRecords
BinaryRecords/Providers/BufferExpressionGeneratorProviders.cs
5,815
C#
// This software is part of the Autofac IoC container // Copyright © 2011 Autofac Contributors // http://autofac.org // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. using System; using System.Linq; using System.Reflection; namespace Autofac.Core.Activators.Reflection { /// <summary> /// Supplies values based on the target parameter type. /// </summary> public class AutowiringParameter : Parameter { /// <summary> /// Returns true if the parameter is able to provide a value to a particular site. /// </summary> /// <param name="pi">Constructor, method, or property-mutator parameter.</param> /// <param name="context">The component context in which the value is being provided.</param> /// <param name="valueProvider">If the result is true, the valueProvider parameter will /// be set to a function that will lazily retrieve the parameter value. If the result is false, /// will be set to null.</param> /// <returns>True if a value can be supplied; otherwise, false.</returns> /// <exception cref="System.ArgumentNullException"> /// Thrown if <paramref name="pi" /> or <paramref name="context" /> is <see langword="null" />. /// </exception> public override bool CanSupplyValue(ParameterInfo pi, IComponentContext context, out Func<object> valueProvider) { if (pi == null) { throw new ArgumentNullException("pi"); } if (context == null) { throw new ArgumentNullException("context"); } IComponentRegistration registration; if (context.ComponentRegistry.TryGetRegistration(new TypedService(pi.ParameterType), out registration)) { valueProvider = () => context.ResolveComponent(registration, Enumerable.Empty<Parameter>()); return true; } valueProvider = null; return false; } } }
44.871429
121
0.650748
[ "MIT" ]
OrchardCMS/Autofac
Core/Source/Autofac/Core/Activators/Reflection/AutowiringParameter.cs
3,144
C#
//#if UNITY_2018_1_OR_NEWER using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Threading; using System.Diagnostics; using Assets.UBindr.Expressions; using NUnit.Framework; // ReSharper disable EqualExpressionComparison // ReSharper disable ConditionIsAlwaysTrueOrFalse namespace Assets.Tests { [TestFixture] public class ExpressionTests { public static CSharpTopDownParser Parser { get; private set; } public static TopDownParser.Scope Scope { get; private set; } private static ViewModel vm; [SetUp] public void SetUp() { Thread.CurrentThread.CurrentCulture = CultureInfo.InvariantCulture; Thread.CurrentThread.CurrentUICulture = CultureInfo.InvariantCulture; Parser = new CSharpTopDownParser(); Scope = new TopDownParser.Scope(Parser); vm = new ViewModel { Child = new ViewModel { Name = "Child Name", Index = 125 }, vm2 = new ViewModel { Val1 = 5 } }; Scope.AddObjectRoot("vm", () => vm); Scope.AddObjectRoot("nullVm", () => null); Scope.AddObjectRoot("rootPi", () => vm.Pi); Scope.AddStaticRoot("Math", typeof(Math)); Scope.AddStaticRoot("MyTime", typeof(MyTime)); } [Test] public void ValidateAssignmentExpressions() { // Verify if expression is a proper assignment path ValidateAssignmentExpression("vm.one", true); ValidateAssignmentExpression("vm.Child", true); ValidateAssignmentExpression("vm.Child.one", true); ValidateAssignmentExpression("vm.one()", false); ValidateAssignmentExpression("5+2", false); ValidateAssignmentExpression("(true?vm:vm.Child).one", true); ValidateAssignmentExpression("(true?vm:vm.Child).one+1", false); } [Test] public void BreakDownPath() { ValidatePath("vm.Child.one", "vm|Child|one"); ValidatePath("vm.GetOne().one", "vm|GetOne|one"); ValidatePath("vm.GetOne().GetOne().one", "vm|GetOne|GetOne|one"); ValidatePath("vm?.GetOne().GetOne().one", "vm|GetOne|GetOne|one"); ValidatePath("vm?.(true?a:b).GetOne().one", "vm|(|GetOne|one"); } [Test] public void RawEvaluationPerformanceTests() { Stopwatch sw = Stopwatch.StartNew(); int iterations = 20000; TopDownParser.Scope scope = new TopDownParser.Scope(Parser); Parser.Evaluate("13+123+123+123+123", scope); for (int i = 0; i < iterations; i++) { Parser.Evaluate("13+123+123+123+123", scope); } WriteLine((float)sw.ElapsedMilliseconds / iterations + "ms/iteration"); } [Test] public void ReusedEvaluationPerformanceTests() { Stopwatch sw = Stopwatch.StartNew(); int iterations = 20000; TopDownParser.Scope scope = new TopDownParser.Scope(Parser); var expression = Parser.BuildExpression("13+123+123+123+123", scope); for (int i = 0; i < iterations; i++) { expression.Evaluate(); } WriteLine((float)sw.ElapsedMilliseconds / iterations + "ms/iteration"); } [Test] public void ValidateParsing() { ValidateParse("yo.val.myFun=6", "(= (. (. yo val) myFun) 6)"); ValidateParse("yo.val?.myFun()", "(?. (. yo val) myFun)"); ValidateParse("yo.val.myFun()", "(. (. yo val) myFun)"); ValidateParse("val.myFun()", "(. val myFun)"); ValidateParse("myFun()", "myFun"); ValidateParse("myFun(1+2)", "(myFun (+ 1 2))"); ValidateParse("myFun(1,2,3,/*comment*/4)", "(myFun 1 2 3 4)"); ValidateParse("myarr[1+2]", "(myarr (+ 1 2))"); ValidateParse("myarr[1,2,3,/*comment*/4]", "(myarr 1 2 3 4)"); ValidateParse("a=7", "(= a 7)"); ValidateParse("!(a>b)", "(! (( (> a b)))"); ValidateParse("a>b", "(> a b)"); ValidateParse("a>=b+1", "(>= a (+ b 1))"); ValidateParse("a<b", "(< a b)"); ValidateParse("a<=b+1", "(<= a (+ b 1))"); ValidateParse("a==b", "(== a b)"); ValidateParse("a!=b+1", "(!= a (+ b 1))"); ValidateParse("a&&b||c", "(|| (&& a b) c)"); ValidateParse("a||b&&c", "(|| a (&& b c))"); ValidateParse("2**3**4", "(** 2 (** 3 4))"); ValidateParse("2**3**4", "(** 2 (** 3 4))"); ValidateParse("true?(false?3:4):2+3", "(? true (( (? false 3 4)) (+ 2 3))"); ValidateParse("true?(1):2+3", "(? true (( 1) (+ 2 3))"); ValidateParse("true?1:2", "(? true 1 2)"); ValidateParse("(1)", "(( 1)"); ValidateParse("(1+2)", "(( (+ 1 2))"); ValidateParse("((1*2)+(2*3))", "(( (+ (( (* 1 2)) (( (* 2 3))))"); ValidateParse("2+3*4", "(+ 2 (* 3 4))"); ValidateParse("2*3+4", "(+ (* 2 3) 4)"); ValidateParse("2*3*4", "(* (* 2 3) 4)"); ValidateParse("2+3+4", "(+ (+ 2 3) 4)"); ValidateParse("-2", "(- 2)"); ValidateParse("3+-2", "(+ 3 (- 2))"); } [Test] public void SimpleEvaluate() { Validate("!true", !true); Validate("3+91", 3 + 91); Validate("3-91", 3 - 91); Validate("3", 3); Validate("'ooga'", "ooga"); } [Test] public void TestEvaluatingOperators() { Validate(" 2 -1", 2 - 1); Validate(" 2 **3+3", (float)Math.Pow(2, 3) + 3); Validate(" 2**3**3", (float)Math.Pow(2, (float)Math.Pow(3, 3))); Validate(" 2 **3", (float)Math.Pow(2, 3)); Validate(" 3 **-2", (float)Math.Pow(3, -2)); Validate(" (1 +2 ) * ( 5 + 12 ) ", (1 + 2) * (5 + 12)); Validate(" (2+2 **3+3 ) * ( 5 + 12 ) ", (2 + (float)Math.Pow(2, 3) + 3) * (5 + 12)); Validate(" 5 + 12 ", 5 + 12); Validate(" 5.512 + 12 ", 5.512f + 12); Validate(" 5 + -12 ", 5 + -12); Validate(" 5 - 12 ", 5 - 12); Validate(" 5.512 - 12 ", 5.512f - 12); Validate(" 5 - -12 ", 5 - -12); Validate(" 5 * 12 ", 5 * 12); Validate(" 5.512 * 12 ", 5.512f * 12); Validate(" 5 * -12 ", 5 * -12); Validate(" 5f / 12 ", 5f / 12); Validate(" 5.512 / 12 ", 5.512f / 12); Validate(" 5f / -12 ", 5f / -12); Validate(" 10 / -2f ", 10 / -2f); Validate("(10-20-10-20)", (10 - 20 - 10 - 20)); Validate("5f/10*2", 5f / 10 * 2); Validate("5f/10/2", 5f / 10 / 2); Validate("5f/(10*2)", 5f / (10 * 2)); Validate("5f/(10/2)", 5f / (10f / 2)); Validate("5f/10+2", 5f / 10 + 2); Validate("5f+10/2", 5f + 10f / 2); Validate("5+10/2", 5 + 10 / 2); Validate("5f/(10+2)", 5f / (10 + 2)); Validate("5f+(10/2)", 5f + (10f / 2)); Validate("5f/10-2", 5f / 10 - 2); Validate("5f-10/2", 5f - 10f / 2); Validate("5f/(10-2)", 5f / (10 - 2)); Validate("5f-(10/2)", 5f - (10f / 2)); Validate("-2.1", -2.1f); Validate("-2.1*-1.2", -2.1f * -1.2f); Validate("2.1", 2.1f); Validate("+2.1", +2.1f); Validate("(10-20)-(10-20)", (10 - 20) - (10 - 20)); Validate("3 + 4 × 2 ÷ ( 1 − 5 ) ^ 2 ^ 3".Replace("^", "**"), 3 + 4 * 2 / (float)Math.Pow((1 - 5), (float)Math.Pow(2, 3))); } [Test] public void Numbers() { Validate(" 3*4+5 ", 3 * 4 + 5); Validate(" 3+4+5 ", 3 + 4 + 5); Validate(" 3*4*5 ", 3 * 4 * 5); Validate(" 3*4/5 ", 3 * 4 / 5); Validate(" 4/5 ", 4 / 5); Validate(" 1+2-3*4/5", 1 + 2 - 3 * 4 / 5); Validate(" 1 + 2 ", 1 + 2); Validate("1+2*3", 1 + 2 * 3); Validate("1+2*3f", 1 + 2 * 3f); Validate("1+2*3.0", 1 + 2 * 3.0f); Validate("1+2%3.0", 1 + 2 % 3.0f); } [Test] public void Booleans() { Validate("true==true", true == true); Validate("true", true); Validate("false", false); Validate("true && false", true && false); Validate("true && true", true && true); Validate("false && false", false && false); Validate("false && true", false && true); Validate("true && (false||true)", true && (false || true)); Validate("!true", false); Validate("!false", true); Validate("-1>0", false); Validate("0>0", false); Validate("1>0", true); Validate("-1>=0", false); Validate("0>=0", true); Validate("1>=0", true); Validate("-1<0", true); Validate("0<0", false); Validate("1<0", false); Validate("-1<=0", true); Validate("0<=0", true); Validate("1<=0", false); Validate("1==1", true); Validate("1==0", false); Validate("1!=1", false); Validate("1!=0", true); Validate("10-1!=10", true); Validate("10-1<10", true); Validate("10-1>10", false); Validate("false==false", false == false); Validate("true!=true", true != true); Validate("false!=false", false != false); Validate("1!=0 == true", 1 != 0 == true); } [Test] public void TestAndOr() { Validate("true && true", true); Validate("true && false", false); Validate("false&& true ", false); Validate("false&& false ", false); Validate("true || true", true || true); Validate("true || false", true || false); Validate("false|| true ", false || true); Validate("false|| false ", false || false); Validate("false && true || false", false && true || false); Validate("false || true && false", false || true && false); Validate("true || false && true", true || false && true); Validate("true && false || true", true && false || true); Validate("true|| false && true", true || false && true); Validate("false|| true && true", false || true && true); Validate("true || false && true", true || false && true); Validate("false && (false || true || false)", false && (false || true || false)); Validate("false && false || true || false", false && false || true || false); Validate("false && vm.throwException()", false); Validate("true || vm.throwException()", true); } [Test] public void TernaryTests() { Validate("true?1:2", true ? 1 : 2); Validate("false?1:2", false ? 1 : 2); Validate("2>1?1:2", 2 > 1 ? 1 : 2); Validate("-2>-1?-1:-2", -2 > -1 ? -1 : -2); Validate("2>1?(1<0?5:1):2", 2 > 1 ? (1 < 0 ? 5 : 1) : 2); Validate("2<1?(1<0?5:1):2", 2 < 1 ? (1 < 0 ? 5 : 1) : 2); Validate("true?1:vm.throwException()", 1); Validate("false?vm.throwException():2", 2); } [Test] public void ComparingValues() { #pragma warning disable CS1718 // Comparison made to same variable #pragma warning disable CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' Validate("null", null); Validate("'a'=='a'", "a" == "a"); Validate("'a'=='b'", "a" == "b"); Validate("'a'!='a'", "a" != "a"); Validate("'a'!='b'", "a" != "b"); Validate("null==null", null == null); Validate("1==null", 1 == null); Validate("1!=null", 1 != null); Validate("null==1", null == 1); Validate("null!=1", null != 1); Validate("1.1==null", 1.1 == null); Validate("1.1!=null", 1.1 != null); Validate("null==1.1", null == 1.1); Validate("null!=1.1", null != 1.1); Validate("vm.Child==null", vm.Child == null); Validate("vm.Child==vm.Child", vm.Child == vm.Child); Validate("vm.Child!=null", vm.Child != null); Validate("vm.Child!=vm.Child", vm.Child != vm.Child); #pragma warning restore CS1718 // Comparison made to same variable #pragma warning restore CS0472 // The result of the expression is always the same since a value of this type is never equal to 'null' } [Test] public void Comments() { Validate(" 3+4*5 /*With a comment*/", 3 + 4 * 5); Validate("'arne'", "arne"); Validate("'arne'+'bertil'", "arnebertil"); } [Test] public void Strings() { Validate("'arne'", "arne"); Validate("'arne'+'bertil'", "arnebertil"); } [Test] public void Parenthesis() { Validate(" (5) ", 5); Validate(" 1+(5) ", 1 + (5)); Validate(" (1+5) ", (1 + 5)); Validate(" (3*4+5) ", (3 * 4 + 5)); Validate(" 1+(2-3)*4/5", 1 + (2 - 3) * 4 / 5); Validate(" 1+2-(3*4)/5", 1 + 2 - (3 * 4) / 5); Validate(" (3*4+5)*(3*4+5) ", (3 * 4 + 5) * (3 * 4 + 5)); } [Test] public void TestEvaluatingVariables() { Validate("vm.Val1", vm.Val1); Validate("vm.vm2.Val1", vm.vm2.Val1); Validate("vm.time", ViewModel.time); Validate("10f / 2", 10f / 2); Validate("vm.Pi", vm.Pi); Validate("vm.Index+vm.Pi", vm.Index + vm.Pi); Validate("vm.Index/5f", vm.Index / 5f); Validate("vm.Index/vm.Pi", vm.Index / vm.Pi); Validate("vm.Index/-vm.Pi", vm.Index / (-vm.Pi)); Validate(" (vm.Index +vm.Pi)", (vm.Index + vm.Pi)); Validate(" (vm.Index *vm.Pi)", (vm.Index * vm.Pi)); Validate(" (vm.Index -vm.Pi)", (vm.Index - vm.Pi)); Validate(" (vm.Index / vm.Pi)", (vm.Index / vm.Pi)); Validate(" 5 + 12 * vm.Index ", 5 + 12 * vm.Index); Validate(" 5 + 12 * (vm.Index +vm.Pi)", 5 + 12 * (vm.Index + vm.Pi)); Validate(" 5 + 12 * (vm.Index /vm.Pi)", 5 + 12 * (vm.Index / vm.Pi)); Validate("nullVm?.Pi", null); Validate("null", null); Validate("nullVm?.Pi==null", true); Validate("(true?vm:null).one", 1); Validate("MyTime.Time", MyTime.Time); } [Test] public void TestEvaluatingFunctions() { Validate("Math.Min (+10 , +2)", Math.Min(+10, +2)); Validate("Math.Min (10 , -2)", Math.Min(10, -2)); Validate("Math.Min (-10 , 2)", Math.Min(-10, 2)); Validate("Math.Min (+10 , 2)", Math.Min(+10, 2)); Validate("Math.Min (10 , 2)", Math.Min(10, 2)); Validate("Math.Max(10 , 2)", Math.Max(10, 2)); Validate("Math.Min(10 , 2)", Math.Min(10, 2)); Validate("Math.Max(2, 10)", Math.Max(2, 10)); Validate("Math.Min(2 , 10)", Math.Min(2, 10)); Validate("Math.Max (5,10)", Math.Max(5, 10)); //Validate("Math.Sin (2.1)", (float)Math.Sin(2.1f)); //Validate("Math.Cos (2.1)", (float)Math.Cos(2.1f)); Validate("vm.AddEx (+10 , +2)", vm.AddEx(+10, +2)); Validate("Math.Max(vm.Index , rootPi)", (float)Math.Max(vm.Index, Math.PI)); } [Test] public void IndexerTests() { Validate("vm.intArray[3-3]", vm.intArray[0]); Validate("vm.intArray[2]", vm.intArray[2]); Validate("vm[2*2]", vm[2 * 2]); Validate("vm.float2Array[1,1]", vm.float2Array[1, 1]); Validate("vm.strings[2]", vm.strings[2]); Validate("vm.intArray[2]", vm.intArray[2]); vm.vm2.intArray[2] = 99; Validate("vm.vm2.intArray[2]", vm.vm2.intArray[2]); Validate("vm['bob']", vm["bob"]); Validate("vm.vm2['bob']", vm.vm2["bob"]); Validate("vm.vm2[5]", vm.vm2[5]); Validate("vm[5]", vm[5]); vm.float2Array[1, 1] = -2.1f; Validate("vm.float2Array[1, 1]", vm.float2Array[1, 1]); } [Test] public void CanExecuteMethod() { Validate("vm.Testa(1,1)", vm.Testa(1, 1)); Validate("vm.Testb(1,1)", vm.Testb(1, 1)); Validate("vm.Testc(1,1)", vm.Testc(1, 1)); // Doesn't work //Validate("vm.Enbatch(vm.Numbers,8)", vm.Enbatch(vm.Numbers, 8)); // Works, but they don't return the same value //Validate("vm.Enbatched", vm.Enbatched); } [Test] public void IndexerGetTests2() { Validate("vm.Str.Length", vm.Str.Length); Validate("vm.strings[1].Length", vm.strings[1].Length); var expression = Parser.BuildExpression("vm.a=15", Scope); var actual = expression.Evaluate(); } [Test] public void SetValueTests() { ValidateSetValue("vm.a", 12); ValidateSetValue("(true?vm:arne).a", 20); ValidateSetValue("(false?vm:vm.Child).a", 22); var expression = Parser.BuildExpression("vm.a", Scope); var actual = expression.Evaluate(); WriteLine(actual.GetType().Name); } [Test] public void StringFormatTests() { Validate("'arne'", "arne"); Validate("'arne {2+1}'", "arne 3"); Validate("'arne [{2+1,4}]'", "arne [ 3]"); Validate("'arne [{2+1.1:0.00}]'", "arne [3.10]"); } [Test] public void ValidateGetPathResultType() { ValidatePathType("vm.a", vm.a.GetType()); ValidatePathType("vm.Child", vm.Child.GetType()); ValidatePathType("vm.Child.a", vm.Child.a.GetType()); ValidatePathType("vm.Name", vm.Name.GetType()); ValidatePathType("vm.NullString", typeof(string)); } [Test] public void GetAttribute() { var expression = Parser.BuildExpression("vm.Child.ranged", Scope); var attribute = CSharpTopDownParser.GetAttribute<MyAttribute>(expression); if (attribute == null) { Assert.Fail(); } } [Test] public void DisableDuringExecuteWorks() { var expression = Parser.BuildExpression("vm.ThrowsError()", Scope); Scope.DisableExecute = true; expression.Evaluate(); Scope.DisableExecute = false; } private void WriteLine(object obj) { #if UNITY_X_Y_OR_NEWER #else if (obj == null) { //Debug.Log("NULL"); } else { Console.Error.WriteLine(obj.ToString()); } #endif } public void ValidateParse(string code, string parsed) { var actual = Parser.BuildExpression(code, Scope).ToString(); WriteLine(string.Format("{0} => {1} [{2}]", code, parsed, parsed)); if (actual != parsed) { Assert.Fail(); } } public void ValidatePathType(string code, Type expectedType) { Type actual = Parser.GetPathResultType(code, Scope); WriteLine(string.Format("{0} => {1} [{2}]", code, actual, expectedType)); if (actual != expectedType) { Assert.Fail(); } } public void Validate(string code, object expected) { code = code.Replace("'", "\""); var expression = Parser.BuildExpression(code, Scope); var actual = expression.Evaluate(); WriteLine(string.Format("[{0}] = {1} ({2}, {3})", code, actual, expected, expression)); Assert.That(Equals(actual, expected), string.Format("Expected {0} but received {1}", expected, actual)); } public void ValidateSetValue(string code, object value) { code = code.Replace("'", "\""); var expression = Parser.BuildExpression(code, Scope); Parser.SetValue(expression, value); var actual = expression.Evaluate(); WriteLine(string.Format("[{0}] = {1} => {2} ({3})", code, value, actual, expression)); Assert.That(Equals(actual, value), string.Format("Expected {0} but received {1}", value, actual)); } private void ValidatePath(string code, string expectedPath) { var expression = Parser.BuildExpression(code, Scope); string path = expression.GetTokenPath().SJoin(x => x.Text, "|"); WriteLine(string.Format("{0} => {1} ({2})", code, path, expression)); Assert.AreEqual(path, expectedPath); } private void ValidateAssignmentExpression(string code, bool shouldBeValid) { var expression = Parser.BuildExpression(code, Scope); bool isValid = Parser.GetIsValidSetValueExpression(expression); WriteLine(string.Format("{0} => {1} ({2})", code, isValid, shouldBeValid)); Assert.AreEqual(isValid, shouldBeValid); } public class MyAttribute : Attribute { public MyAttribute(float minValue, float maxValue) { MinValue = minValue; MaxValue = maxValue; } public float MinValue { get; private set; } public float MaxValue { get; private set; } public override string ToString() { return string.Format("My {0}-{1}", MinValue, MaxValue); } } public static class MyTime { public static float Time { get { return 11.22f; } } } public class ViewModel { public ViewModel() { Numbers = Enumerable.Range(0, 64).Select(x => new Number { Value = x }).ToList(); Str = "Ooga Booga"; } public void ThrowsError() { throw new InvalidOperationException("Error!"); } public int one = 1; public int zero = 1; public int a = 1; public int Index = 10; public float Pi = 3.14159f; public string Name = "myName"; public float VariableF = 10; public bool VariableB = true; public string Str { get; set; } [My(-20, 100)] public float ranged = 0.2f; public string NullString = null; public ViewModel Child; public static float time = 3.12f; public string[] strings = new[] { "a", "b", "c", "d" }; public int[] intArray = new int[] { 0, -1, -2, -3, -4 }; public float[,] float2Array = new float[,] { { 0, -1 }, { 1, 2 } }; public float Val1 = 2; public ViewModel vm2; public int this[string index] { get { return index.GetHashCode(); } } public int this[int index] { get { return index + 2; } } public int Mindex { private get { return Index; } set { Index = value; } } public int GetIndex() { return Index; } public float AddEx(int x, int y) { return x + y; } public float AddEx(float x, int y) { return x + y - 1; } public static float SAddEx(int x, int y) { return x + y; } public static float SAddEx(float x, int y) { return x + y - 1; } public List<Number> Numbers { get; set; } public class Number { public int Value { get; set; } } public IEnumerable<IEnumerable<Number>> Enbatched { get { return Enbatch(Numbers, 8); } } public float Testa(float a, float b) { return a + b; } public float Testb(int a, float b) { return a + b; } public int Testc(int a, int b) { return a + b; } public IEnumerable<IEnumerable<T>> Enbatch<T>(IEnumerable<T> items, int batchSize) { var left = items.ToList(); while (left.Any()) { yield return left.Take(batchSize); left = left.Skip(batchSize).ToList(); } } public void NoResult() { Console.Error.WriteLine("There will be no result"); } } } } //#endif
36.060393
134
0.47147
[ "MIT" ]
Anatoliy-Lejud/sound-designer-check
Assets/UBindr/Tests/ExpressionTests.cs
25,681
C#
using System; class PrintCompanyInformation { static void Main() { Console.Write("Company name: "); string companyName = Console.ReadLine(); Console.Write("Company address: "); string companyAddress = Console.ReadLine(); Console.Write("Phone number: "); string companyPhone = Console.ReadLine(); Console.Write("Fax number: "); string companyFax = Console.ReadLine(); Console.Write("Web site: "); string companyWebSite = Console.ReadLine(); Console.Write("Manager first name: "); string managerFirstName = Console.ReadLine(); Console.Write("Manager last name: "); string managerLasttName = Console.ReadLine(); Console.Write("Manager age: "); string managerAge = Console.ReadLine(); Console.Write("Manager phone: "); string managerPhone = Console.ReadLine(); if (companyFax == string.Empty) { companyFax = "(no fax)"; } Console.WriteLine("\n{0}\nAddress: {1}\nTel. {2}\nFax: {3}\nWeb site: {4}\nManager: {5} {6} (age: {7}, tel. {8})", companyName, companyAddress, companyPhone, companyFax, companyWebSite, managerFirstName, managerLasttName, managerAge, managerPhone); } }
38.606061
256
0.617739
[ "MIT" ]
b-slavov/Telerik-Software-Academy
01.C# Part 1/04.Console-Input-Output/02.PrintCompanyInformation/PrintCompanyInformation.cs
1,276
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/StructuredQueryCondition.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. namespace TerraFX.Interop.Windows; /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION"]/*' /> public enum CONDITION_OPERATION { /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_IMPLICIT"]/*' /> COP_IMPLICIT = 0, /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_EQUAL"]/*' /> COP_EQUAL = (COP_IMPLICIT + 1), /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_NOTEQUAL"]/*' /> COP_NOTEQUAL = (COP_EQUAL + 1), /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_LESSTHAN"]/*' /> COP_LESSTHAN = (COP_NOTEQUAL + 1), /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_GREATERTHAN"]/*' /> COP_GREATERTHAN = (COP_LESSTHAN + 1), /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_LESSTHANOREQUAL"]/*' /> COP_LESSTHANOREQUAL = (COP_GREATERTHAN + 1), /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_GREATERTHANOREQUAL"]/*' /> COP_GREATERTHANOREQUAL = (COP_LESSTHANOREQUAL + 1), /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_VALUE_STARTSWITH"]/*' /> COP_VALUE_STARTSWITH = (COP_GREATERTHANOREQUAL + 1), /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_VALUE_ENDSWITH"]/*' /> COP_VALUE_ENDSWITH = (COP_VALUE_STARTSWITH + 1), /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_VALUE_CONTAINS"]/*' /> COP_VALUE_CONTAINS = (COP_VALUE_ENDSWITH + 1), /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_VALUE_NOTCONTAINS"]/*' /> COP_VALUE_NOTCONTAINS = (COP_VALUE_CONTAINS + 1), /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_DOSWILDCARDS"]/*' /> COP_DOSWILDCARDS = (COP_VALUE_NOTCONTAINS + 1), /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_WORD_EQUAL"]/*' /> COP_WORD_EQUAL = (COP_DOSWILDCARDS + 1), /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_WORD_STARTSWITH"]/*' /> COP_WORD_STARTSWITH = (COP_WORD_EQUAL + 1), /// <include file='CONDITION_OPERATION.xml' path='doc/member[@name="CONDITION_OPERATION.COP_APPLICATION_SPECIFIC"]/*' /> COP_APPLICATION_SPECIFIC = (COP_WORD_STARTSWITH + 1), }
52.660714
145
0.727026
[ "MIT" ]
IngmarBitter/terrafx.interop.windows
sources/Interop/Windows/Windows/um/StructuredQueryCondition/CONDITION_OPERATION.cs
2,951
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.MachineLearningServices.V20200901Preview.Outputs { /// <summary> /// The Private Endpoint Connection resource. /// </summary> [OutputType] public sealed class PrivateEndpointConnectionResponse { /// <summary> /// Specifies the resource ID. /// </summary> public readonly string Id; /// <summary> /// The identity of the resource. /// </summary> public readonly Outputs.IdentityResponse? Identity; /// <summary> /// Specifies the location of the resource. /// </summary> public readonly string? Location; /// <summary> /// Specifies the name of the resource. /// </summary> public readonly string Name; /// <summary> /// The resource of private end point. /// </summary> public readonly Outputs.PrivateEndpointResponse? PrivateEndpoint; /// <summary> /// A collection of information about the state of the connection between service consumer and provider. /// </summary> public readonly Outputs.PrivateLinkServiceConnectionStateResponse PrivateLinkServiceConnectionState; /// <summary> /// The provisioning state of the private endpoint connection resource. /// </summary> public readonly string ProvisioningState; /// <summary> /// The sku of the workspace. /// </summary> public readonly Outputs.SkuResponse? Sku; /// <summary> /// Contains resource tags defined as key/value pairs. /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// Specifies the type of the resource. /// </summary> public readonly string Type; [OutputConstructor] private PrivateEndpointConnectionResponse( string id, Outputs.IdentityResponse? identity, string? location, string name, Outputs.PrivateEndpointResponse? privateEndpoint, Outputs.PrivateLinkServiceConnectionStateResponse privateLinkServiceConnectionState, string provisioningState, Outputs.SkuResponse? sku, ImmutableDictionary<string, string>? tags, string type) { Id = id; Identity = identity; Location = location; Name = name; PrivateEndpoint = privateEndpoint; PrivateLinkServiceConnectionState = privateLinkServiceConnectionState; ProvisioningState = provisioningState; Sku = sku; Tags = tags; Type = type; } } }
32.136842
112
0.611202
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/MachineLearningServices/V20200901Preview/Outputs/PrivateEndpointConnectionResponse.cs
3,053
C#
// ReSharper disable InconsistentNaming using System; using System.Collections; using System.Collections.Generic; using System.Runtime.InteropServices; using System.Text; using VegaLite.Schema; namespace VegaLite { internal static class HtmlChart { public static string VegaUrl = "https://cdn.jsdelivr.net/npm/vega?noext"; public static string VegaLiteUrl = "https://cdn.jsdelivr.net/npm/vega-lite?noext"; public static string VegaEmbedUrl = "https://cdn.jsdelivr.net/npm/vega-embed?noext"; public static string VegaWebglUrl = "https://cdn.jsdelivr.net/npm/vega-loader-arrow?noext"; public static string D3ColorUrl = "https://d3js.org/d3-color.v1.min"; public static string EChartsUrl = "https://cdn.jsdelivr.net/npm/echarts@4.7.0/dist/echarts.min.js"; internal static readonly Func<int, string> indent = amount => string.Empty.PadLeft(amount * 4, '\u0020'); internal static readonly string ____ = indent(1); internal static readonly string ________ = indent(2); internal static readonly string ____________ = indent(3); internal static readonly string ________________ = indent(4); internal static readonly string ____________________ = indent(5); internal static readonly string ________________________ = indent(6); internal static readonly string ____________________________ = indent(7); internal static readonly string OB = "{"; internal static readonly string CB = "}"; internal static readonly string OC = "/*"; internal static readonly string CC = "*/"; public static readonly string LE = RuntimeInformation.IsOSPlatform(OSPlatform.Windows) ? "\r\n" : "\n"; //http://localhost:15514/variables/csharp/dataset_b767d0e57e604a76be3ba865eeb45f71 private static readonly Func<string, string, string, string> HtmlTemplateFunc = (uid, title, content) => { string html = $"{________}<div id=\"{uid}\">{LE}" + $"{____________}<h1>{title}</h1>{LE}" + $"{____________}<div id=\"vis-{uid}\" class=\"view\">{LE}" + $"{____________}<script language=\"javascript\">{LE}" + content + $"{____________}</script>{LE}" + $"</div>{LE}" + $"{________}</div>{LE}"; return html; }; public static string ElementContentTemplate(Guid id, string title, Chart chart) { string uid = id.ToString().Replace("-", ""); string content = Scripts.RequireVegaLiteSvg; content = content.Replace("_ID_", uid); content = content.Replace("_VEGALITE_SPEC_", chart.Specification.ToJson()); content = Scripts.RequireJS + Scripts.RequireVegaLite + content; return HtmlTemplateFunc(uid, title, content); } public static string WebglElementContentTemplate(Guid id, string title, WebglChart chart) { string uid = id.ToString().Replace("-", ""); string content = Scripts.RequireVegaLiteWebgl; content = content.Replace("_ID_", uid); content = content.Replace("_VEGALITE_SPEC_", chart.Specification.ToJson()); content = Scripts.RequireJS + Scripts.RequireVegaLite + content; return HtmlTemplateFunc(uid, title, content); } public static string DataElementContentTemplate<T>(Guid id, string title, int rows, int columns, Chart<T> chart) where T : IEnumerable { string uid = id.ToString().Replace("-", ""); string content = Scripts.RequireVegaLiteDataBuffered; content = content.Replace("_ID_", uid); content = content.Replace("_DATASET_", chart.DataSetName); content = content.Replace("_ROWS_", $"{rows}"); content = content.Replace("_COLUMNS_", $"{columns}"); content = content.Replace("_VEGALITE_SPEC_", chart.Specification.ToJson()); content = Scripts.RequireJS + Scripts.RequireVegaLite + content; return HtmlTemplateFunc(uid, title, content); } public static string WebglDataElementContentTemplate<T>(Guid id, string title, int rows, int columns, WebglChart<T> chart) where T : IEnumerable { string uid = id.ToString().Replace("-", ""); string content = Scripts.RequireVegaLiteDataBuffered; content = content.Replace("_ID_", uid); content = content.Replace("_DATASET_", chart.DataSetName); content = content.Replace("_ROWS_", $"{rows}"); content = content.Replace("_COLUMNS_", $"{columns}"); content = content.Replace("_VEGALITE_SPEC_", chart.Specification.ToJson()); content = Scripts.RequireJS + Scripts.RequireVegaLite + content; return HtmlTemplateFunc(uid, title, content); } public static string ArrowElementContentTemplate(Guid id, string title, Chart chart) { string uid = id.ToString().Replace("-", ""); string content = Scripts.RequireVegaLiteWebgl; content = content.Replace("_ID_", uid); content = content.Replace("_DATASET_", chart.DataSetName); content = content.Replace("_VEGALITE_SPEC_", chart.Specification.ToJson()); content = Scripts.RequireJS + Scripts.RequireVegaLite + content; return HtmlTemplateFunc(uid, title, content); } public static string ArrowDataElementContentTemplate<T>(Guid id, string title, int rows, int columns, Chart<T> chart) where T : IEnumerable { string uid = id.ToString().Replace("-", ""); string content = Scripts.RequireVegaLiteDataBuffered; content = content.Replace("_ID_", uid); content = content.Replace("_DATASET_", chart.DataSetName); content = content.Replace("_ROWS_", $"{rows}"); content = content.Replace("_COLUMNS_", $"{columns}"); content = content.Replace("_VEGALITE_SPEC_", chart.Specification.ToJson()); content = Scripts.RequireJS + Scripts.RequireVegaLite + content; return HtmlTemplateFunc(uid, title, content); } public static string HtmlTemplate(string content) { string html = $"<!DOCTYPE html>{LE}" + $"<html>{LE}" + $"{____}<head>{LE}" + $"{________}<meta charset=\"utf-8\" />{LE}" + $"{____}</head>{LE}" + $"{____}<body>{LE}" + $"{content}{LE}" + $"{____}</body>{LE}" + $"</html>{LE}"; return html; } //view.change('table', vega.changeset() // .remove(view.data('table')[0]) // .insert(generate(1))) // .runAsync(); //view.data('table', generate(1)) } }
45.476378
166
0.366115
[ "MIT" ]
trmcnealy/VegaLite.NET
VegaLite.NET/HtmlChart.cs
11,553
C#
using System; using System.Collections.Specialized; using System.Threading.Tasks; using CalendarSkill.Dialogs.Main.Resources; using CalendarSkill.Dialogs.Shared.Resources; using CalendarSkill.Dialogs.Summary.Resources; using Microsoft.Bot.Schema; using Microsoft.Bot.Solutions.Authentication; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace CalendarSkillTest.Flow { [TestClass] public class SummaryCalendarFlowTests : CalendarBotTestBase { [TestMethod] public async Task Test_CalendarSummary() { await this.GetTestFlow() .Send("What should I do today") .AssertReply(this.ShowAuth()) .Send(this.GetAuthResponse()) .AssertReplyOneOf(this.FoundEventPrompt()) .AssertReply(this.ShowCalendarList()) .AssertReplyOneOf(this.ReadOutMorePrompt()) .Send("No") .AssertReplyOneOf(this.ActionEndMessage()) .StartTestAsync(); } private string[] ActionEndMessage() { return this.ParseReplies(CalendarSharedResponses.CancellingMessage.Replies, new StringDictionary()); } private string[] WelcomePrompt() { return this.ParseReplies(CalendarMainResponses.CalendarWelcomeMessage.Replies, new StringDictionary()); } private string[] FoundEventPrompt() { var responseParams = new StringDictionary() { { "Count", "1" }, { "EventName1", "test title" }, { "EventDuration", "1 hour" }, }; return this.ParseReplies(SummaryResponses.ShowOneMeetingSummaryMessage.Replies, responseParams); } private Action<IActivity> ShowCalendarList() { return activity => { var messageActivity = activity.AsMessageActivity(); Assert.AreEqual(messageActivity.Attachments.Count, 1); }; } private Action<IActivity> ShowAuth() { return activity => { var messageActivity = activity.AsMessageActivity(); }; } private string[] ReadOutMorePrompt() { return this.ParseReplies(SummaryResponses.ReadOutMorePrompt.Replies, new StringDictionary()); } } }
31.868421
115
0.599092
[ "MIT" ]
ClintFrancis/AI
solutions/Virtual-Assistant/src/csharp/skills/tests/calendarskilltest/Flow/SummaryCalendarFlowTests.cs
2,424
C#
using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Binance.Net.Enums; using Binance.Net.Objects.Spot.SpotData; using CryptoExchange.Net.Objects; namespace Binance.Net.Interfaces.SubClients.Spot { /// <summary> /// Spot order interface /// </summary> public interface IBinanceClientSpotOrder { /// <summary> /// Places a new test order. Test orders are not actually being executed and just test the functionality. /// </summary> /// <param name="symbol">The symbol the order is for</param> /// <param name="side">The order side (buy/sell)</param> /// <param name="type">The order type (limit/market)</param> /// <param name="timeInForce">Lifetime of the order (GoodTillCancel/ImmediateOrCancel)</param> /// <param name="quantity">The amount of the symbol</param> /// <param name="quoteOrderQuantity">The amount of the quote symbol. Only valid for market orders</param> /// <param name="price">The price to use</param> /// <param name="newClientOrderId">Unique id for order</param> /// <param name="stopPrice">Used for stop orders</param> /// <param name="icebergQty">User for iceberg orders</param> /// <param name="orderResponseType">Used for the response JSON</param> /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param> /// <param name="ct">Cancellation token</param> /// <returns>Id's for the placed test order</returns> Task<WebCallResult<BinancePlacedOrder>> PlaceTestOrderAsync(string symbol, OrderSide side, OrderType type, decimal? quantity = null, decimal? quoteOrderQuantity = null, string? newClientOrderId = null, decimal? price = null, TimeInForce? timeInForce = null, decimal? stopPrice = null, decimal? icebergQty = null, OrderResponseType? orderResponseType = null, int? receiveWindow = null, CancellationToken ct = default); /// <summary> /// Places a new order /// </summary> /// <param name="symbol">The symbol the order is for</param> /// <param name="side">The order side (buy/sell)</param> /// <param name="type">The order type</param> /// <param name="timeInForce">Lifetime of the order (GoodTillCancel/ImmediateOrCancel/FillOrKill)</param> /// <param name="quantity">The amount of the symbol</param> /// <param name="quoteOrderQuantity">The amount of the quote symbol. Only valid for market orders</param> /// <param name="price">The price to use</param> /// <param name="newClientOrderId">Unique id for order</param> /// <param name="stopPrice">Used for stop orders</param> /// <param name="icebergQty">Used for iceberg orders</param> /// <param name="orderResponseType">Used for the response JSON</param> /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param> /// <param name="ct">Cancellation token</param> /// <returns>Id's for the placed order</returns> Task<WebCallResult<BinancePlacedOrder>> PlaceOrderAsync(string symbol, OrderSide side, OrderType type, decimal? quantity = null, decimal? quoteOrderQuantity = null, string? newClientOrderId = null, decimal? price = null, TimeInForce? timeInForce = null, decimal? stopPrice = null, decimal? icebergQty = null, OrderResponseType? orderResponseType = null, int? receiveWindow = null, CancellationToken ct = default); /// <summary> /// Cancels a pending order /// </summary> /// <param name="symbol">The symbol the order is for</param> /// <param name="orderId">The order id of the order</param> /// <param name="origClientOrderId">The client order id of the order</param> /// <param name="newClientOrderId">Unique identifier for this cancel</param> /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param> /// <param name="ct">Cancellation token</param> /// <returns>Id's for canceled order</returns> Task<WebCallResult<BinanceCanceledOrder>> CancelOrderAsync(string symbol, long? orderId = null, string? origClientOrderId = null, string? newClientOrderId = null, long? receiveWindow = null, CancellationToken ct = default); /// <summary> /// Cancels all open orders on a symbol /// </summary> /// <param name="symbol">The symbol the order is for</param> /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param> /// <param name="ct">Cancellation token</param> /// <returns>Id's for canceled order</returns> Task<WebCallResult<IEnumerable<BinanceCancelledId>>> CancelAllOpenOrdersAsync(string symbol, long? receiveWindow = null, CancellationToken ct = default); /// <summary> /// Retrieves data for a specific order. Either orderId or origClientOrderId should be provided. /// </summary> /// <param name="symbol">The symbol the order is for</param> /// <param name="orderId">The order id of the order</param> /// <param name="origClientOrderId">The client order id of the order</param> /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param> /// <param name="ct">Cancellation token</param> /// <returns>The specific order</returns> Task<WebCallResult<BinanceOrder>> GetOrderAsync(string symbol, long? orderId = null, string? origClientOrderId = null, long? receiveWindow = null, CancellationToken ct = default); /// <summary> /// Gets a list of open orders /// </summary> /// <param name="symbol">The symbol to get open orders for</param> /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param> /// <param name="ct">Cancellation token</param> /// <returns>List of open orders</returns> Task<WebCallResult<IEnumerable<BinanceOrder>>> GetOpenOrdersAsync(string? symbol = null, int? receiveWindow = null, CancellationToken ct = default); /// <summary> /// Gets all orders for the provided symbol /// </summary> /// <param name="symbol">The symbol to get orders for</param> /// <param name="orderId">If set, only orders with an order id higher than the provided will be returned</param> /// <param name="startTime">If set, only orders placed after this time will be returned</param> /// <param name="endTime">If set, only orders placed before this time will be returned</param> /// <param name="limit">Max number of results</param> /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param> /// <param name="ct">Cancellation token</param> /// <returns>List of orders</returns> Task<WebCallResult<IEnumerable<BinanceOrder>>> GetOrdersAsync(string symbol, long? orderId = null, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, int? receiveWindow = null, CancellationToken ct = default); /// <summary> /// Places a new OCO(One cancels other) order /// </summary> /// <param name="symbol">The symbol the order is for</param> /// <param name="side">The order side (buy/sell)</param> /// <param name="stopLimitTimeInForce">Lifetime of the stop order (GoodTillCancel/ImmediateOrCancel/FillOrKill)</param> /// <param name="quantity">The amount of the symbol</param> /// <param name="price">The price to use</param> /// <param name="stopPrice">The stop price</param> /// <param name="stopLimitPrice">The price for the stop limit order</param> /// <param name="stopClientOrderId">Client id for the stop order</param> /// <param name="limitClientOrderId">Client id for the limit order</param> /// <param name="listClientOrderId">Client id for the order list</param> /// <param name="limitIcebergQuantity">Iceberg quantity for the limit order</param> /// <param name="stopIcebergQuantity">Iceberg quantity for the stop order</param> /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param> /// <param name="ct">Cancellation token</param> /// <returns>Order list info</returns> Task<WebCallResult<BinanceOrderOcoList>> PlaceOcoOrderAsync(string symbol, OrderSide side, decimal quantity, decimal price, decimal stopPrice, decimal? stopLimitPrice = null, string? listClientOrderId = null, string? limitClientOrderId = null, string? stopClientOrderId = null, decimal? limitIcebergQuantity = null, decimal? stopIcebergQuantity = null, TimeInForce? stopLimitTimeInForce = null, int? receiveWindow = null, CancellationToken ct = default); /// <summary> /// Cancels a pending oco order /// </summary> /// <param name="symbol">The symbol the order is for</param> /// <param name="orderListId">The id of the order list to cancel</param> /// <param name="listClientOrderId">The client order id of the order list to cancel</param> /// <param name="newClientOrderId">The new client order list id for the order list</param> /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param> /// <param name="ct">Cancellation token</param> /// <returns>Id's for canceled order</returns> Task<WebCallResult<BinanceOrderOcoList>> CancelOcoOrderAsync(string symbol, long? orderListId = null, string? listClientOrderId = null, string? newClientOrderId = null, long? receiveWindow = null, CancellationToken ct = default); /// <summary> /// Retrieves data for a specific oco order. Either orderListId or listClientOrderId should be provided. /// </summary> /// <param name="orderListId">The list order id of the order</param> /// <param name="listClientOrderId">The client order id of the list order</param> /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param> /// <param name="ct">Cancellation token</param> /// <returns>The specific order list</returns> Task<WebCallResult<BinanceOrderOcoList>> GetOcoOrderAsync(long? orderListId = null, string? listClientOrderId = null, long? receiveWindow = null, CancellationToken ct = default); /// <summary> /// Retrieves a list of oco orders matching the parameters /// </summary> /// <param name="fromId">Only return oco orders with id higher than this</param> /// <param name="startTime">Only return oco orders placed later than this. Only valid if fromId isn't provided</param> /// <param name="endTime">Only return oco orders placed before this. Only valid if fromId isn't provided</param> /// <param name="limit">Max number of results</param> /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param> /// <param name="ct">Cancellation token</param> /// <returns>Order lists matching the parameters</returns> Task<WebCallResult<IEnumerable<BinanceOrderOcoList>>> GetOcoOrdersAsync(long? fromId = null, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, long? receiveWindow = null, CancellationToken ct = default); /// <summary> /// Retrieves a list of open oco orders /// </summary> /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param> /// <param name="ct">Cancellation token</param> /// <returns>Open order lists</returns> Task<WebCallResult<IEnumerable<BinanceOrderOcoList>>> GetOpenOcoOrdersAsync(long? receiveWindow = null, CancellationToken ct = default); /// <summary> /// Gets all user trades for provided symbol /// </summary> /// <param name="symbol">Symbol to get trades for</param> /// <param name="orderId">Get trades for this order id</param> /// <param name="limit">The max number of results</param> /// <param name="fromId">TradeId to fetch from. Default gets most recent trades</param> /// <param name="startTime">Orders newer than this date will be retrieved</param> /// <param name="endTime">Orders older than this date will be retrieved</param> /// <param name="receiveWindow">The receive window for which this request is active. When the request takes longer than this to complete the server will reject the request</param> /// <param name="ct">Cancellation token</param> /// <returns>List of trades</returns> Task<WebCallResult<IEnumerable<BinanceTrade>>> GetUserTradesAsync(string symbol, long? orderId = null, DateTime? startTime = null, DateTime? endTime = null, int? limit = null, long? fromId = null, long? receiveWindow = null, CancellationToken ct = default); } }
65.986425
265
0.660975
[ "MIT" ]
CarlPrentice/Binance.Net
Binance.Net/Interfaces/SubClients/Spot/IBinanceClientSpotOrder.cs
14,585
C#