System.Array.Empty()

Here are the examples of the csharp api System.Array.Empty() taken from open source projects. By voting up you can indicate which examples are most useful and appropriate.

6930 Examples 7

19 Source : CooldownManager.Init.cs
with GNU Affero General Public License v3.0
from 0ceal0t

protected override CooldownConfig[] GetOTHER() => Array.Empty<CooldownConfig>();

19 Source : GaugeManager.Init.cs
with GNU Affero General Public License v3.0
from 0ceal0t

protected override GaugeConfig[] GetOTHER() => Array.Empty<GaugeConfig>();

19 Source : IconManager.Init.cs
with GNU Affero General Public License v3.0
from 0ceal0t

protected override IconReplacer[] GetOTHER() => Array.Empty<IconReplacer>();

19 Source : BuffManager.Init.cs
with GNU Affero General Public License v3.0
from 0ceal0t

protected override BuffConfig[] GetOTHER() => Array.Empty<BuffConfig>();

19 Source : ModelClassGenerator.cs
with MIT License
from 0x1000000

private static ClreplacedDeclarationSyntax GenerateClreplaced(SqModelMeta meta, bool rwClreplacedes, ClreplacedDeclarationSyntax? existingClreplaced)
        {
            ClreplacedDeclarationSyntax result;
            MemberDeclarationSyntax[]? oldMembers = null;
            Dictionary<string,SyntaxList<AttributeListSyntax>>? oldAttributes = null;
            if (existingClreplaced != null)
            {
                result = existingClreplaced;

                oldMembers = result.Members
                    .Where(md =>
                    {
                        if (md is ConstructorDeclarationSyntax)
                        {
                            return false;
                        }

                        if (md is IncompleteMemberSyntax)
                        {
                            return false;
                        }

                        if (md is PropertyDeclarationSyntax p)
                        {
                            if (meta.Properties.Any(mp => mp.Name == p.Identifier.ValueText))
                            {
                                if (p.AttributeLists.Count > 0)
                                {
                                    oldAttributes ??= new Dictionary<string, SyntaxList<AttributeListSyntax>>();
                                    oldAttributes.Add(p.Identifier.ValueText, p.AttributeLists);
                                }
                                return false;
                            }
                        }

                        if (md is MethodDeclarationSyntax method)
                        {
                            var name = method.Identifier.ValueText;

                            if (name.StartsWith("With") || AllMethods.Contains(name) || name.StartsWith(MethodNameGetReader + "For") || name.StartsWith(MethodNameGetUpdater + "For"))
                            {
                                return false;
                            }
                        }

                        if (md is ClreplacedDeclarationSyntax clreplacedDeclaration)
                        {
                            var name = clreplacedDeclaration.Identifier.ValueText;

                            if (name == meta.Name + ReaderClreplacedSuffix || name.StartsWith(meta.Name + ReaderClreplacedSuffix + "For"))
                            {
                                return false;
                            }
                            if (name == meta.Name + UpdaterClreplacedSuffix || name.StartsWith(meta.Name + UpdaterClreplacedSuffix + "For"))
                            {
                                return false;
                            }
                        }

                        return true;
                    })
                    .ToArray();

                result = result.RemoveNodes(result.DescendantNodes().OfType<MemberDeclarationSyntax>(), SyntaxRemoveOptions.KeepNoTrivia)!;

            }
            else
            {
                result = SyntaxFactory.ClreplacedDeclaration(meta.Name)
                    .WithModifiers(existingClreplaced?.Modifiers ?? Modifiers(SyntaxKind.PublicKeyword));
            }

            result = result
                .AddMembers(Constructors(meta)
                    .Concat(GenerateStaticFactory(meta))
                    .Concat(rwClreplacedes ? GenerateOrdinalStaticFactory(meta) : Array.Empty<MemberDeclarationSyntax>())
                    .Concat(Properties(meta, oldAttributes))
                    .Concat(GenerateWithModifiers(meta))
                    .Concat(GenerateGetColumns(meta))
                    .Concat(GenerateMapping(meta))
                    .Concat(rwClreplacedes ? GenerateReaderClreplaced(meta): Array.Empty<MemberDeclarationSyntax>())
                    .Concat(rwClreplacedes ? GenerateWriterClreplaced(meta) : Array.Empty<MemberDeclarationSyntax>())
                    .ToArray());

            if (oldMembers != null && oldMembers.Length > 0)
            {
                result = result.AddMembers(oldMembers);
            }

            return result;
        }

19 Source : ModelClassGenerator.cs
with MIT License
from 0x1000000

public static IEnumerable<MemberDeclarationSyntax> GenerateWriterClreplaced(SqModelMeta meta, SqModelTableRef tableRef, bool addName)
        {
            if (!HasUpdater(tableRef))
            {
                return Array.Empty<MemberDeclarationSyntax>();
            }

            var tableType = ExtractTableTypeName(meta, tableRef);
            var clreplacedName = meta.Name + UpdaterClreplacedSuffix;
            if (addName)
            {
                clreplacedName += $"For{tableRef.TableTypeName}";
            }
            var clreplacedType = SyntaxFactory.ParseTypeName(clreplacedName);

            bool hasPk = meta.HasPk();

            var baseInterfaceKeyLess = SyntaxFactory.GenericName(
                    SyntaxFactory.Identifier(nameof(ISqModelUpdater<object, object>)))
                .WithTypeArgumentList(
                    SyntaxFactory.TypeArgumentList(
                        SyntaxFactory.SeparatedList<TypeSyntax>(
                            new SyntaxNodeOrToken[]
                            {
                                SyntaxFactory.IdentifierName(meta.Name),
                                SyntaxFactory.Token(SyntaxKind.CommaToken),
                                SyntaxFactory.IdentifierName(tableType)
                            })));

            var baseInterfaceKey = SyntaxFactory.GenericName(
                    SyntaxFactory.Identifier(nameof(ISqModelUpdaterKey<object, object>)))
                .WithTypeArgumentList(
                    SyntaxFactory.TypeArgumentList(
                        SyntaxFactory.SeparatedList<TypeSyntax>(
                            new SyntaxNodeOrToken[]
                            {
                                SyntaxFactory.IdentifierName(meta.Name),
                                SyntaxFactory.Token(SyntaxKind.CommaToken),
                                SyntaxFactory.IdentifierName(tableType)
                            })));
            var baseInterface = hasPk ? baseInterfaceKey : baseInterfaceKeyLess;

            //Instance
            var instance = SyntaxFactory.PropertyDeclaration(
                    clreplacedType,
                    SyntaxFactory.Identifier("Instance"))
                .WithModifiers(
                    SyntaxFactory.TokenList(
                        SyntaxFactory.Token(SyntaxKind.PublicKeyword),
                        SyntaxFactory.Token(SyntaxKind.StaticKeyword)))
                .WithAccessorList(
                    SyntaxFactory.AccessorList(
                        SyntaxFactory.SingletonList(
                            SyntaxFactory.AccessorDeclaration(
                                    SyntaxKind.GetAccessorDeclaration)
                                .WithSemicolonToken(
                                    SyntaxFactory.Token(SyntaxKind.SemicolonToken)))))
                .WithInitializer(
                    SyntaxFactory.EqualsValueClause(
                        SyntaxFactory.ObjectCreationExpression(clreplacedType)
                            .WithArgumentList(SyntaxFactory.ArgumentList())))
                .WithSemicolonToken(
                    SyntaxFactory.Token(SyntaxKind.SemicolonToken));


            //GetMapping
            var dataMapSetterName = "dataMapSetter";

            var parameterDataMapperSetter = SyntaxFactory.Parameter(
                    SyntaxFactory.Identifier(dataMapSetterName))
                .WithType(
                    SyntaxFactory.GenericName(
                            SyntaxFactory.Identifier(nameof(IDataMapSetter<object, object>)))
                        .WithTypeArgumentList(
                            SyntaxFactory.TypeArgumentList(
                                SyntaxFactory.SeparatedList<TypeSyntax>(
                                    new SyntaxNodeOrToken[]{
                                        SyntaxFactory.IdentifierName(tableType),
                                        SyntaxFactory.Token(SyntaxKind.CommaToken),
                                        SyntaxFactory.IdentifierName(meta.Name)}))));


            var updaterClreplacedDeclaration = SyntaxFactory.ClreplacedDeclaration(clreplacedName)
                .WithModifiers(SyntaxFactory.TokenList(SyntaxFactory.Token(SyntaxKind.PrivateKeyword)))
                .WithBaseList(SyntaxFactory.BaseList().AddTypes(SyntaxFactory.SimpleBaseType(baseInterface)))
                .AddMembers(
                    instance,
                    GetMapping(baseInterfaceKeyLess, MethodNameGetMapping));

            if (hasPk)
            {
                updaterClreplacedDeclaration = updaterClreplacedDeclaration.AddMembers(
                    GetMapping(baseInterfaceKey, MethodNameGetUpdateKeyMapping),
                    GetMapping(baseInterfaceKey, MethodNameGetUpdateMapping));
            }

            MethodDeclarationSyntax GetMapping(GenericNameSyntax bi, string s)
            {
                return SyntaxFactory.MethodDeclaration(SyntaxFactory.IdentifierName(nameof(IRecordSetterNext)),
                        SyntaxFactory.Identifier(s))
                    .WithExplicitInterfaceSpecifier(SyntaxFactory.ExplicitInterfaceSpecifier(bi))
                    .WithParameterList(
                        SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(parameterDataMapperSetter)))
                    .WithBody(
                        SyntaxFactory.Block(
                            SyntaxFactory.SingletonList<Microsoft.Codereplacedysis.CSharp.Syntax.StatementSyntax>(
                                SyntaxFactory.ReturnStatement(
                                    SyntaxFactory.InvocationExpression(
                                            SyntaxFactory.MemberAccessExpression(
                                                SyntaxKind.SimpleMemberAccessExpression,
                                                SyntaxFactory.IdentifierName(meta.Name),
                                                SyntaxFactory.IdentifierName(s)))
                                        .WithArgumentList(
                                            SyntaxFactory.ArgumentList(
                                                SyntaxFactory.SingletonSeparatedList(
                                                    SyntaxFactory.Argument(
                                                        SyntaxFactory.IdentifierName(dataMapSetterName)))))))));
            }

            var getUpdater = SyntaxFactory.MethodDeclaration(baseInterface, addName ? $"{MethodNameGetUpdater}For{tableRef.TableTypeName}" : MethodNameGetUpdater)
                .AddModifiers(SyntaxFactory.Token(SyntaxKind.PublicKeyword),
                    SyntaxFactory.Token(SyntaxKind.StaticKeyword))
                .AddBodyStatements(SyntaxFactory.ReturnStatement(MemberAccess(clreplacedName, "Instance")));

            return new MemberDeclarationSyntax[] { getUpdater, updaterClreplacedDeclaration };
        }

19 Source : SqModelSelectBuilder.cs
with MIT License
from 0x1000000

public IReadOnlyList<ExprColumn> GetColumns(TTable table) => Array.Empty<TableColumn>();

19 Source : HeifContext.cs
with GNU Lesser General Public License v3.0
from 0xC0000054

public IReadOnlyList<HeifEncoderDescriptor> GetEncoderDescriptors(HeifCompressionFormat format = HeifCompressionFormat.Undefined,
                                                                          string nameFilter = null)
        {
            VerifyNotDisposed();

            // LibHeif only has 5 built-in encoders as of version 1.9.0, we use 10 in case more
            // built-in encoders are added in future versions.
            var nativeEncoderDescriptors = new heif_encoder_descriptor[10];
            int returnedEncoderCount;

            unsafe
            {
                fixed (heif_encoder_descriptor* ptr = nativeEncoderDescriptors)
                {
                    returnedEncoderCount = LibHeifNative.heif_context_get_encoder_descriptors(this.context,
                                                                                              format,
                                                                                              nameFilter,
                                                                                              ptr,
                                                                                              nativeEncoderDescriptors.Length);
                }
            }

            if (returnedEncoderCount == 0)
            {
                return Array.Empty<HeifEncoderDescriptor>();
            }
            else
            {
                var encoderDescriptors = new HeifEncoderDescriptor[returnedEncoderCount];

                for (int i = 0; i < returnedEncoderCount; i++)
                {
                    encoderDescriptors[i] = new HeifEncoderDescriptor(nativeEncoderDescriptors[i]);
                }

                return encoderDescriptors;
            }
        }

19 Source : ModelClassGenerator.cs
with MIT License
from 0x1000000

public static MemberDeclarationSyntax[] GenerateMapping(SqModelMeta meta, SqModelTableRef tableRef)
        {
            if (!HasUpdater(tableRef))
            {
                return Array.Empty<MemberDeclarationSyntax>();
            }

            if (meta.HasPk())
            {
                return new []
                {
                    MethodDeclarationSyntax(meta, tableRef, MethodNameGetMapping, null),
                    MethodDeclarationSyntax(meta, tableRef,MethodNameGetUpdateKeyMapping, true),
                    MethodDeclarationSyntax(meta, tableRef,MethodNameGetUpdateMapping, false)
                };
            }
            else
            {
                return new [] { MethodDeclarationSyntax(meta, tableRef, MethodNameGetMapping, null) };
            }


            static MemberDeclarationSyntax MethodDeclarationSyntax(SqModelMeta sqModelMeta, SqModelTableRef tableRef, string name, bool? pkFilter)
            {
                var setter = SyntaxFactory.IdentifierName("s");
                ExpressionSyntax chain = setter;

                foreach (var metaProperty in sqModelMeta.Properties.Where(p => pkFilter.HasValue? p.IsPrimaryKey == pkFilter.Value : !p.IsIdenreplacedy))
                {
                    var col = setter.MemberAccess(nameof(IDataMapSetter<object, object>.Target))
                        .MemberAccess(metaProperty.Column.First(c=>c.TableRef.Equals(tableRef)).ColumnName);
                    ExpressionSyntax prop = setter.MemberAccess(nameof(IDataMapSetter<object, object>.Source))
                        .MemberAccess(metaProperty.Name);
                    if (metaProperty.CastType != null)
                    {
                        prop = SyntaxFactory.CastExpression(SyntaxFactory.ParseTypeName(metaProperty.Type), prop);
                    }

                    chain = chain.MemberAccess("Set").Invoke(col, prop);
                }


                var methodDeclarationSyntax = SyntaxFactory
                    .MethodDeclaration(SyntaxFactory.ParseTypeName(nameof(IRecordSetterNext)), name)
                    .WithModifiers(Modifiers(SyntaxKind.PublicKeyword, SyntaxKind.StaticKeyword))
                    .AddParameterListParameters(FuncParameter("s",
                        $"{nameof(IDataMapSetter<object, object>)}<{ExtractTableTypeName(sqModelMeta, tableRef)},{sqModelMeta.Name}>"))
                    .WithBody(SyntaxFactory.Block(SyntaxFactory.ReturnStatement(chain)));
                return methodDeclarationSyntax;
            }
        }

19 Source : HeifImageHandle.cs
with GNU Lesser General Public License v3.0
from 0xC0000054

public IReadOnlyList<HeifItemId> GetAuxiliaryImageIds()
        {
            VerifyNotDisposed();

            if (LibHeifVersion.Is1Point11OrLater)
            {
                const heif_auxiliary_image_filter filter = heif_auxiliary_image_filter.OmitAlpha | heif_auxiliary_image_filter.OmitDepth;

                int count = LibHeifNative.heif_image_handle_get_number_of_auxiliary_images(this.imageHandle, filter);

                if (count == 0)
                {
                    return Array.Empty<HeifItemId>();
                }

                var ids = new HeifItemId[count];

                unsafe
                {
                    fixed (HeifItemId* ptr = ids)
                    {
                        int filledCount = LibHeifNative.heif_image_handle_get_list_of_auxiliary_image_IDs(this.imageHandle,
                                                                                                          filter,
                                                                                                          ptr,
                                                                                                          count);
                        if (filledCount != count)
                        {
                            ExceptionUtil.ThrowHeifException(Resources.CannotGetAllAuxillaryImages);
                        }
                    }
                }

                return ids;
            }
            else
            {
                return Array.Empty<HeifItemId>();
            }
        }

19 Source : HeifImageHandle.cs
with GNU Lesser General Public License v3.0
from 0xC0000054

public IReadOnlyList<HeifItemId> GetDepthImageIds()
        {
            VerifyNotDisposed();

            int count = LibHeifNative.heif_image_handle_get_number_of_depth_images(this.imageHandle);

            if (count == 0)
            {
                return Array.Empty<HeifItemId>();
            }

            var ids = new HeifItemId[count];

            unsafe
            {
                fixed (HeifItemId* ptr = ids)
                {
                    int filledCount = LibHeifNative.heif_image_handle_get_list_of_depth_image_IDs(this.imageHandle,
                                                                                                  ptr,
                                                                                                  count);
                    if (filledCount != count)
                    {
                        ExceptionUtil.ThrowHeifException(Resources.CannotGetAllMetadataBlockIds);
                    }
                }
            }

            return ids;
        }

19 Source : HeifImageHandle.cs
with GNU Lesser General Public License v3.0
from 0xC0000054

public IReadOnlyList<HeifItemId> GetMetadataBlockIds(string type = null, string contentType = null)
        {
            VerifyNotDisposed();

            int count = LibHeifNative.heif_image_handle_get_number_of_metadata_blocks(this.imageHandle, type);

            if (count == 0)
            {
                return Array.Empty<HeifItemId>();
            }

            var ids = new HeifItemId[count];

            unsafe
            {
                fixed (HeifItemId* ptr = ids)
                {
                    int filledCount = LibHeifNative.heif_image_handle_get_list_of_metadata_block_IDs(this.imageHandle,
                                                                                                     type,
                                                                                                     ptr,
                                                                                                     count);
                    if (filledCount != count)
                    {
                        ExceptionUtil.ThrowHeifException(Resources.CannotGetAllMetadataBlockIds);
                    }
                }
            }

            // The type must be defined in order to filter by content type.
            if (type != null && contentType != null)
            {
                var matchingItems = new List<HeifItemId>();

                for (int i = 0; i < ids.Length; i++)
                {
                    var id = ids[i];
                    var metadataContentType = LibHeifNative.heif_image_handle_get_metadata_content_type(this.imageHandle, id);

                    if (contentType.Equals(metadataContentType.GetStringValue(), StringComparison.Ordinal))
                    {
                        matchingItems.Add(id);
                    }
                }

                return matchingItems;
            }
            else
            {
                return ids;
            }
        }

19 Source : HeifImageHandle.cs
with GNU Lesser General Public License v3.0
from 0xC0000054

public IReadOnlyList<HeifItemId> GetThumbnailImageIds()
        {
            VerifyNotDisposed();

            int count = LibHeifNative.heif_image_handle_get_number_of_thumbnails(this.imageHandle);

            if (count == 0)
            {
                return Array.Empty<HeifItemId>();
            }

            var ids = new HeifItemId[count];

            unsafe
            {
                fixed (HeifItemId* ptr = ids)
                {
                    int filledCount = LibHeifNative.heif_image_handle_get_list_of_thumbnail_IDs(this.imageHandle,
                                                                                                ptr,
                                                                                                count);
                    if (filledCount != count)
                    {
                        ExceptionUtil.ThrowHeifException(Resources.CannotGetAllThumbnailIds);
                    }
                }
            }

            return ids;
        }

19 Source : ExifParser.cs
with MIT License
from 0xC0000054

public unsafe byte[] GetValueBytesFromOffset()
            {
                if (!this.OffsetFieldContainsValue)
                {
                    return null;
                }

                TagDataType type = this.entry.Type;
                uint count = this.entry.Count;
                uint offset = this.entry.Offset;

                if (count == 0)
                {
                    return Array.Empty<byte>();
                }

                // Paint.NET always stores data in little-endian byte order.
                byte[] bytes;
                if (type == TagDataType.Byte ||
                    type == TagDataType.Ascii ||
                    type == TagDataType.SByte ||
                    type == TagDataType.Undefined)
                {
                    bytes = new byte[count];

                    if (this.offsetIsBigEndian)
                    {
                        switch (count)
                        {
                            case 1:
                                bytes[0] = (byte)((offset >> 24) & 0x000000ff);
                                break;
                            case 2:
                                bytes[0] = (byte)((offset >> 24) & 0x000000ff);
                                bytes[1] = (byte)((offset >> 16) & 0x000000ff);
                                break;
                            case 3:
                                bytes[0] = (byte)((offset >> 24) & 0x000000ff);
                                bytes[1] = (byte)((offset >> 16) & 0x000000ff);
                                bytes[2] = (byte)((offset >> 8) & 0x000000ff);
                                break;
                            case 4:
                                bytes[0] = (byte)((offset >> 24) & 0x000000ff);
                                bytes[1] = (byte)((offset >> 16) & 0x000000ff);
                                bytes[2] = (byte)((offset >> 8) & 0x000000ff);
                                bytes[3] = (byte)(offset & 0x000000ff);
                                break;
                        }
                    }
                    else
                    {
                        switch (count)
                        {
                            case 1:
                                bytes[0] = (byte)(offset & 0x000000ff);
                                break;
                            case 2:
                                bytes[0] = (byte)(offset & 0x000000ff);
                                bytes[1] = (byte)((offset >> 8) & 0x000000ff);
                                break;
                            case 3:
                                bytes[0] = (byte)(offset & 0x000000ff);
                                bytes[1] = (byte)((offset >> 8) & 0x000000ff);
                                bytes[2] = (byte)((offset >> 16) & 0x000000ff);
                                break;
                            case 4:
                                bytes[0] = (byte)(offset & 0x000000ff);
                                bytes[1] = (byte)((offset >> 8) & 0x000000ff);
                                bytes[2] = (byte)((offset >> 16) & 0x000000ff);
                                bytes[3] = (byte)((offset >> 24) & 0x000000ff);
                                break;
                        }
                    }
                }
                else if (type == TagDataType.Short || type == TagDataType.SShort)
                {
                    int byteArrayLength = unchecked((int)count) * sizeof(ushort);
                    bytes = new byte[byteArrayLength];

                    fixed (byte* ptr = bytes)
                    {
                        ushort* ushortPtr = (ushort*)ptr;

                        if (this.offsetIsBigEndian)
                        {
                            switch (count)
                            {
                                case 1:
                                    ushortPtr[0] = (ushort)((offset >> 16) & 0x0000ffff);
                                    break;
                                case 2:
                                    ushortPtr[0] = (ushort)((offset >> 16) & 0x0000ffff);
                                    ushortPtr[1] = (ushort)(offset & 0x0000ffff);
                                    break;
                            }
                        }
                        else
                        {
                            switch (count)
                            {
                                case 1:
                                    ushortPtr[0] = (ushort)(offset & 0x0000ffff);
                                    break;
                                case 2:
                                    ushortPtr[0] = (ushort)(offset & 0x0000ffff);
                                    ushortPtr[1] = (ushort)((offset >> 16) & 0x0000ffff);
                                    break;
                            }
                        }
                    }
                }
                else
                {
                    bytes = new byte[4];

                    fixed (byte* ptr = bytes)
                    {
                        // The offset is stored as little-endian in memory.
                        *(uint*)ptr = offset;
                    }
                }

                return bytes;
            }

19 Source : EndianBinaryReader.cs
with MIT License
from 0xC0000054

public byte[] ReadBytes(int count)
        {
            if (count < 0)
            {
                throw new ArgumentOutOfRangeException(nameof(count));
            }
            VerifyNotDisposed();

            if (count == 0)
            {
                return Array.Empty<byte>();
            }

            byte[] bytes = new byte[count];

            int totalBytesRead = 0;

            while (totalBytesRead < count)
            {
                int bytesRead = ReadInternal(bytes, totalBytesRead, count - totalBytesRead);

                if (bytesRead == 0)
                {
                    throw new EndOfStreamException();
                }

                totalBytesRead += bytesRead;
            }

            return bytes;
        }

19 Source : GmicPipeServer.cs
with GNU General Public License v3.0
from 0xC0000054

private IReadOnlyList<GmicLayer> GetRequestedLayers(InputMode mode)
        {
            if (mode == InputMode.ActiveLayer ||
                mode == InputMode.ActiveAndBelow)
            {
                // The last layer in the list is always the layer the user has selected in Paint.NET,
                // so it will be treated as the active layer.
                // The clipboard layer (if present) will be placed above the active layer.

                return new GmicLayer[] { layers[layers.Count - 1] };
            }
            else if (mode == InputMode.AllVisibleLayersDescending)
            {
                List<GmicLayer> reversed = new List<GmicLayer>(layers.Count);

                for (int i = layers.Count - 1; i >= 0; i--)
                {
                    reversed.Add(layers[i]);
                }

                return reversed;
            }
            else
            {
                switch (mode)
                {
                    case InputMode.AllLayers:
                    case InputMode.ActiveAndAbove:
                    case InputMode.AllVisibleLayers:
                        return layers;
                    case InputMode.AllHiddenLayers:
                    case InputMode.AllHiddenLayersDescending:
                        return Array.Empty<GmicLayer>();
                    default:
                        throw new ArgumentException("The mode was not handled: " + mode.ToString());
                }
            }
        }

19 Source : MethodJitter.cs
with MIT License
from 0xd4d

static IEnumerable<Type> GetTypes(replacedembly asm) {
			Type?[] allTypes;
			try {
				allTypes = asm.GetTypes();
			}
			catch (ReflectionTypeLoadException ex) {
				allTypes = ex.Types ?? Array.Empty<Type>();
				Console.WriteLine("Failed to load one or more types");
			}
			bool ignoredTypeMessage = false;
			foreach (var type in allTypes) {
				if (!(type is null)) {
					if (type.IsGenericTypeDefinition) {
						if (!ignoredTypeMessage) {
							ignoredTypeMessage = true;
							Console.WriteLine("Ignoring all generic types");
						}
						continue;
					}
					yield return type;
				}
			}
		}

19 Source : VshCrypto.cs
with MIT License
from 13xforever

public static byte[] AsBytes(this string hexString)
        {
            if (hexString == null)
                return null;

            if (hexString.Length == 0)
                return Array.Empty<byte>();

            if (hexString.Length%2 == 1)
                throw new ArgumentException("Hex string cannot have an odd number of characters");

            var result = new byte[hexString.Length / 2];
            for (int ri = 0, si = 0; ri < result.Length; ri++, si += 2)
                result[ri] = byte.Parse(hexString.Substring(si, 2), NumberStyles.HexNumber);
            return result;
        }

19 Source : DiscordRPforVSPackage.cs
with GNU Affero General Public License v3.0
from 1thenikita

public async System.Threading.Tasks.Task UpdatePresenceAsync(Doreplacedent doreplacedent, Boolean overrideTimestampReset = false)
        {
            try
            {
                await this.JoinableTaskFactory.SwitchToMainThreadAsync();

                if (!Settings.enabled)
                {
                    if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
                        if (!this.Discord.Initialize())
                            ActivityLog.LogError("DiscordRPforVS", $"{Translates.LogError(Settings.Default.translates)}");

                    this.Discord.ClearPresence();
                    return;
                }

                this.Presence.Details = this.Presence.State = this.replacedets.LargeImageKey = this.replacedets.LargeImageText = this.replacedets.SmallImageKey = this.replacedets.SmallImageText = String.Empty;

                if (Settings.secretMode)
                {
                    this.Presence.Details = Translates.PresenceDetails(Settings.Default.translates);
                    this.Presence.State = Translates.PresenceState(Settings.Default.translates);
                    this.replacedets.LargeImageKey = this.versionImageKey;
                    this.replacedets.LargeImageText = this.versionString;
                    this.replacedets.SmallImageKey = this.replacedets.SmallImageText = "";
                    goto finish;
                }

                this.Presence.Details = this.Presence.State = "";
                String[] language = Array.Empty<String>();

                if (doreplacedent != null)
                {
                    String filename = Path.GetFileName(path: doreplacedent.FullName).ToUpperInvariant(), ext = Path.GetExtension(filename);
                    List<KeyValuePair<String[], String[]>> list = Constants.Languages.Where(lang => Array.IndexOf(lang.Key, filename) > -1 || Array.IndexOf(lang.Key, ext) > -1).ToList();
                    language = list.Count > 0 ? list[0].Value : Array.Empty<String>();
                }

                Boolean supported = language.Length > 0;
                this.replacedets.LargeImageKey = Settings.largeLanguage ? supported ? language[0] : "text" : this.versionImageKey;
                this.replacedets.LargeImageText = Settings.largeLanguage ? supported ? language[1] + " " + Translates.File(Settings.Default.translates) : Translates.UnrecognizedExtension(Settings.Default.translates) : this.versionString;
                this.replacedets.SmallImageKey = Settings.largeLanguage ? this.versionImageKey : supported ? language[0] : "text";
                this.replacedets.SmallImageText = Settings.largeLanguage ? this.versionString : supported ? language[1] + " " + Translates.File(Settings.Default.translates) : Translates.UnrecognizedExtension(Settings.Default.translates);

                if (Settings.showFileName)
                    this.Presence.Details = !(doreplacedent is null) ? Path.GetFileName(doreplacedent.FullName) : Translates.NoFile(Settings.Default.translates);

                if (Settings.showSolutionName)
                {
                    Boolean idling = ide.Solution is null || String.IsNullOrEmpty(ide.Solution.FullName);
                    this.Presence.State = idling ? Translates.Idling(Settings.Default.translates) : $"{Translates.Developing(Settings.Default.translates)} {Path.GetFileNameWithoutExtension(ide.Solution.FileName)}";

                    if (idling)
                    {
                        this.replacedets.LargeImageKey = this.versionImageKey;
                        this.replacedets.LargeImageText = this.versionString;
                        this.replacedets.SmallImageKey = this.replacedets.SmallImageText = "";
                    }
                }

                if (Settings.showTimestamp && doreplacedent != null)
                {
                    if (!this.InitializedTimestamp)
                    {
                        this.InitialTimestamps = this.Presence.Timestamps = new Timestamps() { Start = DateTime.UtcNow };
                        this.InitializedTimestamp = true;
                    }

                    if (Settings.resetTimestamp && !overrideTimestampReset)
                        this.Presence.Timestamps = new Timestamps() { Start = DateTime.UtcNow };
                    else if (Settings.resetTimestamp && overrideTimestampReset)
                        this.Presence.Timestamps = this.CurrentTimestamps;
                    else if (!Settings.resetTimestamp && !overrideTimestampReset)
                        this.Presence.Timestamps = this.InitialTimestamps;

                    this.CurrentTimestamps = this.Presence.Timestamps;
                }

                finish:;
                this.Presence.replacedets = this.replacedets;

                if (!this.Discord.IsInitialized && !this.Discord.IsDisposed)
                    if (!this.Discord.Initialize())
                        ActivityLog.LogError("DiscordRPforVS", Translates.LogError(Settings.Default.translates));

                this.Discord.SetPresence(this.Presence);
            }
            catch (ArgumentException e)
            {
                ActivityLog.LogError(e.Source, e.Message);
            }
        }

19 Source : HierarchicalResolver.cs
with MIT License
from Abc-Arbitrage

private static void AddNode(Node root, LoggerDefinition logger, IAppender[] appenders)
        {
            var parts = logger.Name?.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries) ?? Array.Empty<string>();
            var node = root;
            var path = "";

            foreach (var part in parts)
            {
                path = (path + "." + part).Trim('.');

                if (!node.Children.ContainsKey(part))
                {
                    node.Children[part] = new Node
                    {
                        Appenders = node.Appenders,
                        Level = node.Level,
                        LogEventPoolExhaustionStrategy = node.LogEventPoolExhaustionStrategy,
                        LogEventArgumentExhaustionStrategy = node.LogEventArgumentExhaustionStrategy
                    };
                }

                node = node.Children[part];
            }

            node.Appenders = (logger.IncludeParentAppenders ? appenders.Union(node.Appenders) : appenders).Distinct();
            node.LogEventPoolExhaustionStrategy = logger.LogEventPoolExhaustionStrategy;
            node.LogEventArgumentExhaustionStrategy = logger.LogEventArgumentExhaustionStrategy;
            node.Level = logger.Level;
        }

19 Source : Log.Custom.cs
with MIT License
from Abc-Arbitrage

internal void ResetConfiguration()
        {
            var config = _logManager?.ResolveLogConfig(Name);

            Appenders = config?.Appenders ?? Array.Empty<IAppender>();
            LogEventPoolExhaustionStrategy = config?.LogEventPoolExhaustionStrategy ?? default;
            LogEventArgumentExhaustionStrategy = config?.LogEventArgumentExhaustionStrategy ?? default;
            _logLevel = config?.Level ?? Level.Fatal;
        }

19 Source : MixedRealityControllerMappingProfile.cs
with Apache License 2.0
from abist-co-ltd

private static Handedness[] GetSupportedHandedness(Type controllerType)
        {
            var attribute = MixedRealityControllerAttribute.Find(controllerType);
            return attribute != null ? attribute.SupportedHandedness : Array.Empty<Handedness>();
        }

19 Source : MixedRealityGesturesProfileInspector.cs
with Apache License 2.0
from abist-co-ltd

private static MixedRealityInputAction[] GetInputActions()
        {
            if (!MixedRealityToolkit.IsInitialized ||
                !MixedRealityToolkit.Instance.HasActiveProfile ||
                MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile == null ||
                MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.InputActionsProfile == null)
            {
                return Array.Empty<MixedRealityInputAction>();
            }

            return MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.InputActionsProfile.InputActions;
        }

19 Source : MixedRealityInputActionRulesInspector.cs
with Apache License 2.0
from abist-co-ltd

private static MixedRealityInputAction[] GetInputActions()
        {
            if (!MixedRealityToolkit.IsInitialized ||
                !MixedRealityToolkit.Instance.HasActiveProfile ||
                MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile == null ||
                MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.InputActionsProfile == null)
            {
                return System.Array.Empty<MixedRealityInputAction>();
            }

            return MixedRealityToolkit.Instance.ActiveProfile.InputSystemProfile.InputActionsProfile.InputActions;
        }

19 Source : MixedRealitySceneSystemProfileInspector.cs
with Apache License 2.0
from abist-co-ltd

public override void OnInspectorGUI()
        {
            if (!MixedRealityToolkit.IsInitialized)
            {
                return;
            }
            
            if (!RenderProfileHeader(Profilereplacedle, ProfileDescription, target))
            {
                return;
            }

            MixedRealityInspectorUtility.CheckMixedRealityConfigured(true);

            serializedObject.Update();

            MixedRealitySceneSystemProfile profile = (MixedRealitySceneSystemProfile)target;

            RenderFoldout(ref showEditorProperties, "Editor Settings", () =>
            {
                using (new EditorGUI.IndentLevelScope())
                {
                    EditorGUILayout.PropertyField(editorManageBuildSettings);
                    EditorGUILayout.PropertyField(editorManageLoadedScenes);
                    EditorGUILayout.PropertyField(editorEnforceSceneOrder);
                    EditorGUILayout.PropertyField(editorEnforceLightingSceneTypes);

                    if (editorEnforceLightingSceneTypes.boolValue)
                    {
                        EditorGUILayout.Space();
                        EditorGUILayout.HelpBox("Below are the component types that will be allowed in lighting scenes. Types not found in this list will be moved to another scene.", MessageType.Info);
                        EditorGUIUtility.labelWidth = LightingSceneTypesLabelWidth;
                        EditorGUILayout.PropertyField(permittedLightingSceneComponentTypes, true);
                        EditorGUIUtility.labelWidth = 0;
                    }
                }
            }, ShowSceneSystem_Editor_PreferenceKey);

            RenderFoldout(ref showManagerProperties, "Manager Scene Settings", () =>
            {
                using (new EditorGUI.IndentLevelScope())
                {
                    EditorGUILayout.HelpBox(managerSceneContent, MessageType.Info);

                    // Disable the tag field since we're drawing manager scenes
                    SceneInfoDrawer.DrawTagProperty = false;
                    EditorGUILayout.PropertyField(useManagerScene);

                    if (useManagerScene.boolValue && profile.ManagerScene.IsEmpty && !Application.isPlaying)
                    {
                        EditorGUILayout.HelpBox("You haven't created a manager scene yet. Click the button below to create one.", MessageType.Warning);
                        var buttonRect = EditorGUI.IndentedRect(EditorGUILayout.GetControlRect(System.Array.Empty<GUILayoutOption>()));
                        if (GUI.Button(buttonRect, "Create Manager Scene", EditorStyles.miniButton))
                        {
                            // Create a new manager scene and add it to build settings
                            SceneInfo newManagerScene = EditorSceneUtils.CreateAndSaveScene("ManagerScene");
                            SerializedObjectUtils.SetStructValue<SceneInfo>(managerScene, newManagerScene);
                            EditorSceneUtils.AddSceneToBuildSettings(newManagerScene, EditorBuildSettings.scenes, EditorSceneUtils.BuildIndexTarget.First);
                        }
                        EditorGUILayout.Space();
                    }

                    if (useManagerScene.boolValue)
                    {
                        EditorGUILayout.PropertyField(managerScene, includeChildren: true);
                    }
                }
            }, ShowSceneSystem_Manager_PreferenceKey);

            RenderFoldout(ref showLightingProperties, "Lighting Scene Settings", () =>
            {
                using (new EditorGUI.IndentLevelScope())
                {
                    EditorGUILayout.HelpBox(lightingSceneContent, MessageType.Info);

                    EditorGUILayout.PropertyField(useLightingScene);

                    if (useLightingScene.boolValue && profile.NumLightingScenes < 1 && !Application.isPlaying)
                    {
                        EditorGUILayout.HelpBox("You haven't created a lighting scene yet. Click the button below to create one.", MessageType.Warning);
                        var buttonRect = EditorGUI.IndentedRect(EditorGUILayout.GetControlRect(System.Array.Empty<GUILayoutOption>()));
                        if (GUI.Button(buttonRect, "Create Lighting Scene", EditorStyles.miniButton))
                        {
                            // Create a new lighting scene and add it to build settings
                            SceneInfo newLightingScene = EditorSceneUtils.CreateAndSaveScene("LightingScene");
                            // Create an element in the array
                            lightingScenes.arraySize = 1;
                            serializedObject.ApplyModifiedProperties();
                            SerializedObjectUtils.SetStructValue<SceneInfo>(lightingScenes.GetArrayElementAtIndex(0), newLightingScene);
                            EditorSceneUtils.AddSceneToBuildSettings(newLightingScene, EditorBuildSettings.scenes, EditorSceneUtils.BuildIndexTarget.Last);
                        }
                        EditorGUILayout.Space();
                    }

                    if (useLightingScene.boolValue)
                    {
                        // Disable the tag field since we're drawing lighting scenes
                        SceneInfoDrawer.DrawTagProperty = false;

                        if (profile.NumLightingScenes > 0)
                        {
                            string[] lightingSceneNames = profile.LightingScenes.Select(l => l.Name).ToArray<string>();
                            defaultLightingSceneIndex.intValue = EditorGUILayout.Popup("Default Lighting Scene", defaultLightingSceneIndex.intValue, lightingSceneNames);
                        }

                        EditorGUILayout.PropertyField(lightingScenes, includeChildren: true);
                        EditorGUILayout.Space();

                        if (profile.NumLightingScenes > 0)
                        {
                            if (profile.EditorLightingCacheOutOfDate)
                            {
                                EditorGUILayout.HelpBox("Your cached lighting settings may be out of date. This could result in unexpected appearances at runtime.", MessageType.Warning);
                            }
                            if (InspectorUIUtility.RenderIndentedButton(new GUIContent("Update Cached Lighting Settings"), EditorStyles.miniButton))
                            {
                                profile.EditorLightingCacheUpdateRequested = true;
                            }
                        }
                        EditorGUILayout.Space();
                    }
                }
            }, ShowSceneSystem_Lighting_PreferenceKey);

            RenderFoldout(ref showContentProperties, "Content Scene Settings", () =>
            {
                using (new EditorGUI.IndentLevelScope())
                {
                    EditorGUILayout.HelpBox(contentSceneContent, MessageType.Info);

                    // Enable the tag field since we're drawing content scenes
                    SceneInfoDrawer.DrawTagProperty = true;
                    EditorGUILayout.PropertyField(contentScenes, includeChildren: true);
                }
            }, ShowSceneSystem_Content_PreferenceKey);

            serializedObject.ApplyModifiedProperties();

            // Keep this inspector perpetually refreshed
            EditorUtility.SetDirty(target);
        }

19 Source : MixedRealityStandardShaderGUI.cs
with Apache License 2.0
from abist-co-ltd

protected void RenderingOptions(MaterialEditor materialEditor, Material material)
        {
            EditorGUILayout.Space();
            GUILayout.Label(Styles.renderingOptionsreplacedle, EditorStyles.boldLabel);

            materialEditor.ShaderProperty(directionalLight, Styles.directionalLight);

            if (PropertyEnabled(directionalLight))
            {
                materialEditor.ShaderProperty(specularHighlights, Styles.specularHighlights, 2);
            }

            materialEditor.ShaderProperty(sphericalHarmonics, Styles.sphericalHarmonics);

            materialEditor.ShaderProperty(reflections, Styles.reflections);

            if (PropertyEnabled(reflections))
            {
                materialEditor.ShaderProperty(refraction, Styles.refraction, 2);

                if (PropertyEnabled(refraction))
                {
                    materialEditor.ShaderProperty(refractiveIndex, Styles.refractiveIndex, 4);
                }
            }

            materialEditor.ShaderProperty(rimLight, Styles.rimLight);

            if (PropertyEnabled(rimLight))
            {
                materialEditor.ShaderProperty(rimColor, Styles.rimColor, 2);
                materialEditor.ShaderProperty(rimPower, Styles.rimPower, 2);
            }

            materialEditor.ShaderProperty(vertexColors, Styles.vertexColors);

            materialEditor.ShaderProperty(vertexExtrusion, Styles.vertexExtrusion);

            if (PropertyEnabled(vertexExtrusion))
            {
                materialEditor.ShaderProperty(vertexExtrusionValue, Styles.vertexExtrusionValue, 2);
                materialEditor.ShaderProperty(vertexExtrusionSmoothNormals, Styles.vertexExtrusionSmoothNormals, 2);
            }

            if ((RenderingMode)renderingMode.floatValue != RenderingMode.Opaque &&
                (RenderingMode)renderingMode.floatValue != RenderingMode.Cutout)
            {
                materialEditor.ShaderProperty(blendedClippingWidth, Styles.blendedClippingWidth);
                GUILayout.Box(string.Format(Styles.propertiesComponentHelp, nameof(ClippingPrimitive), "other clipping"), EditorStyles.helpBox, Array.Empty<GUILayoutOption>());
            }

            materialEditor.ShaderProperty(clippingBorder, Styles.clippingBorder);

            if (PropertyEnabled(clippingBorder))
            {
                materialEditor.ShaderProperty(clippingBorderWidth, Styles.clippingBorderWidth, 2);
                materialEditor.ShaderProperty(clippingBorderColor, Styles.clippingBorderColor, 2);
                GUILayout.Box(string.Format(Styles.propertiesComponentHelp, nameof(ClippingPrimitive), "other clipping"), EditorStyles.helpBox, Array.Empty<GUILayoutOption>());
            }

            materialEditor.ShaderProperty(nearPlaneFade, Styles.nearPlaneFade);

            if (PropertyEnabled(nearPlaneFade))
            {
                materialEditor.ShaderProperty(nearLightFade, Styles.nearLightFade, 2);
                materialEditor.ShaderProperty(fadeBeginDistance, Styles.fadeBeginDistance, 2);
                materialEditor.ShaderProperty(fadeCompleteDistance, Styles.fadeCompleteDistance, 2);
                materialEditor.ShaderProperty(fadeMinValue, Styles.fadeMinValue, 2);
            }
        }

19 Source : BaseInputDeviceManager.cs
with Apache License 2.0
from abist-co-ltd

public virtual IMixedRealityController[] GetActiveControllers() => System.Array.Empty<IMixedRealityController>();

19 Source : BaseInputDeviceManager.cs
with Apache License 2.0
from abist-co-ltd

public override void Destroy()
        {
            DestroyPointerCache();

            // Loop through active pointers in scene, destroy all gameobjects and clear our tracking dictionary
            foreach (var pointer in activePointersToConfig.Keys)
            {
                var pointerComponent = pointer as MonoBehaviour;
                if (!UnityObjectExtensions.IsNull(pointerComponent))
                {
                    GameObjectExtensions.DestroyGameObject(pointerComponent.gameObject);
                }
            }

            pointerConfigurations = System.Array.Empty<PointerConfig>();
            activePointersToConfig.Clear();
        }

19 Source : BaseBoundarySystem.cs
with Apache License 2.0
from abist-co-ltd

private void CalculateBoundaryBounds()
        {
            // Reset the bounds
            Bounds = System.Array.Empty<Edge>();
            FloorHeight = null;
            RectangularBounds = null;

            // Get the boundary geometry.
            var boundaryGeometry = GetBoundaryGeometry();

            if (boundaryGeometry != null && boundaryGeometry.Count > 0)
            {
                // Get the boundary geometry.
                var boundaryEdges = new List<Edge>(0);

                // FloorHeight starts out as null. Use a suitably high value for the floor to ensure
                // that we do not accidentally set it too low.
                float floorHeight = float.MaxValue;

                for (int i = 0; i < boundaryGeometry.Count; i++)
                {
                    Vector3 pointA = boundaryGeometry[i];
                    Vector3 pointB = boundaryGeometry[(i + 1) % boundaryGeometry.Count];
                    boundaryEdges.Add(new Edge(pointA, pointB));

                    floorHeight = Mathf.Min(floorHeight, boundaryGeometry[i].y);
                }

                FloorHeight = floorHeight;
                Bounds = boundaryEdges.ToArray();
                CreateInscribedBounds();
            }
            else
            {
                Debug.LogWarning("Failed to calculate boundary bounds.");
            }
        }

19 Source : MixedRealityStandardShaderGUI.cs
with Apache License 2.0
from abist-co-ltd

protected void MainMapOptions(MaterialEditor materialEditor, Material material)
        {
            GUILayout.Label(Styles.primaryMapsreplacedle, EditorStyles.boldLabel);

            materialEditor.TexturePropertySingleLine(Styles.albedo, albedoMap, albedoColor);

            if (albedoMap.textureValue == null)
            {
                materialEditor.ShaderProperty(albedoreplacedignedAtRuntime, Styles.albedoreplacedignedAtRuntime, 2);
            }

            materialEditor.ShaderProperty(enableChannelMap, Styles.enableChannelMap);

            if (PropertyEnabled(enableChannelMap))
            {
                EditorGUI.indentLevel += 2;
                materialEditor.TexturePropertySingleLine(Styles.channelMap, channelMap);
                GUILayout.Box("Metallic (Red), Occlusion (Green), Emission (Blue), Smoothness (Alpha)", EditorStyles.helpBox, Array.Empty<GUILayoutOption>());
                EditorGUI.indentLevel -= 2;
            }

            if (!PropertyEnabled(enableChannelMap))
            {
                EditorGUI.indentLevel += 2;

                materialEditor.ShaderProperty(albedoAlphaMode, albedoAlphaMode.displayName);

                if ((RenderingMode)renderingMode.floatValue == RenderingMode.Cutout || 
                    (RenderingMode)renderingMode.floatValue == RenderingMode.Custom)
                {
                    materialEditor.ShaderProperty(alphaCutoff, Styles.alphaCutoff.text);
                }

                if ((AlbedoAlphaMode)albedoAlphaMode.floatValue != AlbedoAlphaMode.Metallic)
                {
                    materialEditor.ShaderProperty(metallic, Styles.metallic);
                }

                if ((AlbedoAlphaMode)albedoAlphaMode.floatValue != AlbedoAlphaMode.Smoothness)
                {
                    materialEditor.ShaderProperty(smoothness, Styles.smoothness);
                }

                SetupMaterialWithAlbedo(material, albedoMap, albedoAlphaMode, albedoreplacedignedAtRuntime);

                EditorGUI.indentLevel -= 2;
            }

            if (PropertyEnabled(directionalLight) ||
                PropertyEnabled(reflections) ||
                PropertyEnabled(rimLight) ||
                PropertyEnabled(environmentColoring))
            {
                materialEditor.ShaderProperty(enableNormalMap, Styles.enableNormalMap);

                if (PropertyEnabled(enableNormalMap))
                {
                    EditorGUI.indentLevel += 2;
                    materialEditor.TexturePropertySingleLine(Styles.normalMap, normalMap, normalMap.textureValue != null ? normalMapScale : null);
                    EditorGUI.indentLevel -= 2;
                }
            }

            materialEditor.ShaderProperty(enableEmission, Styles.enableEmission);

            if (PropertyEnabled(enableEmission))
            {
                materialEditor.ShaderProperty(emissiveColor, Styles.emissiveColor, 2);
            }

            materialEditor.ShaderProperty(enableTriplanarMapping, Styles.enableTriplanarMapping);

            if (PropertyEnabled(enableTriplanarMapping))
            {
                materialEditor.ShaderProperty(enableLocalSpaceTriplanarMapping, Styles.enableLocalSpaceTriplanarMapping, 2);
                materialEditor.ShaderProperty(triplanarMappingBlendSharpness, Styles.triplanarMappingBlendSharpness, 2);
            }

            EditorGUILayout.Space();
            materialEditor.TextureScaleOffsetProperty(albedoMap);
        }

19 Source : OpenVRRenderModel.cs
with Apache License 2.0
from abist-co-ltd

private IEnumerator SetModelAsync(string newRenderModelName)
        {
            if (string.IsNullOrEmpty(newRenderModelName))
            {
                yield break;
            }

            // Pre-load all render models before asking for the data to create meshes.
            CVRRenderModels renderModels = Headers.OpenVR.RenderModels;
            if (renderModels == null)
            {
                yield break;
            }

            // Gather names of render models to pre-load.
            string[] renderModelNames;

            uint count = renderModels.GetComponentCount(newRenderModelName);
            if (count > 0)
            {
                renderModelNames = new string[count];

                for (int componentIndex = 0; componentIndex < count; componentIndex++)
                {
                    uint capacity = renderModels.GetComponentName(newRenderModelName, (uint)componentIndex, null, 0);
                    if (capacity == 0)
                    {
                        continue;
                    }

                    var componentNameStringBuilder = new System.Text.StringBuilder((int)capacity);
                    if (renderModels.GetComponentName(newRenderModelName, (uint)componentIndex, componentNameStringBuilder, capacity) == 0)
                    {
                        continue;
                    }

                    string componentName = componentNameStringBuilder.ToString();

                    capacity = renderModels.GetComponentRenderModelName(newRenderModelName, componentName, null, 0);
                    if (capacity == 0)
                    {
                        continue;
                    }

                    var nameStringBuilder = new System.Text.StringBuilder((int)capacity);
                    if (renderModels.GetComponentRenderModelName(newRenderModelName, componentName, nameStringBuilder, capacity) == 0)
                    {
                        continue;
                    }

                    var s = nameStringBuilder.ToString();

                    // Only need to pre-load if not already cached.
                    if (!(models[s] is RenderModel model) || model.Mesh == null)
                    {
                        renderModelNames[componentIndex] = s;
                    }
                }
            }
            else
            {
                // Only need to pre-load if not already cached.
                if (!(models[newRenderModelName] is RenderModel model) || model.Mesh == null)
                {
                    renderModelNames = new string[] { newRenderModelName };
                }
                else
                {
                    renderModelNames = System.Array.Empty<string>();
                }
            }

            // Keep trying every 100ms until all components finish loading.
            while (true)
            {
                var loading = false;
                for (int renderModelNameIndex = 0; renderModelNameIndex < renderModelNames.Length; renderModelNameIndex++)
                {
                    if (string.IsNullOrEmpty(renderModelNames[renderModelNameIndex]))
                    {
                        continue;
                    }

                    var pRenderModel = System.IntPtr.Zero;

                    var error = renderModels.LoadRenderModel_Async(renderModelNames[renderModelNameIndex], ref pRenderModel);

                    if (error == EVRRenderModelError.Loading)
                    {
                        loading = true;
                    }
                    else if (error == EVRRenderModelError.None)
                    {
                        // Pre-load textures as well.
                        var renderModel = MarshalRenderModel(pRenderModel);

                        // Check the cache first.
                        var material = materials[renderModel.diffuseTextureId] as Material;
                        if (material == null || material.mainTexture == null)
                        {
                            var pDiffuseTexture = System.IntPtr.Zero;

                            error = renderModels.LoadTexture_Async(renderModel.diffuseTextureId, ref pDiffuseTexture);

                            if (error == EVRRenderModelError.Loading)
                            {
                                loading = true;
                            }
                        }
                    }
                }

                if (loading)
                {
                    yield return new WaitForSecondsRealtime(0.1f);
                }
                else
                {
                    break;
                }
            }

            SetModel(newRenderModelName);
            renderModelName = newRenderModelName;
        }

19 Source : MixedRealityProfileUtility.cs
with Apache License 2.0
from abist-co-ltd

public static IReadOnlyCollection<Type> GetProfileTypesForService(Type serviceType)
        {
            if (serviceType == null)
            {
                return Array.Empty<Type>();
            }

            Type[] types;
            if (!profileTypesForServiceCaches.TryGetValue(serviceType, out types))
            {
                HashSet<Type> allTypes = new HashSet<Type>();
                ScriptableObject[] allProfiles = GetProfilesOfType(typeof(BaseMixedRealityProfile));
                for (int i = 0; i < allProfiles.Length; i++)
                {
                    ScriptableObject profile = allProfiles[i];
                    if (IsProfileForService(profile.GetType(), serviceType))
                    {
                        allTypes.Add(profile.GetType());
                    }
                }
                types = allTypes.ToArray();
                profileTypesForServiceCaches.Add(serviceType, types);
            }

            return types;
        }

19 Source : MixedRealityStandardShaderGUI.cs
with Apache License 2.0
from abist-co-ltd

protected void FluentOptions(MaterialEditor materialEditor, Material material)
        {
            EditorGUILayout.Space();
            GUILayout.Label(Styles.fluentOptionsreplacedle, EditorStyles.boldLabel);
            RenderingMode mode = (RenderingMode)renderingMode.floatValue;
            CustomRenderingMode customMode = (CustomRenderingMode)customRenderingMode.floatValue;

            materialEditor.ShaderProperty(hoverLight, Styles.hoverLight);

            if (PropertyEnabled(hoverLight))
            {
                GUILayout.Box(string.Format(Styles.propertiesComponentHelp, nameof(HoverLight), Styles.hoverLight.text), EditorStyles.helpBox, Array.Empty<GUILayoutOption>());

                materialEditor.ShaderProperty(enableHoverColorOverride, Styles.enableHoverColorOverride, 2);

                if (PropertyEnabled(enableHoverColorOverride))
                {
                    materialEditor.ShaderProperty(hoverColorOverride, Styles.hoverColorOverride, 4);
                }
            }

            materialEditor.ShaderProperty(proximityLight, Styles.proximityLight);

            if (PropertyEnabled(proximityLight))
            {
                materialEditor.ShaderProperty(enableProximityLightColorOverride, Styles.enableProximityLightColorOverride, 2);

                if (PropertyEnabled(enableProximityLightColorOverride))
                {
                    materialEditor.ShaderProperty(proximityLightCenterColorOverride, Styles.proximityLightCenterColorOverride, 4);
                    materialEditor.ShaderProperty(proximityLightMiddleColorOverride, Styles.proximityLightMiddleColorOverride, 4);
                    materialEditor.ShaderProperty(proximityLightOuterColorOverride, Styles.proximityLightOuterColorOverride, 4);
                }

                materialEditor.ShaderProperty(proximityLightSubtractive, Styles.proximityLightSubtractive, 2);
                materialEditor.ShaderProperty(proximityLightTwoSided, Styles.proximityLightTwoSided, 2);
                GUILayout.Box(string.Format(Styles.propertiesComponentHelp, nameof(ProximityLight), Styles.proximityLight.text), EditorStyles.helpBox, Array.Empty<GUILayoutOption>());
            }

            materialEditor.ShaderProperty(borderLight, Styles.borderLight);

            if (PropertyEnabled(borderLight))
            {
                materialEditor.ShaderProperty(borderWidth, Styles.borderWidth, 2);

                materialEditor.ShaderProperty(borderMinValue, Styles.borderMinValue, 2);

                materialEditor.ShaderProperty(borderLightReplacesAlbedo, Styles.borderLightReplacesAlbedo, 2);
                
                if (PropertyEnabled(hoverLight) && PropertyEnabled(enableHoverColorOverride))
                {
                    materialEditor.ShaderProperty(borderLightUsesHoverColor, Styles.borderLightUsesHoverColor, 2);
                }

                if (mode == RenderingMode.Cutout || mode == RenderingMode.Fade || mode == RenderingMode.Transparent ||
                    (mode == RenderingMode.Custom && customMode == CustomRenderingMode.Cutout) ||
                    (mode == RenderingMode.Custom && customMode == CustomRenderingMode.Fade))
                {
                    materialEditor.ShaderProperty(borderLightOpaque, Styles.borderLightOpaque, 2);

                    if (PropertyEnabled(borderLightOpaque))
                    {
                        materialEditor.ShaderProperty(borderLightOpaqueAlpha, Styles.borderLightOpaqueAlpha, 4);
                    }
                }
            }

            if (PropertyEnabled(hoverLight) || PropertyEnabled(proximityLight) || PropertyEnabled(borderLight))
            {
                materialEditor.ShaderProperty(fluentLightIntensity, Styles.fluentLightIntensity);
            }

            materialEditor.ShaderProperty(roundCorners, Styles.roundCorners);

            if (PropertyEnabled(roundCorners))
            {
                materialEditor.ShaderProperty(independentCorners, Styles.independentCorners, 2);
                if (PropertyEnabled(independentCorners))
                {
                    materialEditor.ShaderProperty(roundCornersRadius, Styles.roundCornersRadius, 2);
                }
                else
                {
                    materialEditor.ShaderProperty(roundCornerRadius, Styles.roundCornerRadius, 2);
                }

                materialEditor.ShaderProperty(roundCornerMargin, Styles.roundCornerMargin, 2);
            }

            if (PropertyEnabled(roundCorners) || PropertyEnabled(borderLight))
            {
                materialEditor.ShaderProperty(edgeSmoothingValue, Styles.edgeSmoothingValue);
            }

            materialEditor.ShaderProperty(innerGlow, Styles.innerGlow);

            if (PropertyEnabled(innerGlow))
            {
                materialEditor.ShaderProperty(innerGlowColor, Styles.innerGlowColor, 2);
                materialEditor.ShaderProperty(innerGlowPower, Styles.innerGlowPower, 2);
            }

            materialEditor.ShaderProperty(iridescence, Styles.iridescence);

            if (PropertyEnabled(iridescence))
            {
                EditorGUI.indentLevel += 2;
                materialEditor.TexturePropertySingleLine(Styles.iridescentSpectrumMap, iridescentSpectrumMap);
                EditorGUI.indentLevel -= 2;
                materialEditor.ShaderProperty(iridescenceIntensity, Styles.iridescenceIntensity, 2);
                materialEditor.ShaderProperty(iridescenceThreshold, Styles.iridescenceThreshold, 2);
                materialEditor.ShaderProperty(iridescenceAngle, Styles.iridescenceAngle, 2);
            }

            materialEditor.ShaderProperty(environmentColoring, Styles.environmentColoring);

            if (PropertyEnabled(environmentColoring))
            {
                materialEditor.ShaderProperty(environmentColorThreshold, Styles.environmentColorThreshold, 2);
                materialEditor.ShaderProperty(environmentColorIntensity, Styles.environmentColorIntensity, 2);
                materialEditor.ShaderProperty(environmentColorX, Styles.environmentColorX, 2);
                materialEditor.ShaderProperty(environmentColorY, Styles.environmentColorY, 2);
                materialEditor.ShaderProperty(environmentColorZ, Styles.environmentColorZ, 2);
            }
        }

19 Source : Theme.cs
with Apache License 2.0
from abist-co-ltd

[System.Obsolete("Use States.StateList instead")]
        public State[] GetStates()
        {
            if (States != null)
            {
                return States.StateList.ToArray();
            }

            return Array.Empty<State>();
        }

19 Source : SpeechInputHandlerInspector.cs
with Apache License 2.0
from abist-co-ltd

private void ShowList(SerializedProperty list)
        {
            using (new EditorGUI.IndentLevelScope())
            {
                // remove the keywords already replacedigned from the registered list
                var handler = (SpeechInputHandler)target;
                var availableKeywords = System.Array.Empty<string>();

                if (handler.Keywords != null && distinctRegisteredKeywords != null)
                {
                    availableKeywords = distinctRegisteredKeywords.Except(handler.Keywords.Select(keywordAndResponse => keywordAndResponse.Keyword)).ToArray();
                }

                // keyword rows
                for (int index = 0; index < list.arraySize; index++)
                {
                    // the element
                    SerializedProperty speechCommandProperty = list.GetArrayElementAtIndex(index);
                    GUILayout.BeginHorizontal();
                    bool elementExpanded = EditorGUILayout.PropertyField(speechCommandProperty);
                    GUILayout.FlexibleSpace();
                    // the remove element button
                    bool elementRemoved = GUILayout.Button(RemoveButtonContent, EditorStyles.miniButton, MiniButtonWidth);

                    GUILayout.EndHorizontal();

                    if (elementRemoved)
                    {
                        list.DeleteArrayElementAtIndex(index);

                        if (index == list.arraySize)
                        {
                            EditorGUI.indentLevel--;
                            return;
                        }
                    }

                    SerializedProperty keywordProperty = speechCommandProperty.FindPropertyRelative("keyword");

                    bool invalidKeyword = true;
                    if (distinctRegisteredKeywords != null)
                    {
                        foreach (string keyword in distinctRegisteredKeywords)
                        {
                            if (keyword == keywordProperty.stringValue)
                            {
                                invalidKeyword = false;
                                break;
                            }
                        }
                    }

                    if (invalidKeyword)
                    {
                        EditorGUILayout.HelpBox("Registered keyword is not recognized in the speech command profile!", MessageType.Error);
                    }

                    if (!elementRemoved && elementExpanded)
                    {
                        Rect position = EditorGUILayout.GetControlRect();
                        using (new EditorGUI.PropertyScope(position, KeywordContent, keywordProperty))
                        {
                            string[] keywords = availableKeywords.Concat(new[] { keywordProperty.stringValue }).OrderBy(keyword => keyword).ToArray();
                            int previousSelection = ArrayUtility.IndexOf(keywords, keywordProperty.stringValue);
                            int currentSelection = EditorGUILayout.Popup(KeywordContent, previousSelection, keywords);

                            if (currentSelection != previousSelection)
                            {
                                keywordProperty.stringValue = keywords[currentSelection];
                            }
                        }

                        SerializedProperty responseProperty = speechCommandProperty.FindPropertyRelative("response");
                        EditorGUILayout.PropertyField(responseProperty, true);
                    }
                }

                // add button row
                using (new EditorGUILayout.HorizontalScope())
                {
                    GUILayout.FlexibleSpace();

                    // the add element button
                    if (GUILayout.Button(AddButtonContent, EditorStyles.miniButton, MiniButtonWidth))
                    {
                        var index = list.arraySize;
                        list.InsertArrayElementAtIndex(index);
                        var elementProperty = list.GetArrayElementAtIndex(index);
                        SerializedProperty keywordProperty = elementProperty.FindPropertyRelative("keyword");
                        keywordProperty.stringValue = string.Empty;
                    }
                }
            }
        }

19 Source : MeshCursor.cs
with Apache License 2.0
from abist-co-ltd

protected override void OnEnable()
        {
            if (CursorStateData == null)
            {
                CursorStateData = Array.Empty<MeshCursorDatum>();
            }

            if (TargetRenderer == null)
            {
                TargetRenderer = GetComponentInChildren<MeshRenderer>();
            }

            base.OnEnable();
        }

19 Source : SpriteCursor.cs
with Apache License 2.0
from abist-co-ltd

protected override void OnEnable()
        {
            if (CursorStateData == null)
            {
                CursorStateData = Array.Empty<SpriteCursorDatum>();
            }

            if (TargetRenderer == null)
            {
                TargetRenderer = GetComponentInChildren<SpriteRenderer>();
            }

            base.OnEnable();
        }

19 Source : GuidGenerator.cs
with MIT License
from abock

public IEnumerable<string> Generate(
            GuidEncoding encoding,
            GuidFormat format,
            IEnumerable<string> args = null)
        {
            var guid = GenerateGuid(args ?? Array.Empty<string>());

            if (encoding == GuidEncoding.MixedEndian)
                guid = ToMixedEndian(guid);

            var guidString = FormatGuid(format, guid);

            switch (format)
            {
                case GuidFormat.Base64:
                case GuidFormat.Short:
                    yield return guidString;
                    break;
                default:
                    if (uppercase)
                        yield return guidString.ToUpperInvariant();
                    else
                        yield return guidString;
                    break;
            }
        }

19 Source : FSBuilder.cs
with Apache License 2.0
from acblog

public static void EnsureFileExists(string path, bool isExists = true, byte[]? initialData = null)
        {
            if (isExists)
            {
                if (!File.Exists(path))
                {
                    var par = Path.GetDirectoryName(path);
                    if (!string.IsNullOrWhiteSpace(par))
                        EnsureDirectoryExists(par);
                    File.WriteAllBytes(path, initialData ?? Array.Empty<byte>());
                }
            }
            else
            {
                if (File.Exists(path))
                {
                    File.Delete(path);
                }
            }
        }

19 Source : PostFSRepo.cs
with Apache License 2.0
from acblog

public PostMetadata GetDefaultMetadata(string id)
        {
            string path = GetPath(id);
            PostMetadata metadata = new PostMetadata
            {
                id = id,
                creationTime = System.IO.File.GetCreationTime(path).ToString(),
                modificationTime = System.IO.File.GetLastWriteTime(path).ToString()
            };
            {
                var relpath = Path.GetDirectoryName(id)?.Replace("\\", "/");
                var items = relpath?.Split("/", StringSplitOptions.RemoveEmptyEntries);
                metadata.category = items ?? Array.Empty<string>();
            }
            return metadata;
        }

19 Source : Program_DbUpdates.cs
with GNU Affero General Public License v3.0
from ACEmulator

private static void PatchDatabase(string dbType, string host, uint port, string username, string preplacedword, string database)
        {
            var updatesPath = $"DatabaseSetupScripts{Path.DirectorySeparatorChar}Updates{Path.DirectorySeparatorChar}{dbType}";
            var updatesFile = $"{updatesPath}{Path.DirectorySeparatorChar}applied_updates.txt";
            var appliedUpdates = Array.Empty<string>();

            var containerUpdatesFile = $"/ace/Config/{dbType}_applied_updates.txt";
            if (IsRunningInContainer && File.Exists(containerUpdatesFile))
                File.Copy(containerUpdatesFile, updatesFile, true);

            if (File.Exists(updatesFile))
                appliedUpdates = File.ReadAllLines(updatesFile);

            Console.WriteLine($"Searching for {dbType} update SQL scripts .... ");
            foreach (var file in new DirectoryInfo(updatesPath).GetFiles("*.sql").OrderBy(f => f.Name))
            {
                if (appliedUpdates.Contains(file.Name))
                    continue;

                Console.Write($"Found {file.Name} .... ");
                var sqlDBFile = File.ReadAllText(file.FullName);
                var sqlConnect = new MySql.Data.MySqlClient.MySqlConnection($"server={host};port={port};user={username};preplacedword={preplacedword};database={database};DefaultCommandTimeout=120");
                switch (dbType)
                {
                    case "Authentication":
                        sqlDBFile = sqlDBFile.Replace("ace_auth", database);
                        break;
                    case "Shard":
                        sqlDBFile = sqlDBFile.Replace("ace_shard", database);
                        break;
                    case "World":
                        sqlDBFile = sqlDBFile.Replace("ace_world", database);
                        break;
                }
                var script = new MySql.Data.MySqlClient.MySqlScript(sqlConnect, sqlDBFile);

                Console.Write($"Importing into {database} database on SQL server at {host}:{port} .... ");
                try
                {
                    script.StatementExecuted += new MySql.Data.MySqlClient.MySqlStatementExecutedEventHandler(OnStatementExecutedOutputDot);
                    var count = script.Execute();
                    //Console.Write($" {count} database records affected ....");
                    Console.WriteLine(" complete!");
                }
                catch (MySql.Data.MySqlClient.MySqlException ex)
                {
                    Console.WriteLine($" error!");
                    Console.WriteLine($" Unable to apply patch due to following exception: {ex}");
                }
                File.AppendAllText(updatesFile, file.Name + Environment.NewLine);
            }

            if (IsRunningInContainer && File.Exists(updatesFile))
                File.Copy(updatesFile, containerUpdatesFile, true);

            Console.WriteLine($"{dbType} update SQL scripts import complete!");
        }

19 Source : TransactionApiClient.cs
with Apache License 2.0
from Actify-Inc

public virtual async Task<StreamTransactionResponse> CommitTransaction(string transactionId)
        {
            string completeCommitTransactionPath = string.Format(_streamTransactionApiPath, transactionId);
            using (var response = await _client.PutAsync(completeCommitTransactionPath, Array.Empty<byte>()).ConfigureAwait(false))
            {
                var stream = await response.Content.ReadreplacedtreamAsync().ConfigureAwait(false);
                if (response.IsSuccessStatusCode)
                {
                    return DeserializeJsonFromStream<StreamTransactionResponse>(stream);
                }

                var error = DeserializeJsonFromStream<ApiErrorResponse>(stream);
                throw new ApiErrorException(error);
            }
        }

19 Source : ExecutionContext.cs
with MIT License
from actions

public void AddMatchers(IssueMatchersConfig config)
        {
            var root = Root;

            // Lock
            lock (root._matchersLock)
            {
                var newMatchers = new List<IssueMatcherConfig>();

                // Prepend
                var newOwners = new HashSet<string>(StringComparer.OrdinalIgnoreCase);
                foreach (var matcher in config.Matchers)
                {
                    newOwners.Add(matcher.Owner);
                    newMatchers.Add(matcher);
                }

                // Add existing non-matching
                var existingMatchers = root._matchers ?? Array.Empty<IssueMatcherConfig>();
                newMatchers.AddRange(existingMatchers.Where(x => !newOwners.Contains(x.Owner)));

                // Store
                root._matchers = newMatchers.ToArray();

                // Fire events
                foreach (var matcher in config.Matchers)
                {
                    root._onMatcherChanged(null, new MatcherChangedEventArgs(matcher));
                }

                // Output
                var owners = config.Matchers.Select(x => $"'{x.Owner}'");
                var joinedOwners = string.Join(", ", owners);
                // todo: loc
                this.Debug($"Added matchers: {joinedOwners}. Problem matchers scan action output for known warning or error strings and report these inline.");
            }
        }

19 Source : ExecutionContext.cs
with MIT License
from actions

public void RemoveMatchers(IEnumerable<string> owners)
        {
            var root = Root;
            var distinctOwners = new HashSet<string>(owners, StringComparer.OrdinalIgnoreCase);
            var removedMatchers = new List<IssueMatcherConfig>();
            var newMatchers = new List<IssueMatcherConfig>();

            // Lock
            lock (root._matchersLock)
            {
                // Remove
                var existingMatchers = root._matchers ?? Array.Empty<IssueMatcherConfig>();
                foreach (var matcher in existingMatchers)
                {
                    if (distinctOwners.Contains(matcher.Owner))
                    {
                        removedMatchers.Add(matcher);
                    }
                    else
                    {
                        newMatchers.Add(matcher);
                    }
                }

                // Store
                root._matchers = newMatchers.ToArray();

                // Fire events
                foreach (var removedMatcher in removedMatchers)
                {
                    root._onMatcherChanged(null, new MatcherChangedEventArgs(new IssueMatcherConfig { Owner = removedMatcher.Owner }));
                }

                // Output
                owners = removedMatchers.Select(x => $"'{x.Owner}'");
                var joinedOwners = string.Join(", ", owners);
                // todo: loc
                this.Debug($"Removed matchers: {joinedOwners}");
            }
        }

19 Source : ExecutionContext.cs
with MIT License
from actions

public IEnumerable<IssueMatcherConfig> GetMatchers()
        {
            // Lock not required since the list is immutable
            return Root._matchers ?? Array.Empty<IssueMatcherConfig>();
        }

19 Source : AcuminatorVsixPackageLoader.cs
with GNU General Public License v3.0
from Acumatica

private static void SearchForVsixAndEnsureItIsLoadedPackageLoaded()
		{
			var vsixreplacedembly = AppDomain.CurrentDomain.Getreplacedemblies()
													  .FirstOrDefault(a => a.GetName().Name == SharedConstants.PackageName);
			if (vsixreplacedembly == null)
				return;

			var areplacedinatorPackageType = vsixreplacedembly.GetExportedTypes().FirstOrDefault(t => t.Name == VsixPackageType);

			if (areplacedinatorPackageType == null)
				return;

			var dummyServiceCaller = areplacedinatorPackageType.GetMethod(ForceLoadPackageAsync, BindingFlags.Static | BindingFlags.Public);

			if (dummyServiceCaller == null)
				return;

			object loadTask = null;

			try
			{
				loadTask = dummyServiceCaller.Invoke(null, Array.Empty<object>());
			}
			catch
			{
				return;
			}

			if (loadTask is Task task)
			{
				const int defaultTimeoutSeconds = 20;
				task.Wait(TimeSpan.FromSeconds(defaultTimeoutSeconds));
			}
		}

19 Source : Helper.cs
with Apache License 2.0
from adamralph

public static Target CreateTarget(string name, Action action) => CreateTarget(name, Array.Empty<string>(), action);

19 Source : Helper.cs
with Apache License 2.0
from adamralph

public static Target CreateTarget<TInput>(string name, IEnumerable<TInput> forEach, Action<TInput> action) =>
            new ActionTarget<TInput>(name, "", Array.Empty<string>(), forEach, action.ToAsync());

19 Source : CompilationUnitVisitor.cs
with MIT License
from adrianoc

public override void VisitDelegateDeclaration(DelegateDeclarationSyntax node)
        {
            Context.WriteNewLine();
            Context.WriteComment($"Delegate: {node.Identifier.Text}");
            var typeVar = Context.Naming.Delegate(node);
            var accessibility = ModifiersToCecil(node.Modifiers, "TypeAttributes", "Private");

            var typeDef = CecilDefinitionsFactory.Type(
                Context, 
                typeVar, 
                node.Identifier.ValueText, 
                 CecilDefinitionsFactory.DefaultTypeAttributeFor(node.Kind(), false).AppendModifier(accessibility), 
                Context.TypeResolver.Bcl.System.MulticastDelegate, 
                false,
                Array.Empty<string>(),
                node.TypeParameterList, 
                "IsAnsiClreplaced = true");
            
            AddCecilExpressions(typeDef);
            HandleAttributesInMemberDeclaration(node.AttributeLists, typeVar);

            using (Context.DefinitionVariables.WithCurrent("", node.Identifier.ValueText, MemberKind.Type, typeVar))
            {
                var ctorLocalVar = Context.Naming.Delegate(node);
                
                // Delegate ctor
                AddCecilExpression(CecilDefinitionsFactory.Constructor(Context, ctorLocalVar, node.Identifier.Text, "MethodAttributes.FamANDreplacedem | MethodAttributes.Family",
                    new[] {"System.Object", "System.IntPtr"}, "IsRuntime = true"));
                AddCecilExpression($"{ctorLocalVar}.Parameters.Add(new ParameterDefinition({Context.TypeResolver.Bcl.System.Object}));");
                AddCecilExpression($"{ctorLocalVar}.Parameters.Add(new ParameterDefinition({Context.TypeResolver.Bcl.System.IntPtr}));");
                AddCecilExpression($"{typeVar}.Methods.Add({ctorLocalVar});");

                AddDelegateMethod(
                    typeVar, 
                    "Invoke", 
                    ResolveType(node.ReturnType), 
                    node.ParameterList.Parameters,
                    (methodVar, param) => CecilDefinitionsFactory.Parameter(param, Context.SemanticModel, methodVar, Context.Naming.Parameter(param) , ResolveType(param.Type)));

                // BeginInvoke() method
                var methodName = "BeginInvoke";
                var beginInvokeMethodVar = Context.Naming.SyntheticVariable(methodName, ElementKind.Method);
                AddCecilExpression(
                    $@"var {beginInvokeMethodVar} = new MethodDefinition(""{methodName}"", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, {Context.TypeResolver.Bcl.System.IAsyncResult})
					{{
						HasThis = true,
						IsRuntime = true,
					}};");

                foreach (var param in node.ParameterList.Parameters)
                {
                    var paramExps = CecilDefinitionsFactory.Parameter(param, Context.SemanticModel, beginInvokeMethodVar, Context.Naming.Parameter(param), ResolveType(param.Type));
                    AddCecilExpressions(paramExps);
                }

                AddCecilExpression($"{beginInvokeMethodVar}.Parameters.Add(new ParameterDefinition({Context.TypeResolver.Bcl.System.AsyncCallback}));");
                AddCecilExpression($"{beginInvokeMethodVar}.Parameters.Add(new ParameterDefinition({Context.TypeResolver.Bcl.System.Object}));");
                AddCecilExpression($"{typeVar}.Methods.Add({beginInvokeMethodVar});");

                // EndInvoke() method
                var endInvokeMethodVar =  Context.Naming.SyntheticVariable("EndInvoke", ElementKind.Method);

                var endInvokeExps = CecilDefinitionsFactory.Method(
                    Context,
                    endInvokeMethodVar,
                    "EndInvoke",
                    "MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual",
                    Context.GetTypeInfo(node.ReturnType).Type,
                    false,
                    Array.Empty<TypeParameterSyntax>()
                );

                endInvokeExps = endInvokeExps.Concat(new[]
                {
                    $"{endInvokeMethodVar}.HasThis = true;",
                    $"{endInvokeMethodVar}.IsRuntime = true;",
                });
                
                var endInvokeParamExps = CecilDefinitionsFactory.Parameter(
                    "ar", 
                    RefKind.None,
                    false,
                    endInvokeMethodVar,
                    Context.Naming.Parameter("ar", node.Identifier.Text),
                    Context.TypeResolver.Bcl.System.IAsyncResult);

                AddCecilExpressions(endInvokeExps);
                AddCecilExpressions(endInvokeParamExps);
                AddCecilExpression($"{typeVar}.Methods.Add({endInvokeMethodVar});");
               
                base.VisitDelegateDeclaration(node);
            }

            void AddDelegateMethod(string typeLocalVar, string methodName, string returnTypeName, in SeparatedSyntaxList<ParameterSyntax> parameters, Func<string, ParameterSyntax, IEnumerable<string>> parameterHandler)
            {
                var methodLocalVar = Context.Naming.SyntheticVariable(methodName, ElementKind.Method);
                AddCecilExpression(
                    $@"var {methodLocalVar} = new MethodDefinition(""{methodName}"", MethodAttributes.Public | MethodAttributes.HideBySig | MethodAttributes.NewSlot | MethodAttributes.Virtual, {returnTypeName})
				{{
					HasThis = true,
					IsRuntime = true,
				}};");

                foreach (var param in parameters)
                {
                    AddCecilExpressions(parameterHandler(methodLocalVar, param));
                }

                AddCecilExpression($"{typeLocalVar}.Methods.Add({methodLocalVar});");
            }
        }

19 Source : MethodDeclarationVisitor.cs
with MIT License
from adrianoc

protected void ProcessMethodDeclaration<T>(T node, string variableName, string simpleName, string fqName, ITypeSymbol returnType, bool refReturn, Action<string> runWithCurrent, IList<TypeParameterSyntax> typeParameters = null) where T : BaseMethodDeclarationSyntax
        {
            using var _ = LineInformationTracker.Track(Context, node);
            var declaringTypeName = DeclaringTypeFrom(node);
            using (Context.DefinitionVariables.EnterScope())
            {
                typeParameters ??= Array.Empty<TypeParameterSyntax>();

                var methodVar = AddOrUpdateMethodDefinition(node, variableName, fqName, node.Modifiers.MethodModifiersToCecil((targetEnum, modifiers, defaultAccessibility) => ModifiersToCecil(modifiers, targetEnum, defaultAccessibility), GetSpecificModifiers(), DeclaredSymbolFor(node)), returnType, refReturn, typeParameters);
                AddCecilExpression("{0}.Methods.Add({1});", Context.DefinitionVariables.GetLastOf(MemberKind.Type).VariableName, methodVar);

                HandleAttributesInMemberDeclaration(node.AttributeLists, TargetDoesNotMatch, SyntaxKind.ReturnKeyword, methodVar); // Normal method attrs.
                HandleAttributesInMemberDeclaration(node.AttributeLists, TargetMatches, SyntaxKind.ReturnKeyword, $"{methodVar}.MethodReturnType"); // [return:Attr]

                if (node.Modifiers.IndexOf(SyntaxKind.ExternKeyword) == -1)
                {
                    var isAbstract = DeclaredSymbolFor(node).IsAbstract;
                    if (!isAbstract)
                    {
                        ilVar = Context.Naming.ILProcessor(simpleName, declaringTypeName);
                        AddCecilExpression($"{methodVar}.Body.InitLocals = true;");
                        AddCecilExpression($"var {ilVar} = {methodVar}.Body.GetILProcessor();");
                    }

                    WithCurrentMethod(declaringTypeName, methodVar, fqName, node.ParameterList.Parameters.Select(p => Context.GetTypeInfo(p.Type).Type.Name).ToArray(), runWithCurrent);
                    if (!isAbstract && !node.DescendantNodes().Any(n => n.IsKind(SyntaxKind.ReturnStatement)))
                    {
                        AddCilInstruction(ilVar, OpCodes.Ret);
                    }
                }
                else
                {
                    Context.DefinitionVariables.RegisterMethod(declaringTypeName, fqName, node.ParameterList.Parameters.Select(p => Context.GetTypeInfo(p.Type).Type.Name).ToArray(), methodVar);
                }
            }
        }

See More Examples