content stringlengths 5 1.04M | avg_line_length float64 1.75 12.9k | max_line_length int64 2 244k | alphanum_fraction float64 0 0.98 | licenses list | repository_name stringlengths 7 92 | path stringlengths 3 249 | size int64 5 1.04M | lang stringclasses 2 values |
|---|---|---|---|---|---|---|---|---|
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc.Abstractions;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Routing;
using Microsoft.AspNetCore.Routing.Matching;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Microsoft.AspNetCore.Mvc.Routing
{
public class DynamicControllerEndpointMatcherPolicyTest
{
public DynamicControllerEndpointMatcherPolicyTest()
{
var dataSourceKey = new ControllerEndpointDataSourceIdMetadata(1);
var actions = new ActionDescriptor[]
{
new ControllerActionDescriptor()
{
RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["action"] = "Index",
["controller"] = "Home",
},
},
new ControllerActionDescriptor()
{
RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["action"] = "About",
["controller"] = "Home",
},
},
new ControllerActionDescriptor()
{
RouteValues = new Dictionary<string, string>(StringComparer.OrdinalIgnoreCase)
{
["action"] = "Index",
["controller"] = "Blog",
},
}
};
ControllerEndpoints = new[]
{
new Endpoint(
_ => Task.CompletedTask,
new EndpointMetadataCollection(actions[0]),
"Test1"
),
new Endpoint(
_ => Task.CompletedTask,
new EndpointMetadataCollection(actions[1]),
"Test2"
),
new Endpoint(
_ => Task.CompletedTask,
new EndpointMetadataCollection(actions[2]),
"Test3"
),
};
DynamicEndpoint = new Endpoint(
_ => Task.CompletedTask,
new EndpointMetadataCollection(
new object[]
{
new DynamicControllerRouteValueTransformerMetadata(
typeof(CustomTransformer),
State
),
dataSourceKey
}
),
"dynamic"
);
DataSource = new DefaultEndpointDataSource(ControllerEndpoints);
SelectorCache = new TestDynamicControllerEndpointSelectorCache(DataSource, 1);
var services = new ServiceCollection();
services.AddRouting();
services.AddTransient<CustomTransformer>(
s =>
{
var transformer = new CustomTransformer();
transformer.Transform = (c, values, state) => Transform(c, values, state);
transformer.Filter = (c, values, state, candidates) =>
Filter(c, values, state, candidates);
return transformer;
}
);
Services = services.BuildServiceProvider();
Comparer = Services.GetRequiredService<EndpointMetadataComparer>();
}
private EndpointMetadataComparer Comparer { get; }
private DefaultEndpointDataSource DataSource { get; }
private Endpoint[] ControllerEndpoints { get; }
private Endpoint DynamicEndpoint { get; }
private DynamicControllerEndpointSelectorCache SelectorCache { get; }
private IServiceProvider Services { get; }
private Func<
HttpContext,
RouteValueDictionary,
object,
ValueTask<RouteValueDictionary>
> Transform { get; set; }
private Func<
HttpContext,
RouteValueDictionary,
object,
IReadOnlyList<Endpoint>,
ValueTask<IReadOnlyList<Endpoint>>
> Filter { get; set; } = (_, __, ___, e) => new ValueTask<IReadOnlyList<Endpoint>>(e);
private object State { get; } = new object();
[Fact]
public async Task ApplyAsync_NoMatch()
{
// Arrange
var policy = new DynamicControllerEndpointMatcherPolicy(SelectorCache, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[] { null, };
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
candidates.SetValidity(0, false);
Transform = (c, values, state) =>
{
throw new InvalidOperationException();
};
var httpContext = new DefaultHttpContext() { RequestServices = Services, };
// Act
await policy.ApplyAsync(httpContext, candidates);
// Assert
Assert.False(candidates.IsValidCandidate(0));
}
[Fact]
public async Task ApplyAsync_HasMatchNoEndpointFound()
{
// Arrange
var policy = new DynamicControllerEndpointMatcherPolicy(SelectorCache, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[] { null, };
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
Transform = (c, values, state) =>
{
return new ValueTask<RouteValueDictionary>(new RouteValueDictionary());
};
var httpContext = new DefaultHttpContext() { RequestServices = Services, };
// Act
await policy.ApplyAsync(httpContext, candidates);
// Assert
Assert.Null(candidates[0].Endpoint);
Assert.Null(candidates[0].Values);
Assert.False(candidates.IsValidCandidate(0));
}
[Fact]
public async Task ApplyAsync_HasMatchFindsEndpoint_WithoutRouteValues()
{
// Arrange
var policy = new DynamicControllerEndpointMatcherPolicy(SelectorCache, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[] { null, };
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
Transform = (c, values, state) =>
{
return new ValueTask<RouteValueDictionary>(
new RouteValueDictionary(new { controller = "Home", action = "Index", })
);
};
var httpContext = new DefaultHttpContext() { RequestServices = Services, };
// Act
await policy.ApplyAsync(httpContext, candidates);
// Assert
Assert.Same(ControllerEndpoints[0], candidates[0].Endpoint);
Assert.Collection(
candidates[0].Values.OrderBy(kvp => kvp.Key),
kvp =>
{
Assert.Equal("action", kvp.Key);
Assert.Equal("Index", kvp.Value);
},
kvp =>
{
Assert.Equal("controller", kvp.Key);
Assert.Equal("Home", kvp.Value);
}
);
Assert.True(candidates.IsValidCandidate(0));
}
[Fact]
public async Task ApplyAsync_ThrowsForTransformerWithInvalidLifetime()
{
// Arrange
var policy = new DynamicControllerEndpointMatcherPolicy(SelectorCache, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[]
{
new RouteValueDictionary(new { slug = "test", }),
};
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
Transform = (c, values, state) =>
{
return new ValueTask<RouteValueDictionary>(
new RouteValueDictionary(new { controller = "Home", action = "Index", state })
);
};
var httpContext = new DefaultHttpContext()
{
RequestServices = new ServiceCollection()
.AddScoped(sp => new CustomTransformer { State = "Invalid" })
.BuildServiceProvider(),
};
// Act & Assert
await Assert.ThrowsAsync<InvalidOperationException>(
() => policy.ApplyAsync(httpContext, candidates)
);
}
[Fact]
public async Task ApplyAsync_HasMatchFindsEndpoint_WithRouteValues()
{
// Arrange
var policy = new DynamicControllerEndpointMatcherPolicy(SelectorCache, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[]
{
new RouteValueDictionary(new { slug = "test", }),
};
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
Transform = (c, values, state) =>
{
return new ValueTask<RouteValueDictionary>(
new RouteValueDictionary(new { controller = "Home", action = "Index", state })
);
};
var httpContext = new DefaultHttpContext() { RequestServices = Services, };
// Act
await policy.ApplyAsync(httpContext, candidates);
// Assert
Assert.Same(ControllerEndpoints[0], candidates[0].Endpoint);
Assert.Collection(
candidates[0].Values.OrderBy(kvp => kvp.Key),
kvp =>
{
Assert.Equal("action", kvp.Key);
Assert.Equal("Index", kvp.Value);
},
kvp =>
{
Assert.Equal("controller", kvp.Key);
Assert.Equal("Home", kvp.Value);
},
kvp =>
{
Assert.Equal("slug", kvp.Key);
Assert.Equal("test", kvp.Value);
},
kvp =>
{
Assert.Equal("state", kvp.Key);
Assert.Same(State, kvp.Value);
}
);
Assert.True(candidates.IsValidCandidate(0));
}
[Fact]
public async Task ApplyAsync_CanDiscardFoundEndpoints()
{
// Arrange
var policy = new DynamicControllerEndpointMatcherPolicy(SelectorCache, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[]
{
new RouteValueDictionary(new { slug = "test", }),
};
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
Transform = (c, values, state) =>
{
return new ValueTask<RouteValueDictionary>(
new RouteValueDictionary(new { controller = "Home", action = "Index", state })
);
};
Filter = (c, values, state, endpoints) =>
{
return new ValueTask<IReadOnlyList<Endpoint>>(Array.Empty<Endpoint>());
};
var httpContext = new DefaultHttpContext() { RequestServices = Services, };
// Act
await policy.ApplyAsync(httpContext, candidates);
// Assert
Assert.False(candidates.IsValidCandidate(0));
}
[Fact]
public async Task ApplyAsync_CanReplaceFoundEndpoints()
{
// Arrange
var policy = new DynamicControllerEndpointMatcherPolicy(SelectorCache, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[]
{
new RouteValueDictionary(new { slug = "test", }),
};
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
Transform = (c, values, state) =>
{
return new ValueTask<RouteValueDictionary>(
new RouteValueDictionary(new { controller = "Home", action = "Index", state })
);
};
Filter = (c, values, state, endpoints) =>
new ValueTask<IReadOnlyList<Endpoint>>(
new[]
{
new Endpoint(
(ctx) => Task.CompletedTask,
new EndpointMetadataCollection(Array.Empty<object>()),
"ReplacedEndpoint"
)
}
);
var httpContext = new DefaultHttpContext() { RequestServices = Services, };
// Act
await policy.ApplyAsync(httpContext, candidates);
// Assert
Assert.Collection(
candidates[0].Values.OrderBy(kvp => kvp.Key),
kvp =>
{
Assert.Equal("action", kvp.Key);
Assert.Equal("Index", kvp.Value);
},
kvp =>
{
Assert.Equal("controller", kvp.Key);
Assert.Equal("Home", kvp.Value);
},
kvp =>
{
Assert.Equal("slug", kvp.Key);
Assert.Equal("test", kvp.Value);
},
kvp =>
{
Assert.Equal("state", kvp.Key);
Assert.Same(State, kvp.Value);
}
);
Assert.Equal("ReplacedEndpoint", candidates[0].Endpoint.DisplayName);
Assert.True(candidates.IsValidCandidate(0));
}
[Fact]
public async Task ApplyAsync_CanExpandTheListOfFoundEndpoints()
{
// Arrange
var policy = new DynamicControllerEndpointMatcherPolicy(SelectorCache, Comparer);
var endpoints = new[] { DynamicEndpoint, };
var values = new RouteValueDictionary[]
{
new RouteValueDictionary(new { slug = "test", }),
};
var scores = new[] { 0, };
var candidates = new CandidateSet(endpoints, values, scores);
Transform = (c, values, state) =>
{
return new ValueTask<RouteValueDictionary>(
new RouteValueDictionary(new { controller = "Home", action = "Index", state })
);
};
Filter = (c, values, state, endpoints) =>
new ValueTask<IReadOnlyList<Endpoint>>(
new[] { ControllerEndpoints[1], ControllerEndpoints[2] }
);
var httpContext = new DefaultHttpContext() { RequestServices = Services, };
// Act
await policy.ApplyAsync(httpContext, candidates);
// Assert
Assert.Equal(2, candidates.Count);
Assert.True(candidates.IsValidCandidate(0));
Assert.True(candidates.IsValidCandidate(1));
Assert.Same(ControllerEndpoints[1], candidates[0].Endpoint);
Assert.Same(ControllerEndpoints[2], candidates[1].Endpoint);
}
private class TestDynamicControllerEndpointSelectorCache
: DynamicControllerEndpointSelectorCache
{
public TestDynamicControllerEndpointSelectorCache(
EndpointDataSource dataSource,
int key
)
{
AddDataSource(dataSource, key);
}
}
private class CustomTransformer : DynamicRouteValueTransformer
{
public Func<
HttpContext,
RouteValueDictionary,
object,
ValueTask<RouteValueDictionary>
> Transform { get; set; }
public Func<
HttpContext,
RouteValueDictionary,
object,
IReadOnlyList<Endpoint>,
ValueTask<IReadOnlyList<Endpoint>>
> Filter { get; set; }
public override ValueTask<RouteValueDictionary> TransformAsync(
HttpContext httpContext,
RouteValueDictionary values
)
{
return Transform(httpContext, values, State);
}
public override ValueTask<IReadOnlyList<Endpoint>> FilterAsync(
HttpContext httpContext,
RouteValueDictionary values,
IReadOnlyList<Endpoint> endpoints
)
{
return Filter(httpContext, values, State, endpoints);
}
}
}
}
| 34.561404 | 111 | 0.504399 | [
"Apache-2.0"
] | belav/aspnetcore | src/Mvc/Mvc.Core/test/Routing/DynamicControllerEndpointMatcherPolicyTest.cs | 17,730 | C# |
using System.Linq;
using BoutiqueCommonXUnit.Data.Clothes;
using BoutiqueDTO.Infrastructure.Implementations.Converters.Clothes.SizeGroupTransfers;
using BoutiqueDTOXUnit.Infrastructure.Mocks.Converters;
using BoutiqueDTOXUnit.Infrastructure.Mocks.Converters.Clothes;
using Xunit;
namespace BoutiqueDTOXUnit.Infrastructure.Converters.Clothes.SizeGroupsTransfers
{
public class SizeGroupTransferConverterTest
{
/// <summary>
/// Преобразования модели базовых данных размеров одежды в трансферную модель
/// </summary>
[Fact]
public void SizeGroup_ToTransfer_FromTransfer()
{
var sizeGroup = SizeGroupData.SizeGroupDomains.First();
var sizeGroupTransferConverter = SizeGroupTransferConverterMock.SizeGroupTransferConverter;
var sizeGroupTransfer = sizeGroupTransferConverter.ToTransfer(sizeGroup);
var sizeGroupAfterConverter = sizeGroupTransferConverter.FromTransfer(sizeGroupTransfer);
Assert.True(sizeGroupAfterConverter.OkStatus);
Assert.True(sizeGroup.Equals(sizeGroupAfterConverter.Value));
}
}
} | 39.448276 | 103 | 0.751748 | [
"MIT"
] | rubilnik4/VeraBoutique | BoutiqueDTOXUnit/Infrastructure/Converters/Clothes/SizeGroupsTransfers/SizeGroupTransferConverterTest.cs | 1,211 | C# |
using System;
using OMeta;
using OMeta.Interfaces;
namespace OMeta.DB2
{
public class ClassFactory : IClassFactory
{
public static void Register()
{
InternalDriver.Register("DB2",
new InternalDriver
(typeof(ClassFactory)
, "Provider=IBMDADB2.1;Password=myPassword;User ID=myUser;Data Source=myDatasource;Persist Security Info=True"
, true));
}
public ClassFactory()
{
}
public ITables CreateTables()
{
return new DB2.DB2Tables();
}
public ITable CreateTable()
{
return new DB2.DB2Table();
}
public IColumn CreateColumn()
{
return new DB2.DB2Column();
}
public IColumns CreateColumns()
{
return new DB2.DB2Columns();
}
public IDatabase CreateDatabase()
{
return new DB2.DB2Database();
}
public IDatabases CreateDatabases()
{
return new DB2.DB2Databases();
}
public IProcedure CreateProcedure()
{
return new DB2.DB2Procedure();
}
public IProcedures CreateProcedures()
{
return new DB2.DB2Procedures();
}
public IView CreateView()
{
return new DB2.DB2View();
}
public IViews CreateViews()
{
return new DB2.DB2Views();
}
public IParameter CreateParameter()
{
return new DB2.DB2Parameter();
}
public IParameters CreateParameters()
{
return new DB2.DB2Parameters();
}
public IForeignKey CreateForeignKey()
{
return new DB2.DB2ForeignKey();
}
public IForeignKeys CreateForeignKeys()
{
return new DB2.DB2ForeignKeys();
}
public IIndex CreateIndex()
{
return new DB2.DB2Index();
}
public IIndexes CreateIndexes()
{
return new DB2.DB2Indexes();
}
public IDomain CreateDomain()
{
return new DB2Domain();
}
public IDomains CreateDomains()
{
return new DB2Domains();
}
public IResultColumn CreateResultColumn()
{
return new DB2.DB2ResultColumn();
}
public IResultColumns CreateResultColumns()
{
return new DB2.DB2ResultColumns();
}
public IProviderType CreateProviderType()
{
return new ProviderType();
}
public IProviderTypes CreateProviderTypes()
{
return new ProviderTypes();
}
public System.Data.IDbConnection CreateConnection()
{
return new System.Data.OleDb.OleDbConnection();
}
public void ChangeDatabase(System.Data.IDbConnection connection, string database)
{
connection.ChangeDatabase(database);
}
}
}
| 17.351724 | 126 | 0.647456 | [
"MIT"
] | kiler398/OMeta | src/OpenMetaData/DB2/ClassFactory.cs | 2,516 | C# |
using System;
using System.ServiceModel;
using System.Threading.Tasks;
namespace LinqToDB.Remote.Wcf
{
[ServiceBehavior(InstanceContextMode = InstanceContextMode.Single, ConcurrencyMode = ConcurrencyMode.Multiple)]
public class WcfLinqService : IWcfLinqService
{
private readonly ILinqService _linqService;
private readonly bool _transferInternalExceptionToClient;
public WcfLinqService(
ILinqService linqService,
bool transferInternalExceptionToClient
)
{
_linqService = linqService ?? throw new ArgumentNullException(nameof(linqService));
_transferInternalExceptionToClient = transferInternalExceptionToClient;
}
LinqServiceInfo IWcfLinqService.GetInfo(string? configuration)
{
try
{
return _linqService.GetInfo(configuration);
}
catch (Exception exception) when (_transferInternalExceptionToClient)
{
throw new FaultException(exception.ToString());
}
}
int IWcfLinqService.ExecuteBatch(string? configuration, string queryData)
{
try
{
return _linqService.ExecuteBatch(configuration, queryData);
}
catch (Exception exception) when (_transferInternalExceptionToClient)
{
throw new FaultException(exception.ToString());
}
}
int IWcfLinqService.ExecuteNonQuery(string? configuration, string queryData)
{
try
{
return _linqService.ExecuteNonQuery(configuration, queryData);
}
catch (Exception exception) when (_transferInternalExceptionToClient)
{
throw new FaultException(exception.ToString());
}
}
string IWcfLinqService.ExecuteReader(string? configuration, string queryData)
{
try
{
return _linqService.ExecuteReader(configuration, queryData);
}
catch (Exception exception) when (_transferInternalExceptionToClient)
{
throw new FaultException(exception.ToString());
}
}
string? IWcfLinqService.ExecuteScalar(string? configuration, string queryData)
{
try
{
return _linqService.ExecuteScalar(configuration, queryData);
}
catch (Exception exception) when (_transferInternalExceptionToClient)
{
throw new FaultException(exception.ToString());
}
}
async Task<LinqServiceInfo> IWcfLinqService.GetInfoAsync(string? configuration)
{
try
{
return await _linqService.GetInfoAsync(configuration)
.ConfigureAwait(Common.Configuration.ContinueOnCapturedContext); ;
}
catch (Exception exception) when (_transferInternalExceptionToClient)
{
throw new FaultException(exception.ToString());
}
}
async Task<int> IWcfLinqService.ExecuteBatchAsync(string? configuration, string queryData)
{
try
{
return await _linqService.ExecuteBatchAsync(configuration, queryData)
.ConfigureAwait(Common.Configuration.ContinueOnCapturedContext); ;
}
catch (Exception exception) when (_transferInternalExceptionToClient)
{
throw new FaultException(exception.ToString());
}
}
async Task<int> IWcfLinqService.ExecuteNonQueryAsync(string? configuration, string queryData)
{
try
{
return await _linqService.ExecuteNonQueryAsync(configuration, queryData)
.ConfigureAwait(Common.Configuration.ContinueOnCapturedContext); ;
}
catch (Exception exception) when (_transferInternalExceptionToClient)
{
throw new FaultException(exception.ToString());
}
}
async Task<string> IWcfLinqService.ExecuteReaderAsync(string? configuration, string queryData)
{
try
{
return await _linqService.ExecuteReaderAsync(configuration, queryData)
.ConfigureAwait(Common.Configuration.ContinueOnCapturedContext); ;
}
catch (Exception exception) when (_transferInternalExceptionToClient)
{
throw new FaultException(exception.ToString());
}
}
async Task<string?> IWcfLinqService.ExecuteScalarAsync(string? configuration, string queryData)
{
try
{
return await _linqService.ExecuteScalarAsync(configuration, queryData)
.ConfigureAwait(Common.Configuration.ContinueOnCapturedContext); ;
}
catch (Exception exception) when (_transferInternalExceptionToClient)
{
throw new FaultException(exception.ToString());
}
}
}
}
| 28.993243 | 113 | 0.726637 | [
"MIT"
] | BearerPipelineTest/linq2db | Source/LinqToDB.Remote.Wcf/WcfLinqService.cs | 4,146 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Model.Interfaces;
namespace Model.Repositories
{
public class ResourceRepository:IResourceRepository
{
private GeoGrafijaEntities context;
public ResourceRepository(IDbContext context)
{
this.context = (GeoGrafijaEntities)context;
}
public bool CreateItem(Resource item)
{
context.Resources.AddObject(item);
context.SaveChanges();
return true;
}
public Resource GetItem(int id)
{
return context.Resources.Where(x => x.ID == id).FirstOrDefault();
}
public IEnumerable<Resource> GetAllItems()
{
return context.Resources;
}
public bool UpdateItem(Resource item)
{
var oldResource = GetItem(item.ID);
oldResource.Text = item.Text;
oldResource.Name = item.Name;
SaveChanges();
return true;
}
public bool DeleteItem(Resource item)
{
context.Resources.DeleteObject(item);
SaveChanges();
return true;
}
public bool DeleteItem(int id)
{
var item = GetItem(id);
context.Resources.DeleteObject(item);
SaveChanges();
return true;
}
public void SaveChanges()
{
context.SaveChanges();
}
}
}
| 23.059701 | 77 | 0.541748 | [
"MIT"
] | emir01/GeoGrafija | GeoGrafija/Model/Repositories/ResourceRepository.cs | 1,547 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.PooledObjects;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Diagnostics;
using System.Linq;
using System.Reflection;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// This portion of the binder converts an <see cref="ExpressionSyntax"/> into a <see cref="BoundExpression"/>.
/// </summary>
internal partial class Binder
{
/// <summary>
/// Determines whether "this" reference is available within the current context.
/// </summary>
/// <param name="isExplicit">The reference was explicitly specified in syntax.</param>
/// <param name="inStaticContext">True if "this" is not available due to the current method/property/field initializer being static.</param>
/// <returns>True if a reference to "this" is available.</returns>
internal bool HasThis(bool isExplicit, out bool inStaticContext)
{
var memberOpt = this.ContainingMemberOrLambda?.ContainingNonLambdaMember();
if (memberOpt?.IsStatic == true)
{
inStaticContext = memberOpt.Kind == SymbolKind.Field || memberOpt.Kind == SymbolKind.Method || memberOpt.Kind == SymbolKind.Property;
return false;
}
inStaticContext = false;
if (InConstructorInitializer || InAttributeArgument)
{
return false;
}
var containingType = memberOpt?.ContainingType;
bool inTopLevelScriptMember = (object)containingType != null && containingType.IsScriptClass;
// "this" is not allowed in field initializers (that are not script variable initializers):
if (InFieldInitializer && !inTopLevelScriptMember)
{
return false;
}
// top-level script code only allows implicit "this" reference:
return !inTopLevelScriptMember || !isExplicit;
}
internal bool InFieldInitializer
{
get { return this.Flags.Includes(BinderFlags.FieldInitializer); }
}
internal bool InParameterDefaultValue
{
get { return this.Flags.Includes(BinderFlags.ParameterDefaultValue); }
}
protected bool InConstructorInitializer
{
get { return this.Flags.Includes(BinderFlags.ConstructorInitializer); }
}
internal bool InAttributeArgument
{
get { return this.Flags.Includes(BinderFlags.AttributeArgument); }
}
internal bool InCref
{
get { return this.Flags.Includes(BinderFlags.Cref); }
}
protected bool InCrefButNotParameterOrReturnType
{
get { return InCref && !this.Flags.Includes(BinderFlags.CrefParameterOrReturnType); }
}
/// <summary>
/// Returns true if the node is in a position where an unbound type
/// such as (C<,>) is allowed.
/// </summary>
protected virtual bool IsUnboundTypeAllowed(GenericNameSyntax syntax)
{
return _next.IsUnboundTypeAllowed(syntax);
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type
/// </summary>
private BoundBadExpression BadExpression(SyntaxNode syntax)
{
return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty);
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type, and the given bound child.
/// </summary>
private BoundBadExpression BadExpression(SyntaxNode syntax, BoundExpression childNode)
{
return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childNode);
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type, and the given bound children.
/// </summary>
private BoundBadExpression BadExpression(SyntaxNode syntax, ImmutableArray<BoundExpression> childNodes)
{
return BadExpression(syntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childNodes);
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookup resultKind.
/// </summary>
protected BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind lookupResultKind)
{
return BadExpression(syntax, lookupResultKind, ImmutableArray<Symbol>.Empty);
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookup resultKind and the given bound child.
/// </summary>
protected BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind lookupResultKind, BoundExpression childNode)
{
return BadExpression(syntax, lookupResultKind, ImmutableArray<Symbol>.Empty, childNode);
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API.
/// </summary>
private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols)
{
return new BoundBadExpression(syntax,
resultKind,
symbols,
ImmutableArray<BoundExpression>.Empty,
CreateErrorType());
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API,
/// and the given bound child.
/// </summary>
private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols, BoundExpression childNode)
{
return new BoundBadExpression(syntax,
resultKind,
symbols,
ImmutableArray.Create(childNode),
CreateErrorType());
}
/// <summary>
/// Generates a new <see cref="BoundBadExpression"/> with no known type, given lookupResultKind and given symbols for GetSemanticInfo API,
/// and the given bound children.
/// </summary>
private BoundBadExpression BadExpression(SyntaxNode syntax, LookupResultKind resultKind, ImmutableArray<Symbol> symbols, ImmutableArray<BoundExpression> childNodes)
{
return new BoundBadExpression(syntax,
resultKind,
symbols,
childNodes,
CreateErrorType());
}
/// <summary>
/// Helper method to generate a bound expression with HasErrors set to true.
/// Returned bound expression is guaranteed to have a non-null type, except when <paramref name="expr"/> is an unbound lambda.
/// If <paramref name="expr"/> already has errors and meets the above type requirements, then it is returned unchanged.
/// Otherwise, if <paramref name="expr"/> is a BoundBadExpression, then it is updated with the <paramref name="resultKind"/> and non-null type.
/// Otherwise, a new <see cref="BoundBadExpression"/> wrapping <paramref name="expr"/> is returned.
/// </summary>
/// <remarks>
/// Returned expression need not be a <see cref="BoundBadExpression"/>, but is guaranteed to have HasErrors set to true.
/// </remarks>
private BoundExpression ToBadExpression(BoundExpression expr, LookupResultKind resultKind = LookupResultKind.Empty)
{
Debug.Assert(expr != null);
Debug.Assert(resultKind != LookupResultKind.Viable);
TypeSymbol resultType = expr.Type;
BoundKind exprKind = expr.Kind;
if (expr.HasAnyErrors && ((object)resultType != null || exprKind == BoundKind.UnboundLambda))
{
return expr;
}
if (exprKind == BoundKind.BadExpression)
{
var badExpression = (BoundBadExpression)expr;
return badExpression.Update(resultKind, badExpression.Symbols, badExpression.ChildBoundNodes, resultType);
}
else
{
ArrayBuilder<Symbol> symbols = ArrayBuilder<Symbol>.GetInstance();
expr.GetExpressionSymbols(symbols, parent: null, binder: this);
return new BoundBadExpression(
expr.Syntax,
resultKind,
symbols.ToImmutableAndFree(),
ImmutableArray.Create(expr),
resultType ?? CreateErrorType());
}
}
internal TypeSymbol CreateErrorType(string name = "")
{
return new ExtendedErrorTypeSymbol(this.Compilation, name, arity: 0, errorInfo: null, unreported: false);
}
/// <summary>
/// Bind the expression and verify the expression matches the combination of lvalue and
/// rvalue requirements given by valueKind. If the expression was bound successfully, but
/// did not meet the requirements, the return value will be a <see cref="BoundBadExpression"/> that
/// (typically) wraps the subexpression.
/// </summary>
internal BoundExpression BindValue(ExpressionSyntax node, DiagnosticBag diagnostics, BindValueKind valueKind)
{
var result = this.BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false);
return CheckValue(result, valueKind, diagnostics);
}
internal BoundExpression BindValueAllowArgList(ExpressionSyntax node, DiagnosticBag diagnostics, BindValueKind valueKind)
{
var result = this.BindExpressionAllowArgList(node, diagnostics: diagnostics);
return CheckValue(result, valueKind, diagnostics);
}
internal BoundFieldEqualsValue BindFieldInitializer(
FieldSymbol field,
EqualsValueClauseSyntax initializerOpt,
DiagnosticBag diagnostics)
{
Debug.Assert((object)this.ContainingMemberOrLambda == field);
if (initializerOpt == null)
{
return null;
}
Binder initializerBinder = this.GetBinder(initializerOpt);
Debug.Assert(initializerBinder != null);
BoundExpression result = initializerBinder.BindVariableOrAutoPropInitializerValue(initializerOpt, RefKind.None,
field.GetFieldType(initializerBinder.FieldsBeingBound).Type, diagnostics);
return new BoundFieldEqualsValue(initializerOpt, field, initializerBinder.GetDeclaredLocalsForScope(initializerOpt), result);
}
internal BoundExpression BindVariableOrAutoPropInitializerValue(
EqualsValueClauseSyntax initializerOpt,
RefKind refKind,
TypeSymbol varType,
DiagnosticBag diagnostics)
{
if (initializerOpt == null)
{
return null;
}
BindValueKind valueKind;
ExpressionSyntax value;
IsInitializerRefKindValid(initializerOpt, initializerOpt, refKind, diagnostics, out valueKind, out value);
BoundExpression initializer = BindPossibleArrayInitializer(value, varType, valueKind, diagnostics);
initializer = GenerateConversionForAssignment(varType, initializer, diagnostics);
return initializer;
}
internal Binder CreateBinderForParameterDefaultValue(
ParameterSymbol parameter,
EqualsValueClauseSyntax defaultValueSyntax)
{
var binder = new LocalScopeBinder(this.WithContainingMemberOrLambda(parameter.ContainingSymbol).WithAdditionalFlags(BinderFlags.ParameterDefaultValue));
return new ExecutableCodeBinder(defaultValueSyntax,
parameter.ContainingSymbol,
binder);
}
internal BoundParameterEqualsValue BindParameterDefaultValue(
EqualsValueClauseSyntax defaultValueSyntax,
ParameterSymbol parameter,
DiagnosticBag diagnostics,
out BoundExpression valueBeforeConversion)
{
Debug.Assert(this.InParameterDefaultValue);
Debug.Assert(this.ContainingMemberOrLambda.Kind == SymbolKind.Method || this.ContainingMemberOrLambda.Kind == SymbolKind.Property);
// UNDONE: The binding and conversion has to be executed in a checked context.
Binder defaultValueBinder = this.GetBinder(defaultValueSyntax);
Debug.Assert(defaultValueBinder != null);
valueBeforeConversion = defaultValueBinder.BindValue(defaultValueSyntax.Value, diagnostics, BindValueKind.RValue);
// Always generate the conversion, even if the expression is not convertible to the given type.
// We want the erroneous conversion in the tree.
return new BoundParameterEqualsValue(defaultValueSyntax, parameter, defaultValueBinder.GetDeclaredLocalsForScope(defaultValueSyntax),
defaultValueBinder.GenerateConversionForAssignment(parameter.Type, valueBeforeConversion, diagnostics, isDefaultParameter: true));
}
internal BoundFieldEqualsValue BindEnumConstantInitializer(
SourceEnumConstantSymbol symbol,
EqualsValueClauseSyntax equalsValueSyntax,
DiagnosticBag diagnostics)
{
Binder initializerBinder = this.GetBinder(equalsValueSyntax);
Debug.Assert(initializerBinder != null);
var initializer = initializerBinder.BindValue(equalsValueSyntax.Value, diagnostics, BindValueKind.RValue);
initializer = initializerBinder.GenerateConversionForAssignment(symbol.ContainingType.EnumUnderlyingType, initializer, diagnostics);
return new BoundFieldEqualsValue(equalsValueSyntax, symbol, initializerBinder.GetDeclaredLocalsForScope(equalsValueSyntax), initializer);
}
public BoundExpression BindExpression(ExpressionSyntax node, DiagnosticBag diagnostics)
{
return BindExpression(node, diagnostics: diagnostics, invoked: false, indexed: false);
}
protected BoundExpression BindExpression(ExpressionSyntax node, DiagnosticBag diagnostics, bool invoked, bool indexed)
{
BoundExpression expr = BindExpressionInternal(node, diagnostics, invoked, indexed);
VerifyUnchecked(node, diagnostics, expr);
if (expr.Kind == BoundKind.ArgListOperator)
{
// CS0226: An __arglist expression may only appear inside of a call or new expression
Error(diagnostics, ErrorCode.ERR_IllegalArglist, node);
expr = ToBadExpression(expr);
}
return expr;
}
// PERF: allowArgList is not a parameter because it is fairly uncommon case where arglists are allowed
// so we do not want to pass that argument to every BindExpression which is often recursive
// and extra arguments contribute to the stack size.
protected BoundExpression BindExpressionAllowArgList(ExpressionSyntax node, DiagnosticBag diagnostics)
{
BoundExpression expr = BindExpressionInternal(node, diagnostics, invoked: false, indexed: false);
VerifyUnchecked(node, diagnostics, expr);
return expr;
}
private void VerifyUnchecked(ExpressionSyntax node, DiagnosticBag diagnostics, BoundExpression expr)
{
if (!expr.HasAnyErrors && !IsInsideNameof)
{
TypeSymbol exprType = expr.Type;
if ((object)exprType != null && exprType.IsUnsafe())
{
ReportUnsafeIfNotAllowed(node, diagnostics);
//CONSIDER: Return a bad expression so that HasErrors is true?
}
}
}
private BoundExpression BindExpressionInternal(ExpressionSyntax node, DiagnosticBag diagnostics, bool invoked, bool indexed)
{
if (IsEarlyAttributeBinder && !EarlyWellKnownAttributeBinder.CanBeValidAttributeArgument(node, this))
{
return BadExpression(node, LookupResultKind.NotAValue);
}
Debug.Assert(node != null);
switch (node.Kind())
{
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
return BindAnonymousFunction(node, diagnostics);
case SyntaxKind.ThisExpression:
return BindThis((ThisExpressionSyntax)node, diagnostics);
case SyntaxKind.BaseExpression:
return BindBase((BaseExpressionSyntax)node, diagnostics);
case SyntaxKind.InvocationExpression:
return BindInvocationExpression((InvocationExpressionSyntax)node, diagnostics);
case SyntaxKind.ArrayInitializerExpression:
return BindUnexpectedArrayInitializer((InitializerExpressionSyntax)node, diagnostics, ErrorCode.ERR_ArrayInitInBadPlace);
case SyntaxKind.ArrayCreationExpression:
return BindArrayCreationExpression((ArrayCreationExpressionSyntax)node, diagnostics);
case SyntaxKind.ImplicitArrayCreationExpression:
return BindImplicitArrayCreationExpression((ImplicitArrayCreationExpressionSyntax)node, diagnostics);
case SyntaxKind.StackAllocArrayCreationExpression:
return BindStackAllocArrayCreationExpression((StackAllocArrayCreationExpressionSyntax)node, diagnostics);
case SyntaxKind.ImplicitStackAllocArrayCreationExpression:
return BindImplicitStackAllocArrayCreationExpression((ImplicitStackAllocArrayCreationExpressionSyntax)node, diagnostics);
case SyntaxKind.ObjectCreationExpression:
return BindObjectCreationExpression((ObjectCreationExpressionSyntax)node, diagnostics);
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
return BindIdentifier((SimpleNameSyntax)node, invoked, indexed, diagnostics);
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
return BindMemberAccess((MemberAccessExpressionSyntax)node, invoked, indexed, diagnostics: diagnostics);
case SyntaxKind.SimpleAssignmentExpression:
return BindAssignment((AssignmentExpressionSyntax)node, diagnostics);
case SyntaxKind.CastExpression:
return BindCast((CastExpressionSyntax)node, diagnostics);
case SyntaxKind.ElementAccessExpression:
return BindElementAccess((ElementAccessExpressionSyntax)node, diagnostics);
case SyntaxKind.AddExpression:
case SyntaxKind.MultiplyExpression:
case SyntaxKind.SubtractExpression:
case SyntaxKind.DivideExpression:
case SyntaxKind.ModuloExpression:
case SyntaxKind.EqualsExpression:
case SyntaxKind.NotEqualsExpression:
case SyntaxKind.GreaterThanExpression:
case SyntaxKind.LessThanExpression:
case SyntaxKind.GreaterThanOrEqualExpression:
case SyntaxKind.LessThanOrEqualExpression:
case SyntaxKind.BitwiseAndExpression:
case SyntaxKind.BitwiseOrExpression:
case SyntaxKind.ExclusiveOrExpression:
case SyntaxKind.LeftShiftExpression:
case SyntaxKind.RightShiftExpression:
return BindSimpleBinaryOperator((BinaryExpressionSyntax)node, diagnostics);
case SyntaxKind.LogicalAndExpression:
case SyntaxKind.LogicalOrExpression:
return BindConditionalLogicalOperator((BinaryExpressionSyntax)node, diagnostics);
case SyntaxKind.CoalesceExpression:
return BindNullCoalescingOperator((BinaryExpressionSyntax)node, diagnostics);
case SyntaxKind.ConditionalAccessExpression:
return BindConditionalAccessExpression((ConditionalAccessExpressionSyntax)node, diagnostics);
case SyntaxKind.MemberBindingExpression:
return BindMemberBindingExpression((MemberBindingExpressionSyntax)node, invoked, indexed, diagnostics);
case SyntaxKind.ElementBindingExpression:
return BindElementBindingExpression((ElementBindingExpressionSyntax)node, diagnostics);
case SyntaxKind.IsExpression:
return BindIsOperator((BinaryExpressionSyntax)node, diagnostics);
case SyntaxKind.AsExpression:
return BindAsOperator((BinaryExpressionSyntax)node, diagnostics);
case SyntaxKind.UnaryPlusExpression:
case SyntaxKind.UnaryMinusExpression:
case SyntaxKind.LogicalNotExpression:
case SyntaxKind.BitwiseNotExpression:
return BindUnaryOperator((PrefixUnaryExpressionSyntax)node, diagnostics);
case SyntaxKind.IndexExpression:
return BindFromEndIndexExpression((PrefixUnaryExpressionSyntax)node, diagnostics);
case SyntaxKind.RangeExpression:
return BindRangeExpression((RangeExpressionSyntax)node, diagnostics);
case SyntaxKind.AddressOfExpression:
return BindAddressOfExpression((PrefixUnaryExpressionSyntax)node, diagnostics);
case SyntaxKind.PointerIndirectionExpression:
return BindPointerIndirectionExpression((PrefixUnaryExpressionSyntax)node, diagnostics);
case SyntaxKind.PostIncrementExpression:
case SyntaxKind.PostDecrementExpression:
return BindIncrementOperator(node, ((PostfixUnaryExpressionSyntax)node).Operand, ((PostfixUnaryExpressionSyntax)node).OperatorToken, diagnostics);
case SyntaxKind.PreIncrementExpression:
case SyntaxKind.PreDecrementExpression:
return BindIncrementOperator(node, ((PrefixUnaryExpressionSyntax)node).Operand, ((PrefixUnaryExpressionSyntax)node).OperatorToken, diagnostics);
case SyntaxKind.ConditionalExpression:
return BindConditionalOperator((ConditionalExpressionSyntax)node, diagnostics);
case SyntaxKind.SwitchExpression:
return BindSwitchExpression((SwitchExpressionSyntax)node, diagnostics);
case SyntaxKind.NumericLiteralExpression:
case SyntaxKind.StringLiteralExpression:
case SyntaxKind.CharacterLiteralExpression:
case SyntaxKind.TrueLiteralExpression:
case SyntaxKind.FalseLiteralExpression:
case SyntaxKind.NullLiteralExpression:
return BindLiteralConstant((LiteralExpressionSyntax)node, diagnostics);
case SyntaxKind.DefaultLiteralExpression:
return BindDefaultLiteral(node);
case SyntaxKind.ParenthesizedExpression:
// Parenthesis tokens are ignored, and operand is bound in the context of parent
// expression.
return BindParenthesizedExpression(((ParenthesizedExpressionSyntax)node).Expression, diagnostics);
case SyntaxKind.UncheckedExpression:
case SyntaxKind.CheckedExpression:
return BindCheckedExpression((CheckedExpressionSyntax)node, diagnostics);
case SyntaxKind.DefaultExpression:
return BindDefaultExpression((DefaultExpressionSyntax)node, diagnostics);
case SyntaxKind.TypeOfExpression:
return BindTypeOf((TypeOfExpressionSyntax)node, diagnostics);
case SyntaxKind.SizeOfExpression:
return BindSizeOf((SizeOfExpressionSyntax)node, diagnostics);
case SyntaxKind.AddAssignmentExpression:
case SyntaxKind.AndAssignmentExpression:
case SyntaxKind.DivideAssignmentExpression:
case SyntaxKind.ExclusiveOrAssignmentExpression:
case SyntaxKind.LeftShiftAssignmentExpression:
case SyntaxKind.ModuloAssignmentExpression:
case SyntaxKind.MultiplyAssignmentExpression:
case SyntaxKind.OrAssignmentExpression:
case SyntaxKind.RightShiftAssignmentExpression:
case SyntaxKind.SubtractAssignmentExpression:
return BindCompoundAssignment((AssignmentExpressionSyntax)node, diagnostics);
case SyntaxKind.CoalesceAssignmentExpression:
return BindNullCoalescingAssignmentOperator((AssignmentExpressionSyntax)node, diagnostics);
case SyntaxKind.AliasQualifiedName:
case SyntaxKind.PredefinedType:
return this.BindNamespaceOrType(node, diagnostics);
case SyntaxKind.QueryExpression:
return this.BindQuery((QueryExpressionSyntax)node, diagnostics);
case SyntaxKind.AnonymousObjectCreationExpression:
return BindAnonymousObjectCreation((AnonymousObjectCreationExpressionSyntax)node, diagnostics);
case SyntaxKind.QualifiedName:
return BindQualifiedName((QualifiedNameSyntax)node, diagnostics);
case SyntaxKind.ComplexElementInitializerExpression:
return BindUnexpectedComplexElementInitializer((InitializerExpressionSyntax)node, diagnostics);
case SyntaxKind.ArgListExpression:
return BindArgList(node, diagnostics);
case SyntaxKind.RefTypeExpression:
return BindRefType((RefTypeExpressionSyntax)node, diagnostics);
case SyntaxKind.MakeRefExpression:
return BindMakeRef((MakeRefExpressionSyntax)node, diagnostics);
case SyntaxKind.RefValueExpression:
return BindRefValue((RefValueExpressionSyntax)node, diagnostics);
case SyntaxKind.AwaitExpression:
return BindAwait((AwaitExpressionSyntax)node, diagnostics);
case SyntaxKind.OmittedArraySizeExpression:
case SyntaxKind.OmittedTypeArgument:
case SyntaxKind.ObjectInitializerExpression:
// Not reachable during method body binding, but
// may be used by SemanticModel for error cases.
return BadExpression(node);
case SyntaxKind.NullableType:
// Not reachable during method body binding, but
// may be used by SemanticModel for error cases.
// NOTE: This happens when there's a problem with the Nullable<T> type (e.g. it's missing).
// There is no corresponding problem for array or pointer types (which seem analogous), since
// they are not constructed types; the element type can be an error type, but the array/pointer
// type cannot.
return BadExpression(node);
case SyntaxKind.InterpolatedStringExpression:
return BindInterpolatedString((InterpolatedStringExpressionSyntax)node, diagnostics);
case SyntaxKind.IsPatternExpression:
return BindIsPatternExpression((IsPatternExpressionSyntax)node, diagnostics);
case SyntaxKind.TupleExpression:
return BindTupleExpression((TupleExpressionSyntax)node, diagnostics);
case SyntaxKind.ThrowExpression:
return BindThrowExpression((ThrowExpressionSyntax)node, diagnostics);
case SyntaxKind.RefType:
return BindRefType(node, diagnostics);
case SyntaxKind.RefExpression:
return BindRefExpression(node, diagnostics);
case SyntaxKind.DeclarationExpression:
return BindDeclarationExpression((DeclarationExpressionSyntax)node, diagnostics);
case SyntaxKind.SuppressNullableWarningExpression:
return BindSuppressNullableWarningExpression((PostfixUnaryExpressionSyntax)node, diagnostics);
default:
// NOTE: We could probably throw an exception here, but it's conceivable
// that a non-parser syntax tree could reach this point with an unexpected
// SyntaxKind and we don't want to throw if that occurs.
Debug.Assert(false, "Unexpected SyntaxKind " + node.Kind());
return BadExpression(node);
}
}
private static BoundExpression BindDefaultLiteral(ExpressionSyntax node)
{
return new BoundDefaultExpression(node, type: null);
}
internal virtual BoundSwitchExpressionArm BindSwitchExpressionArm(SwitchExpressionArmSyntax node, DiagnosticBag diagnostics)
{
return this.Next.BindSwitchExpressionArm(node, diagnostics);
}
private BoundExpression BindRefExpression(ExpressionSyntax node, DiagnosticBag diagnostics)
{
var firstToken = node.GetFirstToken();
diagnostics.Add(ErrorCode.ERR_UnexpectedToken, firstToken.GetLocation(), firstToken.ValueText);
return new BoundBadExpression(
node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, ImmutableArray<BoundExpression>.Empty,
CreateErrorType("ref"));
}
private BoundExpression BindRefType(ExpressionSyntax node, DiagnosticBag diagnostics)
{
var firstToken = node.GetFirstToken();
diagnostics.Add(ErrorCode.ERR_UnexpectedToken, firstToken.GetLocation(), firstToken.ValueText);
return new BoundTypeExpression(node, null, CreateErrorType("ref"));
}
private BoundExpression BindThrowExpression(ThrowExpressionSyntax node, DiagnosticBag diagnostics)
{
bool hasErrors = node.HasErrors;
if (!IsThrowExpressionInProperContext(node))
{
diagnostics.Add(ErrorCode.ERR_ThrowMisplaced, node.ThrowKeyword.GetLocation());
hasErrors = true;
}
var thrownExpression = BindThrownExpression(node.Expression, diagnostics, ref hasErrors);
return new BoundThrowExpression(node, thrownExpression, null, hasErrors);
}
private static bool IsThrowExpressionInProperContext(ThrowExpressionSyntax node)
{
var parent = node.Parent;
if (parent == null || node.HasErrors)
{
return true;
}
switch (parent.Kind())
{
case SyntaxKind.ConditionalExpression: // ?:
{
var conditionalParent = (ConditionalExpressionSyntax)parent;
return node == conditionalParent.WhenTrue || node == conditionalParent.WhenFalse;
}
case SyntaxKind.CoalesceExpression: // ??
{
var binaryParent = (BinaryExpressionSyntax)parent;
return node == binaryParent.Right;
}
case SyntaxKind.SwitchExpressionArm:
case SyntaxKind.ArrowExpressionClause:
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
return true;
// We do not support && and || because
// 1. The precedence would not syntactically allow it
// 2. It isn't clear what the semantics should be
// 3. It isn't clear what use cases would motivate us to change the precedence to support it
default:
return false;
}
}
// Bind a declaration expression where it isn't permitted.
private BoundExpression BindDeclarationExpression(DeclarationExpressionSyntax node, DiagnosticBag diagnostics)
{
// This is an error, as declaration expressions are handled specially in every context in which
// they are permitted. So we have a context in which they are *not* permitted. Nevertheless, we
// bind it and then give one nice message.
bool isVar;
bool isConst = false;
AliasSymbol alias;
var declType = BindVariableTypeWithAnnotations(node.Designation, diagnostics, node.Type, ref isConst, out isVar, out alias);
Error(diagnostics, ErrorCode.ERR_DeclarationExpressionNotPermitted, node);
return BindDeclarationVariables(declType, node.Designation, node, diagnostics);
}
/// <summary>
/// Bind a declaration variable where it isn't permitted. The caller is expected to produce a diagnostic.
/// </summary>
private BoundExpression BindDeclarationVariables(TypeWithAnnotations declTypeWithAnnotations, VariableDesignationSyntax node, CSharpSyntaxNode syntax, DiagnosticBag diagnostics)
{
declTypeWithAnnotations = declTypeWithAnnotations.HasType ? declTypeWithAnnotations : TypeWithAnnotations.Create(CreateErrorType("var"));
switch (node.Kind())
{
case SyntaxKind.SingleVariableDesignation:
{
var single = (SingleVariableDesignationSyntax)node;
var result = BindDeconstructionVariable(declTypeWithAnnotations, single, syntax, diagnostics);
return result;
}
case SyntaxKind.DiscardDesignation:
{
return BindDiscardExpression(syntax, declTypeWithAnnotations);
}
case SyntaxKind.ParenthesizedVariableDesignation:
{
var tuple = (ParenthesizedVariableDesignationSyntax)node;
int count = tuple.Variables.Count;
var builder = ArrayBuilder<BoundExpression>.GetInstance(count);
var namesBuilder = ArrayBuilder<string>.GetInstance(count);
foreach (var n in tuple.Variables)
{
builder.Add(BindDeclarationVariables(declTypeWithAnnotations, n, n, diagnostics));
namesBuilder.Add(InferTupleElementName(n));
}
ImmutableArray<BoundExpression> subExpressions = builder.ToImmutableAndFree();
var uniqueFieldNames = PooledHashSet<string>.GetInstance();
RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref namesBuilder, uniqueFieldNames);
uniqueFieldNames.Free();
ImmutableArray<string> tupleNames = namesBuilder is null ? default : namesBuilder.ToImmutableAndFree();
ImmutableArray<bool> inferredPositions = tupleNames.IsDefault ? default : tupleNames.SelectAsArray(n => n != null);
bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames();
// We will not check constraints at this point as this code path
// is failure-only and the caller is expected to produce a diagnostic.
var tupleType = TupleTypeSymbol.Create(
locationOpt: null,
subExpressions.SelectAsArray(e => TypeWithAnnotations.Create(e.Type)),
elementLocations: default,
tupleNames,
Compilation,
shouldCheckConstraints: false,
includeNullability: false,
errorPositions: disallowInferredNames ? inferredPositions : default);
return new BoundTupleLiteral(syntax, argumentNamesOpt: default, inferredPositions, subExpressions, tupleType);
}
default:
throw ExceptionUtilities.UnexpectedValue(node.Kind());
}
}
private BoundExpression BindTupleExpression(TupleExpressionSyntax node, DiagnosticBag diagnostics)
{
SeparatedSyntaxList<ArgumentSyntax> arguments = node.Arguments;
int numElements = arguments.Count;
if (numElements < 2)
{
// this should be a parse error already.
var args = numElements == 1 ?
ImmutableArray.Create(BindValue(arguments[0].Expression, diagnostics, BindValueKind.RValue)) :
ImmutableArray<BoundExpression>.Empty;
return BadExpression(node, args);
}
bool hasNaturalType = true;
var boundArguments = ArrayBuilder<BoundExpression>.GetInstance(arguments.Count);
var elementTypesWithAnnotations = ArrayBuilder<TypeWithAnnotations>.GetInstance(arguments.Count);
var elementLocations = ArrayBuilder<Location>.GetInstance(arguments.Count);
// prepare names
var (elementNames, inferredPositions, hasErrors) = ExtractTupleElementNames(arguments, diagnostics);
// prepare types and locations
for (int i = 0; i < numElements; i++)
{
ArgumentSyntax argumentSyntax = arguments[i];
IdentifierNameSyntax nameSyntax = argumentSyntax.NameColon?.Name;
if (nameSyntax != null)
{
elementLocations.Add(nameSyntax.Location);
}
else
{
elementLocations.Add(argumentSyntax.Location);
}
BoundExpression boundArgument = BindValue(argumentSyntax.Expression, diagnostics, BindValueKind.RValue);
if (boundArgument.Type?.SpecialType == SpecialType.System_Void)
{
diagnostics.Add(ErrorCode.ERR_VoidInTuple, argumentSyntax.Location);
boundArgument = new BoundBadExpression(
argumentSyntax, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty,
ImmutableArray.Create<BoundExpression>(boundArgument), CreateErrorType("void"));
}
boundArguments.Add(boundArgument);
var elementTypeWithAnnotations = TypeWithAnnotations.Create(boundArgument.Type);
elementTypesWithAnnotations.Add(elementTypeWithAnnotations);
if (!elementTypeWithAnnotations.HasType)
{
hasNaturalType = false;
}
}
NamedTypeSymbol tupleTypeOpt = null;
var elements = elementTypesWithAnnotations.ToImmutableAndFree();
var locations = elementLocations.ToImmutableAndFree();
if (hasNaturalType)
{
bool disallowInferredNames = this.Compilation.LanguageVersion.DisallowInferredTupleElementNames();
tupleTypeOpt = TupleTypeSymbol.Create(node.Location, elements, locations, elementNames,
this.Compilation, syntax: node, diagnostics: diagnostics, shouldCheckConstraints: true,
includeNullability: false, errorPositions: disallowInferredNames ? inferredPositions : default(ImmutableArray<bool>));
}
else
{
TupleTypeSymbol.VerifyTupleTypePresent(elements.Length, node, this.Compilation, diagnostics);
}
// Always track the inferred positions in the bound node, so that conversions don't produce a warning
// for "dropped names" on tuple literal when the name was inferred.
return new BoundTupleLiteral(node, elementNames, inferredPositions, boundArguments.ToImmutableAndFree(), tupleTypeOpt, hasErrors);
}
private static (ImmutableArray<string> elementNamesArray, ImmutableArray<bool> inferredArray, bool hasErrors) ExtractTupleElementNames(
SeparatedSyntaxList<ArgumentSyntax> arguments, DiagnosticBag diagnostics)
{
bool hasErrors = false;
int numElements = arguments.Count;
var uniqueFieldNames = PooledHashSet<string>.GetInstance();
ArrayBuilder<string> elementNames = null;
ArrayBuilder<string> inferredElementNames = null;
for (int i = 0; i < numElements; i++)
{
ArgumentSyntax argumentSyntax = arguments[i];
IdentifierNameSyntax nameSyntax = argumentSyntax.NameColon?.Name;
string name = null;
string inferredName = null;
if (nameSyntax != null)
{
name = nameSyntax.Identifier.ValueText;
if (diagnostics != null && !CheckTupleMemberName(name, i, argumentSyntax.NameColon.Name, diagnostics, uniqueFieldNames))
{
hasErrors = true;
}
}
else
{
inferredName = InferTupleElementName(argumentSyntax.Expression);
}
CollectTupleFieldMemberName(name, i, numElements, ref elementNames);
CollectTupleFieldMemberName(inferredName, i, numElements, ref inferredElementNames);
}
RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref inferredElementNames, uniqueFieldNames);
uniqueFieldNames.Free();
var result = MergeTupleElementNames(elementNames, inferredElementNames);
elementNames?.Free();
inferredElementNames?.Free();
return (result.names, result.inferred, hasErrors);
}
private static (ImmutableArray<string> names, ImmutableArray<bool> inferred) MergeTupleElementNames(
ArrayBuilder<string> elementNames, ArrayBuilder<string> inferredElementNames)
{
if (elementNames == null)
{
if (inferredElementNames == null)
{
return (default(ImmutableArray<string>), default(ImmutableArray<bool>));
}
else
{
var finalNames = inferredElementNames.ToImmutable();
return (finalNames, finalNames.SelectAsArray(n => n != null));
}
}
if (inferredElementNames == null)
{
return (elementNames.ToImmutable(), default(ImmutableArray<bool>));
}
Debug.Assert(elementNames.Count == inferredElementNames.Count);
var builder = ArrayBuilder<bool>.GetInstance(elementNames.Count);
for (int i = 0; i < elementNames.Count; i++)
{
string inferredName = inferredElementNames[i];
if (elementNames[i] == null && inferredName != null)
{
elementNames[i] = inferredName;
builder.Add(true);
}
else
{
builder.Add(false);
}
}
return (elementNames.ToImmutable(), builder.ToImmutableAndFree());
}
/// <summary>
/// Removes duplicate entries in <paramref name="inferredElementNames"/> and frees it if only nulls remain.
/// </summary>
private static void RemoveDuplicateInferredTupleNamesAndFreeIfEmptied(ref ArrayBuilder<string> inferredElementNames, HashSet<string> uniqueFieldNames)
{
if (inferredElementNames == null)
{
return;
}
// Inferred names that duplicate an explicit name or a previous inferred name are tagged for removal
var toRemove = PooledHashSet<string>.GetInstance();
foreach (var name in inferredElementNames)
{
if (name != null && !uniqueFieldNames.Add(name))
{
toRemove.Add(name);
}
}
for (int i = 0; i < inferredElementNames.Count; i++)
{
var inferredName = inferredElementNames[i];
if (inferredName != null && toRemove.Contains(inferredName))
{
inferredElementNames[i] = null;
}
}
toRemove.Free();
if (inferredElementNames.All(n => n is null))
{
inferredElementNames.Free();
inferredElementNames = null;
}
}
private static string InferTupleElementName(SyntaxNode syntax)
{
string name = syntax.TryGetInferredMemberName();
// Reserved names are never candidates to be inferred names, at any position
if (name == null || TupleTypeSymbol.IsElementNameReserved(name) != -1)
{
return null;
}
return name;
}
private BoundExpression BindRefValue(RefValueExpressionSyntax node, DiagnosticBag diagnostics)
{
// __refvalue(tr, T) requires that tr be a TypedReference and T be a type.
// The result is a *variable* of type T.
BoundExpression argument = BindValue(node.Expression, diagnostics, BindValueKind.RValue);
bool hasErrors = argument.HasAnyErrors;
TypeSymbol typedReferenceType = this.Compilation.GetSpecialType(SpecialType.System_TypedReference);
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
Conversion conversion = this.Conversions.ClassifyConversionFromExpression(argument, typedReferenceType, ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
if (!conversion.IsImplicit || !conversion.IsValid)
{
hasErrors = true;
GenerateImplicitConversionError(diagnostics, node, conversion, argument, typedReferenceType);
}
argument = CreateConversion(argument, conversion, typedReferenceType, diagnostics);
TypeWithAnnotations typeWithAnnotations = BindType(node.Type, diagnostics);
return new BoundRefValueOperator(node, typeWithAnnotations.NullableAnnotation, argument, typeWithAnnotations.Type, hasErrors);
}
private BoundExpression BindMakeRef(MakeRefExpressionSyntax node, DiagnosticBag diagnostics)
{
// __makeref(x) requires that x be a variable, and not be of a restricted type.
BoundExpression argument = this.BindValue(node.Expression, diagnostics, BindValueKind.RefOrOut);
bool hasErrors = argument.HasAnyErrors;
TypeSymbol typedReferenceType = GetSpecialType(SpecialType.System_TypedReference, diagnostics, node);
if ((object)argument.Type != null && argument.Type.IsRestrictedType())
{
// CS1601: Cannot make reference to variable of type '{0}'
Error(diagnostics, ErrorCode.ERR_MethodArgCantBeRefAny, node, argument.Type);
hasErrors = true;
}
// UNDONE: We do not yet implement warnings anywhere for:
// UNDONE: * taking a ref to a volatile field
// UNDONE: * taking a ref to a "non-agile" field
// UNDONE: We should do so here when we implement this feature for regular out/ref parameters.
return new BoundMakeRefOperator(node, argument, typedReferenceType, hasErrors);
}
private BoundExpression BindRefType(RefTypeExpressionSyntax node, DiagnosticBag diagnostics)
{
// __reftype(x) requires that x be implicitly convertible to TypedReference.
BoundExpression argument = BindValue(node.Expression, diagnostics, BindValueKind.RValue);
bool hasErrors = argument.HasAnyErrors;
TypeSymbol typedReferenceType = this.Compilation.GetSpecialType(SpecialType.System_TypedReference);
TypeSymbol typeType = this.Compilation.GetWellKnownType(WellKnownType.System_Type);
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
Conversion conversion = this.Conversions.ClassifyConversionFromExpression(argument, typedReferenceType, ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
if (!conversion.IsImplicit || !conversion.IsValid)
{
hasErrors = true;
GenerateImplicitConversionError(diagnostics, node, conversion, argument, typedReferenceType);
}
argument = CreateConversion(argument, conversion, typedReferenceType, diagnostics);
return new BoundRefTypeOperator(node, argument, null, typeType, hasErrors);
}
private BoundExpression BindArgList(CSharpSyntaxNode node, DiagnosticBag diagnostics)
{
// There are two forms of __arglist expression. In a method with an __arglist parameter,
// it is legal to use __arglist as an expression of type RuntimeArgumentHandle. In
// a call to such a method, it is legal to use __arglist(x, y, z) as the final argument.
// This method only handles the first usage; the second usage is parsed as a call syntax.
// The native compiler allows __arglist in a lambda:
//
// class C
// {
// delegate int D(RuntimeArgumentHandle r);
// static void M(__arglist)
// {
// D f = null;
// f = r=>f(__arglist);
// }
// }
//
// This is clearly wrong. Either the developer intends __arglist to refer to the
// arg list of the *lambda*, or to the arg list of *M*. The former makes no sense;
// lambdas cannot have an arg list. The latter we have no way to generate code for;
// you cannot hoist the arg list to a field of a closure class.
//
// The native compiler allows this and generates code as though the developer
// was attempting to access the arg list of the lambda! We should simply disallow it.
TypeSymbol runtimeArgumentHandleType = GetSpecialType(SpecialType.System_RuntimeArgumentHandle, diagnostics, node);
MethodSymbol method = this.ContainingMember() as MethodSymbol;
bool hasError = false;
if ((object)method == null || !method.IsVararg)
{
// CS0190: The __arglist construct is valid only within a variable argument method
Error(diagnostics, ErrorCode.ERR_ArgsInvalid, node);
hasError = true;
}
else
{
// We're in a varargs method; are we also inside a lambda?
Symbol container = this.ContainingMemberOrLambda;
if (container != method)
{
// We also need to report this any time a local variable of a restricted type
// would be hoisted into a closure for an anonymous function, iterator or async method.
// We do that during the actual rewrites.
// CS4013: Instance of type '{0}' cannot be used inside an anonymous function, query expression, iterator block or async method
Error(diagnostics, ErrorCode.ERR_SpecialByRefInLambda, node, runtimeArgumentHandleType);
hasError = true;
}
}
return new BoundArgList(node, runtimeArgumentHandleType, hasError);
}
/// <summary>
/// This can be reached for the qualified name on the right-hand-side of an `is` operator.
/// For compatibility we parse it as a qualified name, as the is-type expression only permitted
/// a type on the right-hand-side in C# 6. But the same syntax now, in C# 7 and later, can
/// refer to a constant, which would normally be represented as a *simple member access expression*.
/// Since the parser cannot distinguish, it parses it as before and depends on the binder
/// to handle a qualified name appearing as an expression.
/// </summary>
private BoundExpression BindQualifiedName(QualifiedNameSyntax node, DiagnosticBag diagnostics)
{
return BindMemberAccessWithBoundLeft(node, this.BindLeftOfPotentialColorColorMemberAccess(node.Left, diagnostics), node.Right, node.DotToken, invoked: false, indexed: false, diagnostics: diagnostics);
}
private BoundExpression BindParenthesizedExpression(ExpressionSyntax innerExpression, DiagnosticBag diagnostics)
{
var result = BindExpression(innerExpression, diagnostics);
// A parenthesized expression may not be a namespace or a type. If it is a parenthesized
// namespace or type then report the error but let it go; we'll just ignore the
// parenthesis and keep on trucking.
CheckNotNamespaceOrType(result, diagnostics);
return result;
}
private BoundExpression BindTypeOf(TypeOfExpressionSyntax node, DiagnosticBag diagnostics)
{
ExpressionSyntax typeSyntax = node.Type;
TypeofBinder typeofBinder = new TypeofBinder(typeSyntax, this); //has special handling for unbound types
AliasSymbol alias;
TypeWithAnnotations typeWithAnnotations = typeofBinder.BindType(typeSyntax, diagnostics, out alias);
TypeSymbol type = typeWithAnnotations.Type;
bool hasError = false;
// NB: Dev10 has an error for typeof(dynamic), but allows typeof(dynamic[]),
// typeof(C<dynamic>), etc.
if (type.IsDynamic())
{
diagnostics.Add(ErrorCode.ERR_BadDynamicTypeof, node.Location);
hasError = true;
}
else if (typeWithAnnotations.NullableAnnotation.IsAnnotated() && type.IsReferenceType)
{
// error: cannot take the `typeof` a nullable reference type.
diagnostics.Add(ErrorCode.ERR_BadNullableTypeof, node.Location);
hasError = true;
}
BoundTypeExpression boundType = new BoundTypeExpression(typeSyntax, alias, typeWithAnnotations, type.IsErrorType());
return new BoundTypeOfOperator(node, boundType, null, this.GetWellKnownType(WellKnownType.System_Type, diagnostics, node), hasError);
}
private BoundExpression BindSizeOf(SizeOfExpressionSyntax node, DiagnosticBag diagnostics)
{
ExpressionSyntax typeSyntax = node.Type;
AliasSymbol alias;
TypeWithAnnotations typeWithAnnotations = this.BindType(typeSyntax, diagnostics, out alias);
TypeSymbol type = typeWithAnnotations.Type;
bool typeHasErrors = type.IsErrorType() || CheckManagedAddr(type, node, diagnostics);
BoundTypeExpression boundType = new BoundTypeExpression(typeSyntax, alias, typeWithAnnotations, typeHasErrors);
ConstantValue constantValue = GetConstantSizeOf(type);
bool hasErrors = ReferenceEquals(constantValue, null) && ReportUnsafeIfNotAllowed(node, diagnostics, type);
return new BoundSizeOfOperator(node, boundType, constantValue,
this.GetSpecialType(SpecialType.System_Int32, diagnostics, node), hasErrors);
}
/// <returns>true if managed type-related errors were found, otherwise false.</returns>
private static bool CheckManagedAddr(TypeSymbol type, SyntaxNode node, DiagnosticBag diagnostics)
{
var managedKind = type.ManagedKind;
if (managedKind == ManagedKind.Managed)
{
diagnostics.Add(ErrorCode.ERR_ManagedAddr, node.Location, type);
return true;
}
else if (managedKind == ManagedKind.UnmanagedWithGenerics)
{
var supported = CheckFeatureAvailability(node, MessageID.IDS_FeatureUnmanagedConstructedTypes, diagnostics);
return !supported;
}
return false;
}
internal static ConstantValue GetConstantSizeOf(TypeSymbol type)
{
return ConstantValue.CreateSizeOf((type.GetEnumUnderlyingType() ?? type).SpecialType);
}
private BoundExpression BindDefaultExpression(DefaultExpressionSyntax node, DiagnosticBag diagnostics)
{
TypeWithAnnotations typeWithAnnotations = this.BindType(node.Type, diagnostics, out AliasSymbol alias);
var typeExpression = new BoundTypeExpression(node.Type, aliasOpt: alias, typeWithAnnotations);
TypeSymbol type = typeWithAnnotations.Type;
return new BoundDefaultExpression(node, typeExpression, constantValueOpt: type.GetDefaultValue(), type);
}
/// <summary>
/// Binds a simple identifier.
/// </summary>
private BoundExpression BindIdentifier(
SimpleNameSyntax node,
bool invoked,
bool indexed,
DiagnosticBag diagnostics)
{
Debug.Assert(node != null);
// If the syntax tree is ill-formed and the identifier is missing then we've already
// given a parse error. Just return an error local and continue with analysis.
if (node.IsMissing)
{
return BadExpression(node);
}
// A simple-name is either of the form I or of the form I<A1, ..., AK>, where I is a
// single identifier and <A1, ..., AK> is an optional type-argument-list. When no
// type-argument-list is specified, consider K to be zero. The simple-name is evaluated
// and classified as follows:
// If K is zero and the simple-name appears within a block and if the block's (or an
// enclosing block's) local variable declaration space contains a local variable,
// parameter or constant with name I, then the simple-name refers to that local
// variable, parameter or constant and is classified as a variable or value.
// If K is zero and the simple-name appears within the body of a generic method
// declaration and if that declaration includes a type parameter with name I, then the
// simple-name refers to that type parameter.
BoundExpression expression;
// It's possible that the argument list is malformed; if so, do not attempt to bind it;
// just use the null array.
int arity = node.Arity;
bool hasTypeArguments = arity > 0;
SeparatedSyntaxList<TypeSyntax> typeArgumentList = node.Kind() == SyntaxKind.GenericName
? ((GenericNameSyntax)node).TypeArgumentList.Arguments
: default(SeparatedSyntaxList<TypeSyntax>);
Debug.Assert(arity == typeArgumentList.Count);
var typeArgumentsWithAnnotations = hasTypeArguments ?
BindTypeArguments(typeArgumentList, diagnostics) :
default(ImmutableArray<TypeWithAnnotations>);
var lookupResult = LookupResult.GetInstance();
LookupOptions options = LookupOptions.AllMethodsOnArityZero;
if (invoked)
{
options |= LookupOptions.MustBeInvocableIfMember;
}
if (!IsInMethodBody && !IsInsideNameof)
{
Debug.Assert((options & LookupOptions.NamespacesOrTypesOnly) == 0);
options |= LookupOptions.MustNotBeMethodTypeParameter;
}
var name = node.Identifier.ValueText;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
this.LookupSymbolsWithFallback(lookupResult, name, arity: arity, useSiteDiagnostics: ref useSiteDiagnostics, options: options);
diagnostics.Add(node, useSiteDiagnostics);
if (lookupResult.Kind != LookupResultKind.Empty)
{
// have we detected an error with the current node?
bool isError = false;
bool wasError;
var members = ArrayBuilder<Symbol>.GetInstance();
Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, node, name, node.Arity, members, diagnostics, out wasError); // reports diagnostics in result.
isError |= wasError;
if ((object)symbol == null)
{
Debug.Assert(members.Count > 0);
var receiver = SynthesizeMethodGroupReceiver(node, members);
expression = ConstructBoundMemberGroupAndReportOmittedTypeArguments(
node,
typeArgumentList,
typeArgumentsWithAnnotations,
receiver,
name,
members,
lookupResult,
receiver != null ? BoundMethodGroupFlags.HasImplicitReceiver : BoundMethodGroupFlags.None,
isError,
diagnostics);
}
else
{
bool isNamedType = (symbol.Kind == SymbolKind.NamedType) || (symbol.Kind == SymbolKind.ErrorType);
if (hasTypeArguments && isNamedType)
{
symbol = ConstructNamedTypeUnlessTypeArgumentOmitted(node, (NamedTypeSymbol)symbol, typeArgumentList, typeArgumentsWithAnnotations, diagnostics);
}
expression = BindNonMethod(node, symbol, diagnostics, lookupResult.Kind, indexed, isError);
if (!isNamedType && (hasTypeArguments || node.Kind() == SyntaxKind.GenericName))
{
Debug.Assert(isError); // Should have been reported by GetSymbolOrMethodOrPropertyGroup.
expression = new BoundBadExpression(
syntax: node,
resultKind: LookupResultKind.WrongArity,
symbols: ImmutableArray.Create(symbol),
childBoundNodes: ImmutableArray.Create(expression),
type: expression.Type,
hasErrors: isError);
}
}
members.Free();
}
else
{
if (node.IsKind(SyntaxKind.IdentifierName) && FallBackOnDiscard((IdentifierNameSyntax)node, diagnostics))
{
lookupResult.Free();
return new BoundDiscardExpression(node, type: null);
}
// Otherwise, the simple-name is undefined and a compile-time error occurs.
expression = BadExpression(node);
if (lookupResult.Error != null)
{
Error(diagnostics, lookupResult.Error, node);
}
else if (IsJoinRangeVariableInLeftKey(node))
{
Error(diagnostics, ErrorCode.ERR_QueryOuterKey, node, name);
}
else if (IsInJoinRightKey(node))
{
Error(diagnostics, ErrorCode.ERR_QueryInnerKey, node, name);
}
else
{
Error(diagnostics, ErrorCode.ERR_NameNotInContext, node, name);
}
}
lookupResult.Free();
return expression;
}
/// <summary>
/// Is this is an _ identifier in a context where discards are allowed?
/// </summary>
private static bool FallBackOnDiscard(IdentifierNameSyntax node, DiagnosticBag diagnostics)
{
if (node.Identifier.ContextualKind() != SyntaxKind.UnderscoreToken)
{
return false;
}
CSharpSyntaxNode containingDeconstruction = node.GetContainingDeconstruction();
bool isDiscard = containingDeconstruction != null || IsOutVarDiscardIdentifier(node);
if (isDiscard)
{
CheckFeatureAvailability(node, MessageID.IDS_FeatureTuples, diagnostics);
}
return isDiscard;
}
private static bool IsOutVarDiscardIdentifier(SimpleNameSyntax node)
{
Debug.Assert(node.Identifier.ContextualKind() == SyntaxKind.UnderscoreToken);
CSharpSyntaxNode parent = node.Parent;
return (parent?.Kind() == SyntaxKind.Argument &&
((ArgumentSyntax)parent).RefOrOutKeyword.Kind() == SyntaxKind.OutKeyword);
}
private BoundExpression SynthesizeMethodGroupReceiver(CSharpSyntaxNode syntax, ArrayBuilder<Symbol> members)
{
// SPEC: For each instance type T starting with the instance type of the immediately
// SPEC: enclosing type declaration, and continuing with the instance type of each
// SPEC: enclosing class or struct declaration, [do a lot of things to find a match].
// SPEC: ...
// SPEC: If T is the instance type of the immediately enclosing class or struct type
// SPEC: and the lookup identifies one or more methods, the result is a method group
// SPEC: with an associated instance expression of this.
// Explanation of spec:
//
// We are looping over a set of types, from inner to outer, attempting to resolve the
// meaning of a simple name; for example "M(123)".
//
// There are a number of possibilities:
//
// If the lookup finds M in an outer class:
//
// class Outer {
// static void M(int x) {}
// class Inner {
// void X() { M(123); }
// }
// }
//
// or the base class of an outer class:
//
// class Base {
// public static void M(int x) {}
// }
// class Outer : Base {
// class Inner {
// void X() { M(123); }
// }
// }
//
// Then there is no "associated instance expression" of the method group. That is, there
// is no possibility of there being an "implicit this".
//
// If the lookup finds M on the class that triggered the lookup on the other hand, or
// one of its base classes:
//
// class Base {
// public static void M(int x) {}
// }
// class Derived : Base {
// void X() { M(123); }
// }
//
// Then the associated instance expression is "this" *even if one or more methods in the
// method group are static*. If it turns out that the method was static, then we'll
// check later to determine if there was a receiver actually present in the source code
// or not. (That happens during the "final validation" phase of overload resolution.
// Implementation explanation:
//
// If we're here, then lookup has identified one or more methods.
Debug.Assert(members.Count > 0);
// The lookup implementation loops over the set of types from inner to outer, and stops
// when it makes a match. (This is correct because any matches found on more-outer types
// would be hidden, and discarded.) This means that we only find members associated with
// one containing class or struct. The method is possibly on that type directly, or via
// inheritance from a base type of the type.
//
// The question then is what the "associated instance expression" is; is it "this" or
// nothing at all? If the type that we found the method on is the current type, or is a
// base type of the current type, then there should be a "this" associated with the
// method group. Otherwise, it should be null.
var currentType = this.ContainingType;
if ((object)currentType == null)
{
// This may happen if there is no containing type,
// e.g. we are binding an expression in an assembly-level attribute
return null;
}
var declaringType = members[0].ContainingType;
HashSet<DiagnosticInfo> unused = null;
if (currentType.IsEqualToOrDerivedFrom(declaringType, TypeCompareKind.ConsiderEverything, useSiteDiagnostics: ref unused) ||
(currentType.IsInterface && (declaringType.IsObjectType() || currentType.AllInterfacesNoUseSiteDiagnostics.Contains(declaringType))))
{
return ThisReference(syntax, currentType, wasCompilerGenerated: true);
}
else
{
return TryBindInteractiveReceiver(syntax, ContainingMember(), currentType, declaringType);
}
}
private bool IsBadLocalOrParameterCapture(Symbol symbol, TypeSymbol type, RefKind refKind)
{
if (refKind != RefKind.None || type.IsRefLikeType)
{
var containingMethod = this.ContainingMemberOrLambda as MethodSymbol;
if ((object)containingMethod != null && (object)symbol.ContainingSymbol != (object)containingMethod)
{
// Not expecting symbol from constructed method.
Debug.Assert(!symbol.ContainingSymbol.Equals(containingMethod));
// Captured in a lambda.
return (containingMethod.MethodKind == MethodKind.AnonymousFunction || containingMethod.MethodKind == MethodKind.LocalFunction) && !IsInsideNameof; // false in EE evaluation method
}
}
return false;
}
private BoundExpression BindNonMethod(SimpleNameSyntax node, Symbol symbol, DiagnosticBag diagnostics, LookupResultKind resultKind, bool indexed, bool isError)
{
// Events are handled later as we don't know yet if we are binding to the event or it's backing field.
if (symbol.Kind != SymbolKind.Event)
{
ReportDiagnosticsIfObsolete(diagnostics, symbol, node, hasBaseReceiver: false);
}
switch (symbol.Kind)
{
case SymbolKind.Local:
{
var localSymbol = (LocalSymbol)symbol;
Location localSymbolLocation = localSymbol.Locations[0];
TypeSymbol type;
bool isNullableUnknown;
if (node.SyntaxTree == localSymbolLocation.SourceTree &&
node.SpanStart < localSymbolLocation.SourceSpan.Start)
{
// Here we report a local variable being used before its declaration
//
// There are two possible diagnostics for this:
//
// CS0841: ERR_VariableUsedBeforeDeclaration
// Cannot use local variable 'x' before it is declared
//
// CS0844: ERR_VariableUsedBeforeDeclarationAndHidesField
// Cannot use local variable 'x' before it is declared. The
// declaration of the local variable hides the field 'C.x'.
//
// There are two situations in which we give these errors.
//
// First, the scope of a local variable -- that is, the region of program
// text in which it can be looked up by name -- is throughout the entire
// block which declares it. It is therefore possible to use a local
// before it is declared, which is an error.
//
// As an additional help to the user, we give a special error for this
// scenario:
//
// class C {
// int x;
// void M() {
// Print(x);
// int x = 5;
// } }
//
// Because a too-clever C++ user might be attempting to deliberately
// bind to "this.x" in the "Print". (In C++ the local does not come
// into scope until its declaration.)
//
FieldSymbol possibleField = null;
var lookupResult = LookupResult.GetInstance();
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
this.LookupMembersInType(
lookupResult,
ContainingType,
localSymbol.Name,
arity: 0,
basesBeingResolved: null,
options: LookupOptions.Default,
originalBinder: this,
diagnose: false,
useSiteDiagnostics: ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
possibleField = lookupResult.SingleSymbolOrDefault as FieldSymbol;
lookupResult.Free();
if ((object)possibleField != null)
{
Error(diagnostics, ErrorCode.ERR_VariableUsedBeforeDeclarationAndHidesField, node, node, possibleField);
}
else
{
Error(diagnostics, ErrorCode.ERR_VariableUsedBeforeDeclaration, node, node);
}
type = new ExtendedErrorTypeSymbol(
this.Compilation, name: "var", arity: 0, errorInfo: null, variableUsedBeforeDeclaration: true);
isNullableUnknown = true;
}
else if ((localSymbol as SourceLocalSymbol)?.IsVar == true && localSymbol.ForbiddenZone?.Contains(node) == true)
{
// A var (type-inferred) local variable has been used in its own initialization (the "forbidden zone").
// There are many cases where this occurs, including:
//
// 1. var x = M(out x);
// 2. M(out var x, out x);
// 3. var (x, y) = (y, x);
//
// localSymbol.ForbiddenDiagnostic provides a suitable diagnostic for whichever case applies.
//
diagnostics.Add(localSymbol.ForbiddenDiagnostic, node.Location, node);
type = new ExtendedErrorTypeSymbol(
this.Compilation, name: "var", arity: 0, errorInfo: null, variableUsedBeforeDeclaration: true);
isNullableUnknown = true;
}
else
{
type = localSymbol.Type;
isNullableUnknown = false;
if (IsBadLocalOrParameterCapture(localSymbol, type, localSymbol.RefKind))
{
isError = true;
Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUseLocal, node, localSymbol);
}
}
var constantValueOpt = localSymbol.IsConst && !IsInsideNameof && !type.IsErrorType()
? localSymbol.GetConstantValue(node, this.LocalInProgress, diagnostics) : null;
return new BoundLocal(node, localSymbol, BoundLocalDeclarationKind.None, constantValueOpt: constantValueOpt, isNullableUnknown: isNullableUnknown, type: type, hasErrors: isError);
}
case SymbolKind.Parameter:
{
var parameter = (ParameterSymbol)symbol;
if (IsBadLocalOrParameterCapture(parameter, parameter.Type, parameter.RefKind))
{
isError = true;
Error(diagnostics, ErrorCode.ERR_AnonDelegateCantUse, node, parameter.Name);
}
return new BoundParameter(node, parameter, hasErrors: isError);
}
case SymbolKind.NamedType:
case SymbolKind.ErrorType:
case SymbolKind.TypeParameter:
// If I identifies a type, then the result is that type constructed with the
// given type arguments. UNDONE: Construct the child type if it is generic!
return new BoundTypeExpression(node, null, (TypeSymbol)symbol, hasErrors: isError);
case SymbolKind.Property:
{
BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics);
return BindPropertyAccess(node, receiver, (PropertySymbol)symbol, diagnostics, resultKind, hasErrors: isError);
}
case SymbolKind.Event:
{
BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics);
return BindEventAccess(node, receiver, (EventSymbol)symbol, diagnostics, resultKind, hasErrors: isError);
}
case SymbolKind.Field:
{
BoundExpression receiver = SynthesizeReceiver(node, symbol, diagnostics);
return BindFieldAccess(node, receiver, (FieldSymbol)symbol, diagnostics, resultKind, indexed, hasErrors: isError);
}
case SymbolKind.Namespace:
return new BoundNamespaceExpression(node, (NamespaceSymbol)symbol, hasErrors: isError);
case SymbolKind.Alias:
{
var alias = (AliasSymbol)symbol;
symbol = alias.Target;
switch (symbol.Kind)
{
case SymbolKind.NamedType:
case SymbolKind.ErrorType:
return new BoundTypeExpression(node, alias, (NamedTypeSymbol)symbol, hasErrors: isError);
case SymbolKind.Namespace:
return new BoundNamespaceExpression(node, (NamespaceSymbol)symbol, alias, hasErrors: isError);
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
}
case SymbolKind.RangeVariable:
return BindRangeVariable(node, (RangeVariableSymbol)symbol, diagnostics);
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
}
protected virtual BoundExpression BindRangeVariable(SimpleNameSyntax node, RangeVariableSymbol qv, DiagnosticBag diagnostics)
{
return Next.BindRangeVariable(node, qv, diagnostics);
}
private BoundExpression SynthesizeReceiver(SyntaxNode node, Symbol member, DiagnosticBag diagnostics)
{
// SPEC: Otherwise, if T is the instance type of the immediately enclosing class or
// struct type, if the lookup identifies an instance member, and if the reference occurs
// within the block of an instance constructor, an instance method, or an instance
// accessor, the result is the same as a member access of the form this.I. This can only
// happen when K is zero.
if (member.IsStatic)
{
return null;
}
var currentType = this.ContainingType;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
NamedTypeSymbol declaringType = member.ContainingType;
if (currentType.IsEqualToOrDerivedFrom(declaringType, TypeCompareKind.ConsiderEverything, useSiteDiagnostics: ref useSiteDiagnostics) ||
(currentType.IsInterface && (declaringType.IsObjectType() || currentType.AllInterfacesNoUseSiteDiagnostics.Contains(declaringType))))
{
bool hasErrors = false;
if (EnclosingNameofArgument != node)
{
if (InFieldInitializer && !currentType.IsScriptClass)
{
//can't access "this" in field initializers
Error(diagnostics, ErrorCode.ERR_FieldInitRefNonstatic, node, member);
hasErrors = true;
}
else if (InConstructorInitializer || InAttributeArgument)
{
//can't access "this" in constructor initializers or attribute arguments
Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, member);
hasErrors = true;
}
else
{
// not an instance member if the container is a type, like when binding default parameter values.
var containingMember = ContainingMember();
bool locationIsInstanceMember = !containingMember.IsStatic &&
(containingMember.Kind != SymbolKind.NamedType || currentType.IsScriptClass);
if (!locationIsInstanceMember)
{
// error CS0120: An object reference is required for the non-static field, method, or property '{0}'
Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, member);
hasErrors = true;
}
}
hasErrors = hasErrors || IsRefOrOutThisParameterCaptured(node, diagnostics);
}
return ThisReference(node, currentType, hasErrors, wasCompilerGenerated: true);
}
else
{
return TryBindInteractiveReceiver(node, ContainingMember(), currentType, declaringType);
}
}
internal Symbol ContainingMember()
{
// We skip intervening lambdas and local functions to find the actual member.
var containingMember = this.ContainingMemberOrLambda;
while (containingMember.Kind != SymbolKind.NamedType && (object)containingMember.ContainingSymbol != null && containingMember.ContainingSymbol.Kind != SymbolKind.NamedType)
{
containingMember = containingMember.ContainingSymbol;
}
return containingMember;
}
private BoundExpression TryBindInteractiveReceiver(SyntaxNode syntax, Symbol currentMember, NamedTypeSymbol currentType, NamedTypeSymbol memberDeclaringType)
{
if (currentType.TypeKind == TypeKind.Submission && !currentMember.IsStatic)
{
if (memberDeclaringType.TypeKind == TypeKind.Submission)
{
return new BoundPreviousSubmissionReference(syntax, memberDeclaringType) { WasCompilerGenerated = true };
}
else
{
TypeSymbol hostObjectType = Compilation.GetHostObjectTypeSymbol();
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
if ((object)hostObjectType != null && hostObjectType.IsEqualToOrDerivedFrom(memberDeclaringType, TypeCompareKind.ConsiderEverything, useSiteDiagnostics: ref useSiteDiagnostics))
{
return new BoundHostObjectMemberReference(syntax, hostObjectType) { WasCompilerGenerated = true };
}
}
}
return null;
}
public BoundExpression BindNamespaceOrTypeOrExpression(ExpressionSyntax node, DiagnosticBag diagnostics)
{
if (node.Kind() == SyntaxKind.PredefinedType)
{
return this.BindNamespaceOrType(node, diagnostics);
}
if (SyntaxFacts.IsName(node.Kind()))
{
if (SyntaxFacts.IsNamespaceAliasQualifier(node))
{
return this.BindNamespaceAlias((IdentifierNameSyntax)node, diagnostics);
}
else if (SyntaxFacts.IsInNamespaceOrTypeContext(node))
{
return this.BindNamespaceOrType(node, diagnostics);
}
}
else if (SyntaxFacts.IsTypeSyntax(node.Kind()))
{
return this.BindNamespaceOrType(node, diagnostics);
}
return this.BindExpression(node, diagnostics, SyntaxFacts.IsInvoked(node), SyntaxFacts.IsIndexed(node));
}
public BoundExpression BindLabel(ExpressionSyntax node, DiagnosticBag diagnostics)
{
var name = node as IdentifierNameSyntax;
if (name == null)
{
Debug.Assert(node.ContainsDiagnostics);
return BadExpression(node, LookupResultKind.NotLabel);
}
var result = LookupResult.GetInstance();
string labelName = name.Identifier.ValueText;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
this.LookupSymbolsWithFallback(result, labelName, arity: 0, useSiteDiagnostics: ref useSiteDiagnostics, options: LookupOptions.LabelsOnly);
diagnostics.Add(node, useSiteDiagnostics);
if (!result.IsMultiViable)
{
Error(diagnostics, ErrorCode.ERR_LabelNotFound, node, labelName);
result.Free();
return BadExpression(node, result.Kind);
}
Debug.Assert(result.IsSingleViable, "If this happens, we need to deal with multiple label definitions.");
var symbol = (LabelSymbol)result.Symbols.First();
result.Free();
return new BoundLabel(node, symbol, null);
}
public BoundExpression BindNamespaceOrType(ExpressionSyntax node, DiagnosticBag diagnostics)
{
var symbol = this.BindNamespaceOrTypeOrAliasSymbol(node, diagnostics, null, false);
return CreateBoundNamespaceOrTypeExpression(node, symbol.Symbol);
}
public BoundExpression BindNamespaceAlias(IdentifierNameSyntax node, DiagnosticBag diagnostics)
{
var symbol = this.BindNamespaceAliasSymbol(node, diagnostics);
return CreateBoundNamespaceOrTypeExpression(node, symbol);
}
private static BoundExpression CreateBoundNamespaceOrTypeExpression(ExpressionSyntax node, Symbol symbol)
{
var alias = symbol as AliasSymbol;
if ((object)alias != null)
{
symbol = alias.Target;
}
var type = symbol as TypeSymbol;
if ((object)type != null)
{
return new BoundTypeExpression(node, alias, type);
}
var namespaceSymbol = symbol as NamespaceSymbol;
if ((object)namespaceSymbol != null)
{
return new BoundNamespaceExpression(node, namespaceSymbol, alias);
}
throw ExceptionUtilities.UnexpectedValue(symbol);
}
private BoundThisReference BindThis(ThisExpressionSyntax node, DiagnosticBag diagnostics)
{
Debug.Assert(node != null);
bool hasErrors = true;
bool inStaticContext;
if (!HasThis(isExplicit: true, inStaticContext: out inStaticContext))
{
//this error is returned in the field initializer case
Error(diagnostics, inStaticContext ? ErrorCode.ERR_ThisInStaticMeth : ErrorCode.ERR_ThisInBadContext, node);
}
else
{
hasErrors = IsRefOrOutThisParameterCaptured(node.Token, diagnostics);
}
return ThisReference(node, this.ContainingType, hasErrors);
}
private BoundThisReference ThisReference(SyntaxNode node, NamedTypeSymbol thisTypeOpt, bool hasErrors = false, bool wasCompilerGenerated = false)
{
return new BoundThisReference(node, thisTypeOpt ?? CreateErrorType(), hasErrors) { WasCompilerGenerated = wasCompilerGenerated };
}
private bool IsRefOrOutThisParameterCaptured(SyntaxNodeOrToken thisOrBaseToken, DiagnosticBag diagnostics)
{
ParameterSymbol thisSymbol = this.ContainingMemberOrLambda.EnclosingThisSymbol();
// If there is no this parameter, then it is definitely not captured and
// any diagnostic would be cascading.
if ((object)thisSymbol != null && thisSymbol.ContainingSymbol != ContainingMemberOrLambda && thisSymbol.RefKind != RefKind.None)
{
Error(diagnostics, ErrorCode.ERR_ThisStructNotInAnonMeth, thisOrBaseToken);
return true;
}
return false;
}
private BoundBaseReference BindBase(BaseExpressionSyntax node, DiagnosticBag diagnostics)
{
bool hasErrors = false;
TypeSymbol baseType = this.ContainingType is null ? null : this.ContainingType.BaseTypeNoUseSiteDiagnostics;
bool inStaticContext;
if (!HasThis(isExplicit: true, inStaticContext: out inStaticContext))
{
//this error is returned in the field initializer case
Error(diagnostics, inStaticContext ? ErrorCode.ERR_BaseInStaticMeth : ErrorCode.ERR_BaseInBadContext, node.Token);
hasErrors = true;
}
else if ((object)baseType == null) // e.g. in System.Object
{
Error(diagnostics, ErrorCode.ERR_NoBaseClass, node);
hasErrors = true;
}
else if (this.ContainingType is null || (node.Parent.Kind() != SyntaxKind.SimpleMemberAccessExpression && node.Parent.Kind() != SyntaxKind.ElementAccessExpression))
{
Error(diagnostics, ErrorCode.ERR_BaseIllegal, node.Token);
hasErrors = true;
}
else if (IsRefOrOutThisParameterCaptured(node.Token, diagnostics))
{
// error has been reported by IsRefOrOutThisParameterCaptured
hasErrors = true;
}
return new BoundBaseReference(node, baseType, hasErrors);
}
private BoundExpression BindCast(CastExpressionSyntax node, DiagnosticBag diagnostics)
{
BoundExpression operand = this.BindValue(node.Expression, diagnostics, BindValueKind.RValue);
TypeWithAnnotations targetTypeWithAnnotations = this.BindType(node.Type, diagnostics);
TypeSymbol targetType = targetTypeWithAnnotations.Type;
if (targetType.IsNullableType() &&
!operand.HasAnyErrors &&
(object)operand.Type != null &&
!operand.Type.IsNullableType() &&
!TypeSymbol.Equals(targetType.GetNullableUnderlyingType(), operand.Type, TypeCompareKind.ConsiderEverything2))
{
return BindExplicitNullableCastFromNonNullable(node, operand, targetTypeWithAnnotations, diagnostics);
}
return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics);
}
private BoundExpression BindFromEndIndexExpression(PrefixUnaryExpressionSyntax node, DiagnosticBag diagnostics)
{
Debug.Assert(node.OperatorToken.IsKind(SyntaxKind.CaretToken));
CheckFeatureAvailability(node, MessageID.IDS_FeatureIndexOperator, diagnostics);
// Used in lowering as the second argument to the constructor. Example: new Index(value, fromEnd: true)
GetSpecialType(SpecialType.System_Boolean, diagnostics, node);
BoundExpression boundOperand = BindValue(node.Operand, diagnostics, BindValueKind.RValue);
TypeSymbol intType = GetSpecialType(SpecialType.System_Int32, diagnostics, node);
TypeSymbol indexType = GetWellKnownType(WellKnownType.System_Index, diagnostics, node);
if ((object)boundOperand.Type != null && boundOperand.Type.IsNullableType())
{
// Used in lowering to construct the nullable
GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, node);
NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node);
if (!indexType.IsNonNullableValueType())
{
Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, node, nullableType, nullableType.TypeParameters.Single(), indexType);
}
intType = nullableType.Construct(intType);
indexType = nullableType.Construct(indexType);
}
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(boundOperand, intType, ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
if (!conversion.IsValid)
{
GenerateImplicitConversionError(diagnostics, node, conversion, boundOperand, intType);
}
BoundExpression boundConversion = CreateConversion(boundOperand, conversion, intType, diagnostics);
MethodSymbol symbolOpt = GetWellKnownTypeMember(Compilation, WellKnownMember.System_Index__ctor, diagnostics, syntax: node) as MethodSymbol;
return new BoundFromEndIndexExpression(node, boundConversion, symbolOpt, indexType);
}
private BoundExpression BindRangeExpression(RangeExpressionSyntax node, DiagnosticBag diagnostics)
{
CheckFeatureAvailability(node, MessageID.IDS_FeatureRangeOperator, diagnostics);
TypeSymbol rangeType = GetWellKnownType(WellKnownType.System_Range, diagnostics, node);
MethodSymbol symbolOpt = null;
if (!rangeType.IsErrorType())
{
// Depending on the available arguments to the range expression, there are four
// possible well-known members we could bind to. The constructor is always the
// fallback member, usable in any situation. However, if any of the other members
// are available and applicable, we will prefer that.
WellKnownMember? memberOpt = null;
if (node.LeftOperand is null && node.RightOperand is null)
{
memberOpt = WellKnownMember.System_Range__get_All;
}
else if (node.LeftOperand is null)
{
memberOpt = WellKnownMember.System_Range__EndAt;
}
else if (node.RightOperand is null)
{
memberOpt = WellKnownMember.System_Range__StartAt;
}
if (!(memberOpt is null))
{
symbolOpt = (MethodSymbol)GetWellKnownTypeMember(
Compilation,
memberOpt.GetValueOrDefault(),
diagnostics,
syntax: node,
isOptional: true);
}
if (symbolOpt is null)
{
symbolOpt = (MethodSymbol)GetWellKnownTypeMember(
Compilation,
WellKnownMember.System_Range__ctor,
diagnostics,
syntax: node);
}
}
BoundExpression left = BindRangeExpressionOperand(node.LeftOperand, diagnostics);
BoundExpression right = BindRangeExpressionOperand(node.RightOperand, diagnostics);
if (left?.Type.IsNullableType() == true || right?.Type.IsNullableType() == true)
{
// Used in lowering to construct the nullable
GetSpecialType(SpecialType.System_Boolean, diagnostics, node);
GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, node);
NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node);
if (!rangeType.IsNonNullableValueType())
{
Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, node, nullableType, nullableType.TypeParameters.Single(), rangeType);
}
rangeType = nullableType.Construct(rangeType);
}
return new BoundRangeExpression(node, left, right, symbolOpt, rangeType);
}
private BoundExpression BindRangeExpressionOperand(ExpressionSyntax operand, DiagnosticBag diagnostics)
{
if (operand is null)
{
return null;
}
BoundExpression boundOperand = BindValue(operand, diagnostics, BindValueKind.RValue);
TypeSymbol indexType = GetWellKnownType(WellKnownType.System_Index, diagnostics, operand);
if (boundOperand.Type?.IsNullableType() == true)
{
// Used in lowering to construct the nullable
GetSpecialTypeMember(SpecialMember.System_Nullable_T__ctor, diagnostics, operand);
NamedTypeSymbol nullableType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, operand);
if (!indexType.IsNonNullableValueType())
{
Error(diagnostics, ErrorCode.ERR_ValConstraintNotSatisfied, operand, nullableType, nullableType.TypeParameters.Single(), indexType);
}
indexType = nullableType.Construct(indexType);
}
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(boundOperand, indexType, ref useSiteDiagnostics);
diagnostics.Add(operand, useSiteDiagnostics);
if (!conversion.IsValid)
{
GenerateImplicitConversionError(diagnostics, operand, conversion, boundOperand, indexType);
}
return CreateConversion(boundOperand, conversion, indexType, diagnostics);
}
private BoundExpression BindCastCore(ExpressionSyntax node, BoundExpression operand, TypeWithAnnotations targetTypeWithAnnotations, bool wasCompilerGenerated, DiagnosticBag diagnostics)
{
TypeSymbol targetType = targetTypeWithAnnotations.Type;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
Conversion conversion = this.Conversions.ClassifyConversionFromExpression(operand, targetType, ref useSiteDiagnostics, forCast: true);
diagnostics.Add(node, useSiteDiagnostics);
var conversionGroup = new ConversionGroup(conversion, targetTypeWithAnnotations);
if (operand.HasAnyErrors || targetType.IsErrorType() || !conversion.IsValid || targetType.IsStatic)
{
GenerateExplicitConversionErrors(diagnostics, node, conversion, operand, targetType);
return new BoundConversion(
node,
operand,
conversion,
@checked: CheckOverflowAtRuntime,
explicitCastInCode: true,
conversionGroup,
constantValueOpt: ConstantValue.NotAvailable,
type: targetType,
hasErrors: true);
}
return CreateConversion(node, operand, conversion, isCast: true, conversionGroup, wasCompilerGenerated: wasCompilerGenerated, destination: targetType, diagnostics: diagnostics);
}
private void GenerateExplicitConversionErrors(
DiagnosticBag diagnostics,
SyntaxNode syntax,
Conversion conversion,
BoundExpression operand,
TypeSymbol targetType)
{
// Make sure that errors within the unbound lambda don't get lost.
if (operand.Kind == BoundKind.UnboundLambda)
{
GenerateAnonymousFunctionConversionError(diagnostics, operand.Syntax, (UnboundLambda)operand, targetType);
return;
}
if (operand.HasAnyErrors || targetType.IsErrorType())
{
// an error has already been reported elsewhere
return;
}
if (targetType.IsStatic)
{
// The specification states in the section titled "Referencing Static
// Class Types" that it is always illegal to have a static class in a
// cast operator.
diagnostics.Add(ErrorCode.ERR_ConvertToStaticClass, syntax.Location, targetType);
return;
}
if (!targetType.IsReferenceType && !targetType.IsNullableType() && operand.IsLiteralNull())
{
diagnostics.Add(ErrorCode.ERR_ValueCantBeNull, syntax.Location, targetType);
return;
}
if (conversion.ResultKind == LookupResultKind.OverloadResolutionFailure)
{
Debug.Assert(conversion.IsUserDefined);
ImmutableArray<MethodSymbol> originalUserDefinedConversions = conversion.OriginalUserDefinedConversions;
if (originalUserDefinedConversions.Length > 1)
{
diagnostics.Add(ErrorCode.ERR_AmbigUDConv, syntax.Location, originalUserDefinedConversions[0], originalUserDefinedConversions[1], operand.Display, targetType);
}
else
{
Debug.Assert(originalUserDefinedConversions.Length == 0,
"How can there be exactly one applicable user-defined conversion if the conversion doesn't exist?");
SymbolDistinguisher distinguisher1 = new SymbolDistinguisher(this.Compilation, operand.Type, targetType);
diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, distinguisher1.First, distinguisher1.Second);
}
return;
}
switch (operand.Kind)
{
case BoundKind.MethodGroup:
{
if (targetType.TypeKind != TypeKind.Delegate ||
!MethodGroupConversionDoesNotExistOrHasErrors((BoundMethodGroup)operand, (NamedTypeSymbol)targetType, syntax.Location, diagnostics, out _))
{
diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, MessageID.IDS_SK_METHOD.Localize(), targetType);
}
return;
}
case BoundKind.TupleLiteral:
{
var tuple = (BoundTupleLiteral)operand;
var targetElementTypesWithAnnotations = default(ImmutableArray<TypeWithAnnotations>);
// If target is a tuple or compatible type with the same number of elements,
// report errors for tuple arguments that failed to convert, which would be more useful.
if (targetType.TryGetElementTypesWithAnnotationsIfTupleOrCompatible(out targetElementTypesWithAnnotations) &&
targetElementTypesWithAnnotations.Length == tuple.Arguments.Length)
{
GenerateExplicitConversionErrorsForTupleLiteralArguments(diagnostics, tuple.Arguments, targetElementTypesWithAnnotations);
return;
}
// target is not compatible with source and source does not have a type
if ((object)tuple.Type == null)
{
Error(diagnostics, ErrorCode.ERR_ConversionNotTupleCompatible, syntax, tuple.Arguments.Length, targetType);
return;
}
// Otherwise it is just a regular conversion failure from T1 to T2.
break;
}
case BoundKind.StackAllocArrayCreation:
{
var stackAllocExpression = (BoundStackAllocArrayCreation)operand;
Error(diagnostics, ErrorCode.ERR_StackAllocConversionNotPossible, syntax, stackAllocExpression.ElementType, targetType);
return;
}
}
Debug.Assert((object)operand.Type != null);
SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, operand.Type, targetType);
diagnostics.Add(ErrorCode.ERR_NoExplicitConv, syntax.Location, distinguisher.First, distinguisher.Second);
}
private void GenerateExplicitConversionErrorsForTupleLiteralArguments(
DiagnosticBag diagnostics,
ImmutableArray<BoundExpression> tupleArguments,
ImmutableArray<TypeWithAnnotations> targetElementTypesWithAnnotations)
{
// report all leaf elements of the tuple literal that failed to convert
// NOTE: we are not responsible for reporting use site errors here, just the failed leaf conversions.
// By the time we get here we have done analysis and know we have failed the cast in general, and diagnostics collected in the process is already in the bag.
// The only thing left is to form a diagnostics about the actually failing conversion(s).
// This whole method does not itself collect any usesite diagnostics. Its only purpose is to produce an error better than "conversion failed here"
HashSet<DiagnosticInfo> usDiagsUnused = null;
for (int i = 0; i < targetElementTypesWithAnnotations.Length; i++)
{
var argument = tupleArguments[i];
var targetElementType = targetElementTypesWithAnnotations[i].Type;
var elementConversion = Conversions.ClassifyConversionFromExpression(argument, targetElementType, ref usDiagsUnused);
if (!elementConversion.IsValid)
{
GenerateExplicitConversionErrors(diagnostics, argument.Syntax, elementConversion, argument, targetElementType);
}
}
}
/// <summary>
/// This implements the casting behavior described in section 6.2.3 of the spec:
///
/// - If the nullable conversion is from S to T?, the conversion is evaluated as the underlying conversion
/// from S to T followed by a wrapping from T to T?.
///
/// This particular check is done in the binder because it involves conversion processing rules (like overflow
/// checking and constant folding) which are not handled by Conversions.
/// </summary>
private BoundExpression BindExplicitNullableCastFromNonNullable(ExpressionSyntax node, BoundExpression operand, TypeWithAnnotations targetTypeWithAnnotations, DiagnosticBag diagnostics)
{
Debug.Assert(targetTypeWithAnnotations.HasType && targetTypeWithAnnotations.IsNullableType());
Debug.Assert((object)operand.Type != null && !operand.Type.IsNullableType());
// Section 6.2.3 of the spec only applies when the non-null version of the types involved have a
// built in conversion.
HashSet<DiagnosticInfo> unused = null;
TypeWithAnnotations underlyingTargetTypeWithAnnotations = targetTypeWithAnnotations.Type.GetNullableUnderlyingTypeWithAnnotations();
var underlyingConversion = Conversions.ClassifyBuiltInConversion(operand.Type, underlyingTargetTypeWithAnnotations.Type, ref unused);
if (!underlyingConversion.Exists)
{
return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics);
}
var bag = DiagnosticBag.GetInstance();
try
{
var underlyingExpr = BindCastCore(node, operand, underlyingTargetTypeWithAnnotations, wasCompilerGenerated: false, diagnostics: bag);
if (underlyingExpr.HasErrors || bag.HasAnyErrors())
{
Error(diagnostics, ErrorCode.ERR_NoExplicitConv, node, operand.Type, targetTypeWithAnnotations.Type);
return new BoundConversion(
node,
operand,
Conversion.NoConversion,
@checked: CheckOverflowAtRuntime,
explicitCastInCode: true,
conversionGroupOpt: new ConversionGroup(Conversion.NoConversion, explicitType: targetTypeWithAnnotations),
constantValueOpt: ConstantValue.NotAvailable,
type: targetTypeWithAnnotations.Type,
hasErrors: true);
}
// It's possible for the S -> T conversion to produce a 'better' constant value. If this
// constant value is produced place it in the tree so that it gets emitted. This maintains
// parity with the native compiler which also evaluated the conversion at compile time.
if (underlyingExpr.ConstantValue != null)
{
underlyingExpr.WasCompilerGenerated = true;
return BindCastCore(node, underlyingExpr, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics);
}
return BindCastCore(node, operand, targetTypeWithAnnotations, wasCompilerGenerated: operand.WasCompilerGenerated, diagnostics: diagnostics);
}
finally
{
bag.Free();
}
}
private static NameSyntax GetNameSyntax(SyntaxNode syntax)
{
string nameString;
return GetNameSyntax(syntax, out nameString);
}
/// <summary>
/// Gets the NameSyntax associated with the syntax node
/// If no syntax is attached it sets the nameString to plain text
/// name and returns a null NameSyntax
/// </summary>
/// <param name="syntax">Syntax node</param>
/// <param name="nameString">Plain text name</param>
internal static NameSyntax GetNameSyntax(SyntaxNode syntax, out string nameString)
{
nameString = string.Empty;
while (true)
{
switch (syntax.Kind())
{
case SyntaxKind.PredefinedType:
nameString = ((PredefinedTypeSyntax)syntax).Keyword.ValueText;
return null;
case SyntaxKind.SimpleLambdaExpression:
nameString = MessageID.IDS_Lambda.Localize().ToString();
return null;
case SyntaxKind.ParenthesizedExpression:
syntax = ((ParenthesizedExpressionSyntax)syntax).Expression;
continue;
case SyntaxKind.CastExpression:
syntax = ((CastExpressionSyntax)syntax).Expression;
continue;
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
return ((MemberAccessExpressionSyntax)syntax).Name;
case SyntaxKind.MemberBindingExpression:
return ((MemberBindingExpressionSyntax)syntax).Name;
default:
return syntax as NameSyntax;
}
}
}
/// <summary>
/// Gets the plain text name associated with the expression syntax node
/// </summary>
/// <param name="syntax">Expression syntax node</param>
/// <returns>Plain text name</returns>
private static string GetName(ExpressionSyntax syntax)
{
string nameString;
var nameSyntax = GetNameSyntax(syntax, out nameString);
if (nameSyntax != null)
{
return nameSyntax.GetUnqualifiedName().Identifier.ValueText;
}
return nameString;
}
// Given a list of arguments, create arrays of the bound arguments and the names of those
// arguments.
private void BindArgumentsAndNames(ArgumentListSyntax argumentListOpt, DiagnosticBag diagnostics, AnalyzedArguments result, bool allowArglist = false, bool isDelegateCreation = false)
{
if (argumentListOpt != null)
{
BindArgumentsAndNames(argumentListOpt.Arguments, diagnostics, result, allowArglist, isDelegateCreation: isDelegateCreation);
}
}
private void BindArgumentsAndNames(BracketedArgumentListSyntax argumentListOpt, DiagnosticBag diagnostics, AnalyzedArguments result)
{
if (argumentListOpt != null)
{
BindArgumentsAndNames(argumentListOpt.Arguments, diagnostics, result, allowArglist: false);
}
}
private void BindArgumentsAndNames(
SeparatedSyntaxList<ArgumentSyntax> arguments,
DiagnosticBag diagnostics,
AnalyzedArguments result,
bool allowArglist,
bool isDelegateCreation = false)
{
// Only report the first "duplicate name" or "named before positional" error,
// so as to avoid "cascading" errors.
bool hadError = false;
// Only report the first "non-trailing named args required C# 7.2" error,
// so as to avoid "cascading" errors.
bool hadLangVersionError = false;
foreach (var argumentSyntax in arguments)
{
BindArgumentAndName(result, diagnostics, ref hadError, ref hadLangVersionError,
argumentSyntax, allowArglist, isDelegateCreation: isDelegateCreation);
}
}
private bool RefMustBeObeyed(bool isDelegateCreation, ArgumentSyntax argumentSyntax)
{
if (Compilation.FeatureStrictEnabled || !isDelegateCreation)
{
return true;
}
switch (argumentSyntax.Expression.Kind())
{
// The next 3 cases should never be allowed as they cannot be ref/out. Assuming a bug in legacy compiler.
case SyntaxKind.ParenthesizedLambdaExpression:
case SyntaxKind.SimpleLambdaExpression:
case SyntaxKind.AnonymousMethodExpression:
case SyntaxKind.InvocationExpression:
case SyntaxKind.ObjectCreationExpression:
case SyntaxKind.ParenthesizedExpression: // this is never allowed in legacy compiler
case SyntaxKind.DeclarationExpression:
// A property/indexer is also invalid as it cannot be ref/out, but cannot be checked here. Assuming a bug in legacy compiler.
return true;
default:
// The only ones that concern us here for compat is: locals, params, fields
// BindArgumentAndName correctly rejects all other cases, except for properties and indexers.
// They are handled after BindArgumentAndName returns and the binding can be checked.
return false;
}
}
private void BindArgumentAndName(
AnalyzedArguments result,
DiagnosticBag diagnostics,
ref bool hadError,
ref bool hadLangVersionError,
ArgumentSyntax argumentSyntax,
bool allowArglist,
bool isDelegateCreation = false)
{
RefKind origRefKind = argumentSyntax.RefOrOutKeyword.Kind().GetRefKind();
// The old native compiler ignores ref/out in a delegate creation expression.
// For compatibility we implement the same bug except in strict mode.
// Note: Some others should still be rejected when ref/out present. See RefMustBeObeyed.
RefKind refKind = origRefKind == RefKind.None || RefMustBeObeyed(isDelegateCreation, argumentSyntax) ? origRefKind : RefKind.None;
BoundExpression boundArgument = BindArgumentValue(diagnostics, argumentSyntax, allowArglist, refKind);
BindArgumentAndName(
result,
diagnostics,
ref hadLangVersionError,
argumentSyntax,
boundArgument,
argumentSyntax.NameColon,
refKind);
// check for ref/out property/indexer, only needed for 1 parameter version
if (!hadError && isDelegateCreation && origRefKind != RefKind.None && result.Arguments.Count == 1)
{
var arg = result.Argument(0);
switch (arg.Kind)
{
case BoundKind.PropertyAccess:
case BoundKind.IndexerAccess:
var requiredValueKind = origRefKind == RefKind.In ? BindValueKind.ReadonlyRef : BindValueKind.RefOrOut;
hadError = !CheckValueKind(argumentSyntax, arg, requiredValueKind, false, diagnostics);
return;
}
}
if (argumentSyntax.RefOrOutKeyword.Kind() != SyntaxKind.None)
{
argumentSyntax.Expression.CheckDeconstructionCompatibleArgument(diagnostics);
}
}
private BoundExpression BindArgumentValue(DiagnosticBag diagnostics, ArgumentSyntax argumentSyntax, bool allowArglist, RefKind refKind)
{
if (argumentSyntax.Expression.Kind() == SyntaxKind.DeclarationExpression)
{
var declarationExpression = (DeclarationExpressionSyntax)argumentSyntax.Expression;
if (declarationExpression.IsOutDeclaration())
{
return BindOutDeclarationArgument(declarationExpression, diagnostics);
}
}
return BindArgumentExpression(diagnostics, argumentSyntax.Expression, refKind, allowArglist);
}
private BoundExpression BindOutDeclarationArgument(DeclarationExpressionSyntax declarationExpression, DiagnosticBag diagnostics)
{
TypeSyntax typeSyntax = declarationExpression.Type;
VariableDesignationSyntax designation = declarationExpression.Designation;
if (typeSyntax.GetRefKind() != RefKind.None)
{
diagnostics.Add(ErrorCode.ERR_OutVariableCannotBeByRef, declarationExpression.Type.Location);
}
switch (designation.Kind())
{
case SyntaxKind.DiscardDesignation:
{
bool isVar;
bool isConst = false;
AliasSymbol alias;
var declType = BindVariableTypeWithAnnotations(designation, diagnostics, typeSyntax, ref isConst, out isVar, out alias);
Debug.Assert(isVar != declType.HasType);
return new BoundDiscardExpression(declarationExpression, declType.Type);
}
case SyntaxKind.SingleVariableDesignation:
return BindOutVariableDeclarationArgument(declarationExpression, diagnostics);
default:
throw ExceptionUtilities.UnexpectedValue(designation.Kind());
}
}
private BoundExpression BindOutVariableDeclarationArgument(
DeclarationExpressionSyntax declarationExpression,
DiagnosticBag diagnostics)
{
Debug.Assert(declarationExpression.IsOutVarDeclaration());
bool isVar;
var designation = (SingleVariableDesignationSyntax)declarationExpression.Designation;
TypeSyntax typeSyntax = declarationExpression.Type;
// Is this a local?
SourceLocalSymbol localSymbol = this.LookupLocal(designation.Identifier);
if ((object)localSymbol != null)
{
Debug.Assert(localSymbol.DeclarationKind == LocalDeclarationKind.OutVariable);
if ((InConstructorInitializer || InFieldInitializer) && ContainingMemberOrLambda.ContainingSymbol.Kind == SymbolKind.NamedType)
{
CheckFeatureAvailability(declarationExpression, MessageID.IDS_FeatureExpressionVariablesInQueriesAndInitializers, diagnostics);
}
bool isConst = false;
AliasSymbol alias;
var declType = BindVariableTypeWithAnnotations(declarationExpression, diagnostics, typeSyntax, ref isConst, out isVar, out alias);
localSymbol.ScopeBinder.ValidateDeclarationNameConflictsInScope(localSymbol, diagnostics);
if (isVar)
{
return new OutVariablePendingInference(declarationExpression, localSymbol, null);
}
CheckRestrictedTypeInAsync(this.ContainingMemberOrLambda, declType.Type, diagnostics, typeSyntax);
return new BoundLocal(declarationExpression, localSymbol, BoundLocalDeclarationKind.WithExplicitType, constantValueOpt: null, isNullableUnknown: false, type: declType.Type);
}
// Is this a field?
GlobalExpressionVariable expressionVariableField = LookupDeclaredField(designation);
if ((object)expressionVariableField == null)
{
// We should have the right binder in the chain, cannot continue otherwise.
throw ExceptionUtilities.Unreachable;
}
BoundExpression receiver = SynthesizeReceiver(designation, expressionVariableField, diagnostics);
if (typeSyntax.IsVar)
{
var ignored = DiagnosticBag.GetInstance();
BindTypeOrAliasOrVarKeyword(typeSyntax, ignored, out isVar);
ignored.Free();
if (isVar)
{
return new OutVariablePendingInference(declarationExpression, expressionVariableField, receiver);
}
}
TypeSymbol fieldType = expressionVariableField.GetFieldType(this.FieldsBeingBound).Type;
return new BoundFieldAccess(declarationExpression,
receiver,
expressionVariableField,
null,
LookupResultKind.Viable,
isDeclaration: true,
type: fieldType);
}
/// <summary>
/// Returns true if a bad special by ref local was found.
/// </summary>
internal static bool CheckRestrictedTypeInAsync(Symbol containingSymbol, TypeSymbol type, DiagnosticBag diagnostics, SyntaxNode syntax)
{
if (containingSymbol.Kind == SymbolKind.Method
&& ((MethodSymbol)containingSymbol).IsAsync
&& type.IsRestrictedType())
{
Error(diagnostics, ErrorCode.ERR_BadSpecialByRefLocal, syntax, type);
return true;
}
return false;
}
internal GlobalExpressionVariable LookupDeclaredField(SingleVariableDesignationSyntax variableDesignator)
{
return LookupDeclaredField(variableDesignator, variableDesignator.Identifier.ValueText);
}
internal GlobalExpressionVariable LookupDeclaredField(SyntaxNode node, string identifier)
{
foreach (Symbol member in ContainingType?.GetMembers(identifier) ?? ImmutableArray<Symbol>.Empty)
{
GlobalExpressionVariable field;
if (member.Kind == SymbolKind.Field &&
(field = member as GlobalExpressionVariable)?.SyntaxTree == node.SyntaxTree &&
field.SyntaxNode == node)
{
return field;
}
}
return null;
}
// Bind a named/positional argument.
// Prevent cascading diagnostic by considering the previous
// error state and returning the updated error state.
private void BindArgumentAndName(
AnalyzedArguments result,
DiagnosticBag diagnostics,
ref bool hadLangVersionError,
CSharpSyntaxNode argumentSyntax,
BoundExpression boundArgumentExpression,
NameColonSyntax nameColonSyntax,
RefKind refKind)
{
Debug.Assert(argumentSyntax is ArgumentSyntax || argumentSyntax is AttributeArgumentSyntax);
bool hasRefKinds = result.RefKinds.Any();
if (refKind != RefKind.None)
{
// The common case is no ref or out arguments. So we defer all work until the first one is seen.
if (!hasRefKinds)
{
hasRefKinds = true;
int argCount = result.Arguments.Count;
for (int i = 0; i < argCount; ++i)
{
result.RefKinds.Add(RefKind.None);
}
}
}
if (hasRefKinds)
{
result.RefKinds.Add(refKind);
}
bool hasNames = result.Names.Any();
if (nameColonSyntax != null)
{
// The common case is no named arguments. So we defer all work until the first named argument is seen.
if (!hasNames)
{
hasNames = true;
int argCount = result.Arguments.Count;
for (int i = 0; i < argCount; ++i)
{
result.Names.Add(null);
}
}
result.Names.Add(nameColonSyntax.Name);
}
else if (hasNames)
{
// We just saw a fixed-position argument after a named argument.
if (!hadLangVersionError && !Compilation.LanguageVersion.AllowNonTrailingNamedArguments())
{
// CS1738: Named argument specifications must appear after all fixed arguments have been specified
Error(diagnostics, ErrorCode.ERR_NamedArgumentSpecificationBeforeFixedArgument, argumentSyntax,
new CSharpRequiredLanguageVersion(MessageID.IDS_FeatureNonTrailingNamedArguments.RequiredVersion()));
hadLangVersionError = true;
}
result.Names.Add(null);
}
result.Arguments.Add(boundArgumentExpression);
}
/// <summary>
/// Bind argument and verify argument matches rvalue or out param requirements.
/// </summary>
private BoundExpression BindArgumentExpression(DiagnosticBag diagnostics, ExpressionSyntax argumentExpression, RefKind refKind, bool allowArglist)
{
BindValueKind valueKind =
refKind == RefKind.None ?
BindValueKind.RValue :
refKind == RefKind.In ?
BindValueKind.ReadonlyRef :
BindValueKind.RefOrOut;
BoundExpression argument;
if (allowArglist)
{
argument = this.BindValueAllowArgList(argumentExpression, diagnostics, valueKind);
}
else
{
argument = this.BindValue(argumentExpression, diagnostics, valueKind);
}
return argument;
}
private void CoerceArguments<TMember>(
MemberResolutionResult<TMember> methodResult,
ArrayBuilder<BoundExpression> arguments,
DiagnosticBag diagnostics)
where TMember : Symbol
{
var result = methodResult.Result;
// Parameter types should be taken from the least overridden member:
var parameters = methodResult.LeastOverriddenMember.GetParameters();
for (int arg = 0; arg < arguments.Count; ++arg)
{
var kind = result.ConversionForArg(arg);
BoundExpression argument = arguments[arg];
if (!kind.IsIdentity || argument.Kind == BoundKind.TupleLiteral)
{
TypeWithAnnotations typeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg);
// NOTE: for some reason, dev10 doesn't report this for indexer accesses.
if (!methodResult.Member.IsIndexer() && !argument.HasAnyErrors && typeWithAnnotations.Type.IsUnsafe())
{
// CONSIDER: dev10 uses the call syntax, but this seems clearer.
ReportUnsafeIfNotAllowed(argument.Syntax, diagnostics);
//CONSIDER: Return a bad expression so that HasErrors is true?
}
arguments[arg] = CreateConversion(argument.Syntax, argument, kind, isCast: false, conversionGroupOpt: null, typeWithAnnotations.Type, diagnostics);
}
else if (argument.Kind == BoundKind.OutVariablePendingInference)
{
TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg);
arguments[arg] = ((OutVariablePendingInference)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations, diagnostics);
}
else if (argument.Kind == BoundKind.OutDeconstructVarPendingInference)
{
TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg);
arguments[arg] = ((OutDeconstructVarPendingInference)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations, this, success: true);
}
else if (argument.Kind == BoundKind.DiscardExpression && !argument.HasExpressionType())
{
TypeWithAnnotations parameterTypeWithAnnotations = GetCorrespondingParameterTypeWithAnnotations(ref result, parameters, arg);
Debug.Assert(parameterTypeWithAnnotations.HasType);
arguments[arg] = ((BoundDiscardExpression)argument).SetInferredTypeWithAnnotations(parameterTypeWithAnnotations);
}
}
}
private TypeWithAnnotations GetCorrespondingParameterTypeWithAnnotations(ref MemberAnalysisResult result, ImmutableArray<ParameterSymbol> parameters, int arg)
{
int paramNum = result.ParameterFromArgument(arg);
var type = parameters[paramNum].TypeWithAnnotations;
if (paramNum == parameters.Length - 1 && result.Kind == MemberResolutionKind.ApplicableInExpandedForm)
{
type = ((ArrayTypeSymbol)type.Type).ElementTypeWithAnnotations;
}
return type;
}
private BoundExpression BindArrayCreationExpression(ArrayCreationExpressionSyntax node, DiagnosticBag diagnostics)
{
// SPEC begins
//
// An array-creation-expression is used to create a new instance of an array-type.
//
// array-creation-expression:
// new non-array-type[expression-list] rank-specifiersopt array-initializeropt
// new array-type array-initializer
// new rank-specifier array-initializer
//
// An array creation expression of the first form allocates an array instance of the
// type that results from deleting each of the individual expressions from the
// expression list. For example, the array creation expression new int[10, 20] produces
// an array instance of type int[,], and the array creation expression new int[10][,]
// produces an array of type int[][,]. Each expression in the expression list must be of
// type int, uint, long, or ulong, or implicitly convertible to one or more of these
// types. The value of each expression determines the length of the corresponding
// dimension in the newly allocated array instance. Since the length of an array
// dimension must be nonnegative, it is a compile-time error to have a
// constant-expression with a negative value in the expression list.
//
// If an array creation expression of the first form includes an array initializer, each
// expression in the expression list must be a constant and the rank and dimension
// lengths specified by the expression list must match those of the array initializer.
//
// In an array creation expression of the second or third form, the rank of the
// specified array type or rank specifier must match that of the array initializer. The
// individual dimension lengths are inferred from the number of elements in each of the
// corresponding nesting levels of the array initializer. Thus, the expression new
// int[,] {{0, 1}, {2, 3}, {4, 5}} exactly corresponds to new int[3, 2] {{0, 1}, {2, 3},
// {4, 5}}
//
// An array creation expression of the third form is referred to as an implicitly typed
// array creation expression. It is similar to the second form, except that the element
// type of the array is not explicitly given, but determined as the best common type
// (7.5.2.14) of the set of expressions in the array initializer. For a multidimensional
// array, i.e., one where the rank-specifier contains at least one comma, this set
// comprises all expressions found in nested array-initializers.
//
// An array creation expression permits instantiation of an array with elements of an
// array type, but the elements of such an array must be manually initialized. For
// example, the statement
//
// int[][] a = new int[100][];
//
// creates a single-dimensional array with 100 elements of type int[]. The initial value
// of each element is null. It is not possible for the same array creation expression to
// also instantiate the sub-arrays, and the statement
//
// int[][] a = new int[100][5]; // Error
//
// results in a compile-time error.
//
// The following are examples of implicitly typed array creation expressions:
//
// var a = new[] { 1, 10, 100, 1000 }; // int[]
// var b = new[] { 1, 1.5, 2, 2.5 }; // double[]
// var c = new[,] { { "hello", null }, { "world", "!" } }; // string[,]
// var d = new[] { 1, "one", 2, "two" }; // Error
//
// The last expression causes a compile-time error because neither int nor string is
// implicitly convertible to the other, and so there is no best common type. An
// explicitly typed array creation expression must be used in this case, for example
// specifying the type to be object[]. Alternatively, one of the elements can be cast to
// a common base type, which would then become the inferred element type.
//
// SPEC ends
var type = (ArrayTypeSymbol)BindArrayType(node.Type, diagnostics, permitDimensions: true, basesBeingResolved: null, disallowRestrictedTypes: true).Type;
// CONSIDER:
//
// There may be erroneous rank specifiers in the source code, for example:
//
// int y = 123;
// int[][] z = new int[10][y];
//
// The "10" is legal but the "y" is not. If we are in such a situation we do have the
// "y" expression syntax stashed away in the syntax tree. However, we do *not* perform
// semantic analysis. This means that "go to definition" on "y" does not work, and so
// on. We might consider doing a semantic analysis here (with error suppression; a parse
// error has already been reported) so that "go to definition" works.
ArrayBuilder<BoundExpression> sizes = ArrayBuilder<BoundExpression>.GetInstance();
ArrayRankSpecifierSyntax firstRankSpecifier = node.Type.RankSpecifiers[0];
bool hasErrors = false;
foreach (var arg in firstRankSpecifier.Sizes)
{
var size = BindArrayDimension(arg, diagnostics, ref hasErrors);
if (size != null)
{
sizes.Add(size);
}
else if (node.Initializer is null && arg == firstRankSpecifier.Sizes[0])
{
Error(diagnostics, ErrorCode.ERR_MissingArraySize, firstRankSpecifier);
hasErrors = true;
}
}
// produce errors for additional sizes in the ranks
for (int additionalRankIndex = 1; additionalRankIndex < node.Type.RankSpecifiers.Count; additionalRankIndex++)
{
var rank = node.Type.RankSpecifiers[additionalRankIndex];
var dimension = rank.Sizes;
foreach (var arg in dimension)
{
if (arg.Kind() != SyntaxKind.OmittedArraySizeExpression)
{
var size = BindValue(arg, diagnostics, BindValueKind.RValue);
Error(diagnostics, ErrorCode.ERR_InvalidArray, dimension[0]);
hasErrors = true;
// Capture the invalid sizes for `SemanticModel` and `IOperation`
sizes.Add(size);
}
}
}
ImmutableArray<BoundExpression> arraySizes = sizes.ToImmutableAndFree();
return node.Initializer == null
? new BoundArrayCreation(node, arraySizes, null, type, hasErrors)
: BindArrayCreationWithInitializer(diagnostics, node, node.Initializer, type, arraySizes, hasErrors: hasErrors);
}
private BoundExpression BindArrayDimension(ExpressionSyntax dimension, DiagnosticBag diagnostics, ref bool hasErrors)
{
// These make the parse tree nicer, but they shouldn't actually appear in the bound tree.
if (dimension.Kind() != SyntaxKind.OmittedArraySizeExpression)
{
var size = BindValue(dimension, diagnostics, BindValueKind.RValue);
if (!size.HasAnyErrors)
{
size = ConvertToArrayIndex(size, dimension, diagnostics, allowIndexAndRange: false);
if (IsNegativeConstantForArraySize(size))
{
Error(diagnostics, ErrorCode.ERR_NegativeArraySize, dimension);
hasErrors = true;
}
}
return size;
}
return null;
}
private BoundExpression BindImplicitArrayCreationExpression(ImplicitArrayCreationExpressionSyntax node, DiagnosticBag diagnostics)
{
// See BindArrayCreationExpression method above for implicitly typed array creation SPEC.
InitializerExpressionSyntax initializer = node.Initializer;
int rank = node.Commas.Count + 1;
ImmutableArray<BoundExpression> boundInitializerExpressions = BindArrayInitializerExpressions(initializer, diagnostics, dimension: 1, rank: rank);
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
TypeSymbol bestType = BestTypeInferrer.InferBestType(boundInitializerExpressions, this.Conversions, ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
if ((object)bestType == null || bestType.IsVoidType()) // Dev10 also reports ERR_ImplicitlyTypedArrayNoBestType for void.
{
Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, node);
bestType = CreateErrorType();
}
if (bestType.IsRestrictedType())
{
// CS0611: Array elements cannot be of type '{0}'
Error(diagnostics, ErrorCode.ERR_ArrayElementCantBeRefAny, node, bestType);
}
// Element type nullability will be inferred in flow analysis and does not need to be set here.
var arrayType = ArrayTypeSymbol.CreateCSharpArray(Compilation.Assembly, TypeWithAnnotations.Create(bestType), rank);
return BindArrayCreationWithInitializer(diagnostics, node, initializer, arrayType,
sizes: ImmutableArray<BoundExpression>.Empty, boundInitExprOpt: boundInitializerExpressions);
}
private BoundExpression BindImplicitStackAllocArrayCreationExpression(ImplicitStackAllocArrayCreationExpressionSyntax node, DiagnosticBag diagnostics)
{
InitializerExpressionSyntax initializer = node.Initializer;
ImmutableArray<BoundExpression> boundInitializerExpressions = BindArrayInitializerExpressions(initializer, diagnostics, dimension: 1, rank: 1);
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
TypeSymbol bestType = BestTypeInferrer.InferBestType(boundInitializerExpressions, this.Conversions, ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
if ((object)bestType == null || bestType.IsVoidType())
{
Error(diagnostics, ErrorCode.ERR_ImplicitlyTypedArrayNoBestType, node);
bestType = CreateErrorType();
}
if (!bestType.IsErrorType())
{
CheckManagedAddr(bestType, node, diagnostics);
}
return BindStackAllocWithInitializer(
node,
initializer,
type: GetStackAllocType(node, TypeWithAnnotations.Create(bestType), diagnostics, out bool hasErrors),
elementType: bestType,
sizeOpt: null,
diagnostics,
hasErrors: hasErrors,
boundInitializerExpressions);
}
// This method binds all the array initializer expressions.
// NOTE: It doesn't convert the bound initializer expressions to array's element type.
// NOTE: This is done separately in ConvertAndBindArrayInitialization method below.
private ImmutableArray<BoundExpression> BindArrayInitializerExpressions(InitializerExpressionSyntax initializer, DiagnosticBag diagnostics, int dimension, int rank)
{
var exprBuilder = ArrayBuilder<BoundExpression>.GetInstance();
BindArrayInitializerExpressions(initializer, exprBuilder, diagnostics, dimension, rank);
return exprBuilder.ToImmutableAndFree();
}
/// <summary>
/// This method walks through the array's InitializerExpressionSyntax and binds all the initializer expressions recursively.
/// NOTE: It doesn't convert the bound initializer expressions to array's element type.
/// NOTE: This is done separately in ConvertAndBindArrayInitialization method below.
/// </summary>
/// <param name="initializer">Initializer Syntax.</param>
/// <param name="exprBuilder">Bound expression builder.</param>
/// <param name="diagnostics">Diagnostics.</param>
/// <param name="dimension">Current array dimension being processed.</param>
/// <param name="rank">Rank of the array type.</param>
private void BindArrayInitializerExpressions(InitializerExpressionSyntax initializer, ArrayBuilder<BoundExpression> exprBuilder, DiagnosticBag diagnostics, int dimension, int rank)
{
Debug.Assert(rank > 0);
Debug.Assert(dimension > 0 && dimension <= rank);
Debug.Assert(exprBuilder != null);
if (dimension == rank)
{
// We are processing the nth dimension of a rank-n array. We expect that these will
// only be values, not array initializers.
foreach (var expression in initializer.Expressions)
{
var boundExpression = BindValue(expression, diagnostics, BindValueKind.RValue);
exprBuilder.Add(boundExpression);
}
}
else
{
// Inductive case; we'd better have another array initializer
foreach (var expression in initializer.Expressions)
{
if (expression.Kind() == SyntaxKind.ArrayInitializerExpression)
{
BindArrayInitializerExpressions((InitializerExpressionSyntax)expression, exprBuilder, diagnostics, dimension + 1, rank);
}
else
{
// We have non-array initializer expression, but we expected an array initializer expression.
var boundExpression = BindValue(expression, diagnostics, BindValueKind.RValue);
if ((object)boundExpression.Type == null || !boundExpression.Type.IsErrorType())
{
if (!boundExpression.HasAnyErrors)
{
Error(diagnostics, ErrorCode.ERR_ArrayInitializerExpected, expression);
}
// Wrap the expression with a bound bad expression with error type.
boundExpression = BadExpression(
expression,
LookupResultKind.Empty,
ImmutableArray.Create(boundExpression.ExpressionSymbol),
ImmutableArray.Create(boundExpression));
}
exprBuilder.Add(boundExpression);
}
}
}
}
/// <summary>
/// Given an array of bound initializer expressions, this method converts these bound expressions
/// to array's element type and generates a BoundArrayInitialization with the converted initializers.
/// </summary>
/// <param name="diagnostics">Diagnostics.</param>
/// <param name="node">Initializer Syntax.</param>
/// <param name="type">Array type.</param>
/// <param name="knownSizes">Known array bounds.</param>
/// <param name="dimension">Current array dimension being processed.</param>
/// <param name="boundInitExpr">Array of bound initializer expressions.</param>
/// <param name="boundInitExprIndex">
/// Index into the array of bound initializer expressions to fetch the next bound expression.
/// </param>
/// <returns></returns>
private BoundArrayInitialization ConvertAndBindArrayInitialization(
DiagnosticBag diagnostics,
InitializerExpressionSyntax node,
ArrayTypeSymbol type,
int?[] knownSizes,
int dimension,
ImmutableArray<BoundExpression> boundInitExpr,
ref int boundInitExprIndex)
{
Debug.Assert(!boundInitExpr.IsDefault);
ArrayBuilder<BoundExpression> initializers = ArrayBuilder<BoundExpression>.GetInstance();
if (dimension == type.Rank)
{
// We are processing the nth dimension of a rank-n array. We expect that these will
// only be values, not array initializers.
TypeSymbol elemType = type.ElementType;
foreach (var expressionSyntax in node.Expressions)
{
Debug.Assert(boundInitExprIndex >= 0 && boundInitExprIndex < boundInitExpr.Length);
BoundExpression boundExpression = boundInitExpr[boundInitExprIndex];
boundInitExprIndex++;
BoundExpression convertedExpression = GenerateConversionForAssignment(elemType, boundExpression, diagnostics);
initializers.Add(convertedExpression);
}
}
else
{
// Inductive case; we'd better have another array initializer
foreach (var expr in node.Expressions)
{
BoundExpression init = null;
if (expr.Kind() == SyntaxKind.ArrayInitializerExpression)
{
init = ConvertAndBindArrayInitialization(diagnostics, (InitializerExpressionSyntax)expr,
type, knownSizes, dimension + 1, boundInitExpr, ref boundInitExprIndex);
}
else
{
// We have non-array initializer expression, but we expected an array initializer expression.
// We have already generated the diagnostics during binding, so just fetch the bound expression.
Debug.Assert(boundInitExprIndex >= 0 && boundInitExprIndex < boundInitExpr.Length);
init = boundInitExpr[boundInitExprIndex];
Debug.Assert(init.HasAnyErrors);
Debug.Assert(init.Type.IsErrorType());
boundInitExprIndex++;
}
initializers.Add(init);
}
}
bool hasErrors = false;
var knownSizeOpt = knownSizes[dimension - 1];
if (knownSizeOpt == null)
{
knownSizes[dimension - 1] = initializers.Count;
}
else if (knownSizeOpt != initializers.Count)
{
// No need to report an error if the known size is negative
// since we've already reported CS0248 earlier and it's
// expected that the number of initializers won't match.
if (knownSizeOpt >= 0)
{
Error(diagnostics, ErrorCode.ERR_ArrayInitializerIncorrectLength, node, knownSizeOpt.Value);
hasErrors = true;
}
}
return new BoundArrayInitialization(node, initializers.ToImmutableAndFree(), hasErrors: hasErrors);
}
private BoundArrayInitialization BindArrayInitializerList(
DiagnosticBag diagnostics,
InitializerExpressionSyntax node,
ArrayTypeSymbol type,
int?[] knownSizes,
int dimension,
ImmutableArray<BoundExpression> boundInitExprOpt = default(ImmutableArray<BoundExpression>))
{
// Bind the array initializer expressions, if not already bound.
// NOTE: Initializer expressions might already be bound for implicitly type array creation
// NOTE: during array's element type inference.
if (boundInitExprOpt.IsDefault)
{
boundInitExprOpt = BindArrayInitializerExpressions(node, diagnostics, dimension, type.Rank);
}
// Convert the bound array initializer expressions to array's element type and
// generate BoundArrayInitialization with the converted initializers.
int boundInitExprIndex = 0;
return ConvertAndBindArrayInitialization(diagnostics, node, type, knownSizes, dimension, boundInitExprOpt, ref boundInitExprIndex);
}
private BoundArrayInitialization BindUnexpectedArrayInitializer(
InitializerExpressionSyntax node,
DiagnosticBag diagnostics,
ErrorCode errorCode,
CSharpSyntaxNode errorNode = null)
{
var result = BindArrayInitializerList(
diagnostics,
node,
this.Compilation.CreateArrayTypeSymbol(GetSpecialType(SpecialType.System_Object, diagnostics, node)),
new int?[1],
dimension: 1);
if (!result.HasAnyErrors)
{
result = new BoundArrayInitialization(node, result.Initializers, hasErrors: true);
}
Error(diagnostics, errorCode, errorNode ?? node);
return result;
}
// We could be in the cases
//
// (1) int[] x = { a, b }
// (2) new int[] { a, b }
// (3) new int[2] { a, b }
// (4) new [] { a, b }
//
// In case (1) there is no creation syntax.
// In cases (2) and (3) creation syntax is an ArrayCreationExpression.
// In case (4) creation syntax is an ImplicitArrayCreationExpression.
//
// In cases (1), (2) and (4) there are no sizes.
//
// The initializer syntax is always provided.
//
// If we are in case (3) and sizes are provided then the number of sizes must match the rank
// of the array type passed in.
// For case (4), i.e. ImplicitArrayCreationExpression, we must have already bound the
// initializer expressions for best type inference.
// These bound expressions are stored in boundInitExprOpt and reused in creating
// BoundArrayInitialization to avoid binding them twice.
private BoundArrayCreation BindArrayCreationWithInitializer(
DiagnosticBag diagnostics,
ExpressionSyntax creationSyntax,
InitializerExpressionSyntax initSyntax,
ArrayTypeSymbol type,
ImmutableArray<BoundExpression> sizes,
ImmutableArray<BoundExpression> boundInitExprOpt = default(ImmutableArray<BoundExpression>),
bool hasErrors = false)
{
Debug.Assert(creationSyntax == null ||
creationSyntax.Kind() == SyntaxKind.ArrayCreationExpression ||
creationSyntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression);
Debug.Assert(initSyntax != null);
Debug.Assert((object)type != null);
Debug.Assert(boundInitExprOpt.IsDefault || creationSyntax.Kind() == SyntaxKind.ImplicitArrayCreationExpression);
// NOTE: In error scenarios, it may be the case sizes.Count > type.Rank.
// For example, new int[1 2] has 2 sizes, but rank 1 (since there are 0 commas).
int rank = type.Rank;
int numSizes = sizes.Length;
int?[] knownSizes = new int?[Math.Max(rank, numSizes)];
// If there are sizes given and there is an array initializer, then every size must be a
// constant. (We'll check later that it matches)
for (int i = 0; i < numSizes; ++i)
{
// Here we are being bug-for-bug compatible with C# 4. When you have code like
// byte[] b = new[uint.MaxValue] { 2 };
// you might expect an error that says that the number of elements in the initializer does
// not match the size of the array. But in C# 4 if the constant does not fit into an integer
// then we confusingly give the error "that's not a constant".
// NOTE: in the example above, GetIntegerConstantForArraySize is returning null because the
// size doesn't fit in an int - not because it doesn't match the initializer length.
var size = sizes[i];
knownSizes[i] = GetIntegerConstantForArraySize(size);
if (!size.HasAnyErrors && knownSizes[i] == null)
{
Error(diagnostics, ErrorCode.ERR_ConstantExpected, size.Syntax);
hasErrors = true;
}
}
// KnownSizes is further mutated by BindArrayInitializerList as it works out more
// information about the sizes.
BoundArrayInitialization initializer = BindArrayInitializerList(diagnostics, initSyntax, type, knownSizes, 1, boundInitExprOpt);
hasErrors = hasErrors || initializer.HasAnyErrors;
bool hasCreationSyntax = creationSyntax != null;
CSharpSyntaxNode nonNullSyntax = (CSharpSyntaxNode)creationSyntax ?? initSyntax;
// Construct a set of size expressions if we were not given any.
//
// It is possible in error scenarios that some of the bounds were not determined. Substitute
// zeroes for those.
if (numSizes == 0)
{
BoundExpression[] sizeArray = new BoundExpression[rank];
for (int i = 0; i < rank; i++)
{
sizeArray[i] = new BoundLiteral(
nonNullSyntax,
ConstantValue.Create(knownSizes[i] ?? 0),
GetSpecialType(SpecialType.System_Int32, diagnostics, nonNullSyntax))
{ WasCompilerGenerated = true };
}
sizes = sizeArray.AsImmutableOrNull();
}
else if (!hasErrors && rank != numSizes)
{
Error(diagnostics, ErrorCode.ERR_BadIndexCount, nonNullSyntax, type.Rank);
hasErrors = true;
}
return new BoundArrayCreation(nonNullSyntax, sizes, initializer, type, hasErrors: hasErrors)
{
WasCompilerGenerated = !hasCreationSyntax &&
(initSyntax.Parent == null ||
initSyntax.Parent.Kind() != SyntaxKind.EqualsValueClause ||
((EqualsValueClauseSyntax)initSyntax.Parent).Value != initSyntax)
};
}
private BoundExpression BindStackAllocArrayCreationExpression(
StackAllocArrayCreationExpressionSyntax node, DiagnosticBag diagnostics)
{
TypeSyntax typeSyntax = node.Type;
if (typeSyntax.Kind() != SyntaxKind.ArrayType)
{
Error(diagnostics, ErrorCode.ERR_BadStackAllocExpr, typeSyntax);
return new BoundBadExpression(
node,
LookupResultKind.NotCreatable, //in this context, anyway
ImmutableArray<Symbol>.Empty,
ImmutableArray<BoundExpression>.Empty,
new PointerTypeSymbol(BindType(typeSyntax, diagnostics)));
}
ArrayTypeSyntax arrayTypeSyntax = (ArrayTypeSyntax)typeSyntax;
var elementTypeSyntax = arrayTypeSyntax.ElementType;
var arrayType = (ArrayTypeSymbol)BindArrayType(arrayTypeSyntax, diagnostics, permitDimensions: true, basesBeingResolved: null, disallowRestrictedTypes: false).Type;
var elementType = arrayType.ElementTypeWithAnnotations;
TypeSymbol type = GetStackAllocType(node, elementType, diagnostics, out bool hasErrors);
if (!elementType.Type.IsErrorType())
{
hasErrors = hasErrors || CheckManagedAddr(elementType.Type, elementTypeSyntax, diagnostics);
}
SyntaxList<ArrayRankSpecifierSyntax> rankSpecifiers = arrayTypeSyntax.RankSpecifiers;
if (rankSpecifiers.Count != 1 ||
rankSpecifiers[0].Sizes.Count != 1)
{
// NOTE: Dev10 reported several parse errors here.
Error(diagnostics, ErrorCode.ERR_BadStackAllocExpr, typeSyntax);
var builder = ArrayBuilder<BoundExpression>.GetInstance();
var discardedDiagnostics = DiagnosticBag.GetInstance();
foreach (ArrayRankSpecifierSyntax rankSpecifier in rankSpecifiers)
{
foreach (ExpressionSyntax size in rankSpecifier.Sizes)
{
if (size.Kind() != SyntaxKind.OmittedArraySizeExpression)
{
builder.Add(BindExpression(size, discardedDiagnostics));
}
}
}
discardedDiagnostics.Free();
return new BoundBadExpression(
node,
LookupResultKind.Empty,
ImmutableArray<Symbol>.Empty,
builder.ToImmutableAndFree(),
new PointerTypeSymbol(elementType));
}
ExpressionSyntax countSyntax = rankSpecifiers[0].Sizes[0];
BoundExpression count = null;
if (countSyntax.Kind() != SyntaxKind.OmittedArraySizeExpression)
{
count = BindValue(countSyntax, diagnostics, BindValueKind.RValue);
if (!count.HasAnyErrors)
{
// NOTE: this is different from how we would bind an array size (in which case we would allow uint, long, or ulong).
count = GenerateConversionForAssignment(GetSpecialType(SpecialType.System_Int32, diagnostics, node), count, diagnostics);
if (!count.HasAnyErrors && IsNegativeConstantForArraySize(count))
{
Error(diagnostics, ErrorCode.ERR_NegativeStackAllocSize, countSyntax);
hasErrors = true;
}
}
}
else if (node.Initializer == null)
{
Error(diagnostics, ErrorCode.ERR_MissingArraySize, rankSpecifiers[0]);
count = BadExpression(countSyntax);
hasErrors = true;
}
return node.Initializer == null
? new BoundStackAllocArrayCreation(node, elementType.Type, count, initializerOpt: null, type, hasErrors: hasErrors)
: BindStackAllocWithInitializer(node, node.Initializer, type, elementType.Type, count, diagnostics, hasErrors);
}
private bool ReportBadStackAllocPosition(SyntaxNode node, DiagnosticBag diagnostics)
{
Debug.Assert(node is StackAllocArrayCreationExpressionSyntax || node is ImplicitStackAllocArrayCreationExpressionSyntax);
bool inLegalPosition = true;
// If we are using a language version that does not restrict the position of a stackalloc expression, skip that test.
LanguageVersion requiredVersion = MessageID.IDS_FeatureNestedStackalloc.RequiredVersion();
if (requiredVersion > Compilation.LanguageVersion)
{
inLegalPosition = (IsInMethodBody || IsLocalFunctionsScopeBinder) && node.IsLegalCSharp73SpanStackAllocPosition();
if (!inLegalPosition)
{
MessageID.IDS_FeatureNestedStackalloc.CheckFeatureAvailability(diagnostics, node.GetFirstToken().GetLocation());
}
}
// Check if we're syntactically within a catch or finally clause.
if (this.Flags.IncludesAny(BinderFlags.InCatchBlock | BinderFlags.InCatchFilter | BinderFlags.InFinallyBlock))
{
Error(diagnostics, ErrorCode.ERR_StackallocInCatchFinally, node);
}
return inLegalPosition;
}
private TypeSymbol GetStackAllocType(SyntaxNode node, TypeWithAnnotations elementTypeWithAnnotations, DiagnosticBag diagnostics, out bool hasErrors)
{
var inLegalPosition = ReportBadStackAllocPosition(node, diagnostics);
hasErrors = !inLegalPosition;
if (inLegalPosition && !node.IsLocalVariableDeclarationInitializationForPointerStackalloc())
{
CheckFeatureAvailability(node, MessageID.IDS_FeatureRefStructs, diagnostics);
var spanType = GetWellKnownType(WellKnownType.System_Span_T, diagnostics, node);
if (!spanType.IsErrorType())
{
return ConstructNamedType(
type: spanType,
typeSyntax: node.Kind() == SyntaxKind.StackAllocArrayCreationExpression
? ((StackAllocArrayCreationExpressionSyntax)node).Type
: node,
typeArgumentsSyntax: default,
typeArguments: ImmutableArray.Create(elementTypeWithAnnotations),
basesBeingResolved: null,
diagnostics: diagnostics);
}
}
return null;
}
private BoundExpression BindStackAllocWithInitializer(
SyntaxNode node,
InitializerExpressionSyntax initSyntax,
TypeSymbol type,
TypeSymbol elementType,
BoundExpression sizeOpt,
DiagnosticBag diagnostics,
bool hasErrors,
ImmutableArray<BoundExpression> boundInitExprOpt = default)
{
if (boundInitExprOpt.IsDefault)
{
boundInitExprOpt = BindArrayInitializerExpressions(initSyntax, diagnostics, dimension: 1, rank: 1);
}
boundInitExprOpt = boundInitExprOpt.SelectAsArray((expr, t) => GenerateConversionForAssignment(t.elementType, expr, t.diagnostics), (elementType, diagnostics));
if (sizeOpt != null)
{
if (!sizeOpt.HasAnyErrors)
{
int? constantSizeOpt = GetIntegerConstantForArraySize(sizeOpt);
if (constantSizeOpt == null)
{
Error(diagnostics, ErrorCode.ERR_ConstantExpected, sizeOpt.Syntax);
hasErrors = true;
}
else if (boundInitExprOpt.Length != constantSizeOpt)
{
Error(diagnostics, ErrorCode.ERR_ArrayInitializerIncorrectLength, node, constantSizeOpt.Value);
hasErrors = true;
}
}
}
else
{
sizeOpt = new BoundLiteral(
node,
ConstantValue.Create(boundInitExprOpt.Length),
GetSpecialType(SpecialType.System_Int32, diagnostics, node))
{ WasCompilerGenerated = true };
}
return new BoundStackAllocArrayCreation(node, elementType, sizeOpt, new BoundArrayInitialization(initSyntax, boundInitExprOpt), type, hasErrors);
}
private static int? GetIntegerConstantForArraySize(BoundExpression expression)
{
// If the bound could have been converted to int, then it was. If it could not have been
// converted to int, and it was a constant, then it was out of range.
Debug.Assert(expression != null);
if (expression.HasAnyErrors)
{
return null;
}
var constantValue = expression.ConstantValue;
if (constantValue == null || constantValue.IsBad || expression.Type.SpecialType != SpecialType.System_Int32)
{
return null;
}
return constantValue.Int32Value;
}
private static bool IsNegativeConstantForArraySize(BoundExpression expression)
{
Debug.Assert(expression != null);
if (expression.HasAnyErrors)
{
return false;
}
var constantValue = expression.ConstantValue;
if (constantValue == null || constantValue.IsBad)
{
return false;
}
var type = expression.Type.SpecialType;
if (type == SpecialType.System_Int32)
{
return constantValue.Int32Value < 0;
}
if (type == SpecialType.System_Int64)
{
return constantValue.Int64Value < 0;
}
// By the time we get here we definitely have int, long, uint or ulong. Obviously the
// latter two are never negative.
Debug.Assert(type == SpecialType.System_UInt32 || type == SpecialType.System_UInt64);
return false;
}
/// <summary>
/// Bind the (implicit or explicit) constructor initializer of a constructor symbol (in source).
/// </summary>
/// <param name="initializerArgumentListOpt">
/// Null for implicit,
/// BaseConstructorInitializerSyntax.ArgumentList, or
/// ThisConstructorInitializerSyntax.ArgumentList, or
/// BaseClassWithArgumentsSyntax.ArgumentList for explicit.</param>
/// <param name="constructor">Constructor containing the initializer.</param>
/// <param name="diagnostics">Accumulates errors (e.g. unable to find constructor to invoke).</param>
/// <returns>A bound expression for the constructor initializer call.</returns>
/// <remarks>
/// This method should be kept consistent with Compiler.BindConstructorInitializer (e.g. same error codes).
/// </remarks>
internal BoundExpression BindConstructorInitializer(
ArgumentListSyntax initializerArgumentListOpt,
MethodSymbol constructor,
DiagnosticBag diagnostics)
{
Binder argumentListBinder = null;
if (initializerArgumentListOpt != null)
{
argumentListBinder = this.GetBinder(initializerArgumentListOpt);
}
var result = (argumentListBinder ?? this).BindConstructorInitializerCore(initializerArgumentListOpt, constructor, diagnostics);
if (argumentListBinder != null)
{
// This code is reachable only for speculative SemanticModel.
Debug.Assert(argumentListBinder.IsSemanticModelBinder);
result = argumentListBinder.WrapWithVariablesIfAny(initializerArgumentListOpt, result);
}
return result;
}
private BoundExpression BindConstructorInitializerCore(
ArgumentListSyntax initializerArgumentListOpt,
MethodSymbol constructor,
DiagnosticBag diagnostics)
{
// Either our base type is not object, or we have an initializer syntax, or both. We're going to
// need to do overload resolution on the set of constructors of the base type, either on
// the provided initializer syntax, or on an implicit ": base()" syntax.
// SPEC ERROR: The specification states that if you have the situation
// SPEC ERROR: class B { ... } class D1 : B {} then the default constructor
// SPEC ERROR: generated for D1 must call an accessible *parameterless* constructor
// SPEC ERROR: in B. However, it also states that if you have
// SPEC ERROR: class B { ... } class D2 : B { D2() {} } or
// SPEC ERROR: class B { ... } class D3 : B { D3() : base() {} } then
// SPEC ERROR: the compiler performs *overload resolution* to determine
// SPEC ERROR: which accessible constructor of B is called. Since B might have
// SPEC ERROR: a ctor with all optional parameters, overload resolution might
// SPEC ERROR: succeed even if there is no parameterless constructor. This
// SPEC ERROR: is unintentionally inconsistent, and the native compiler does not
// SPEC ERROR: implement this behavior. Rather, we should say in the spec that
// SPEC ERROR: if there is no ctor in D1, then a ctor is created for you exactly
// SPEC ERROR: as though you'd said "D1() : base() {}".
// SPEC ERROR: This is what we now do in Roslyn.
Debug.Assert((object)constructor != null);
Debug.Assert(constructor.MethodKind == MethodKind.Constructor ||
constructor.MethodKind == MethodKind.StaticConstructor); // error scenario: constructor initializer on static constructor
Debug.Assert(diagnostics != null);
NamedTypeSymbol containingType = constructor.ContainingType;
// Structs and enums do not have implicit constructor initializers.
if ((containingType.TypeKind == TypeKind.Enum || containingType.TypeKind == TypeKind.Struct) && initializerArgumentListOpt == null)
{
return null;
}
AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance();
try
{
TypeSymbol constructorReturnType = constructor.ReturnType;
Debug.Assert(constructorReturnType.IsVoidType()); //true of all constructors
// Get the bound arguments and the argument names.
// : this(__arglist()) is legal
if (initializerArgumentListOpt != null)
{
this.BindArgumentsAndNames(initializerArgumentListOpt, diagnostics, analyzedArguments, allowArglist: true);
}
NamedTypeSymbol initializerType = containingType;
bool isBaseConstructorInitializer = initializerArgumentListOpt == null ||
initializerArgumentListOpt.Parent.Kind() == SyntaxKind.BaseConstructorInitializer;
if (isBaseConstructorInitializer)
{
initializerType = initializerType.BaseTypeNoUseSiteDiagnostics;
// Soft assert: we think this is the case, and we're asserting to catch scenarios that violate our expectations
Debug.Assert((object)initializerType != null ||
containingType.SpecialType == SpecialType.System_Object ||
containingType.IsInterface);
if ((object)initializerType == null || containingType.SpecialType == SpecialType.System_Object) //e.g. when defining System.Object in source
{
// If the constructor initializer is implicit and there is no base type, we're done.
// Otherwise, if the constructor initializer is explicit, we're in an error state.
if (initializerArgumentListOpt == null)
{
return null;
}
else
{
diagnostics.Add(ErrorCode.ERR_ObjectCallingBaseConstructor, constructor.Locations[0], containingType);
return new BoundBadExpression(
syntax: initializerArgumentListOpt.Parent,
resultKind: LookupResultKind.Empty,
symbols: ImmutableArray<Symbol>.Empty,
childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments),
type: constructorReturnType);
}
}
else if (initializerArgumentListOpt != null && containingType.TypeKind == TypeKind.Struct)
{
diagnostics.Add(ErrorCode.ERR_StructWithBaseConstructorCall, constructor.Locations[0], containingType);
return new BoundBadExpression(
syntax: initializerArgumentListOpt.Parent,
resultKind: LookupResultKind.Empty,
symbols: ImmutableArray<Symbol>.Empty, //CONSIDER: we could look for a matching constructor on System.ValueType
childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments),
type: constructorReturnType);
}
}
else
{
Debug.Assert(initializerArgumentListOpt.Parent.Kind() == SyntaxKind.ThisConstructorInitializer);
}
if (initializerArgumentListOpt != null && analyzedArguments.HasDynamicArgument)
{
diagnostics.Add(ErrorCode.ERR_NoDynamicPhantomOnBaseCtor,
((ConstructorInitializerSyntax)initializerArgumentListOpt.Parent).ThisOrBaseKeyword.GetLocation());
return new BoundBadExpression(
syntax: initializerArgumentListOpt.Parent,
resultKind: LookupResultKind.Empty,
symbols: ImmutableArray<Symbol>.Empty, //CONSIDER: we could look for a matching constructor on System.ValueType
childBoundNodes: BuildArgumentsForErrorRecovery(analyzedArguments),
type: constructorReturnType);
}
CSharpSyntaxNode nonNullSyntax;
Location errorLocation;
if (initializerArgumentListOpt != null)
{
nonNullSyntax = initializerArgumentListOpt.Parent;
errorLocation = ((ConstructorInitializerSyntax)nonNullSyntax).ThisOrBaseKeyword.GetLocation();
}
else
{
// Note: use syntax node of constructor with initializer, not constructor invoked by initializer (i.e. methodResolutionResult).
nonNullSyntax = constructor.GetNonNullSyntaxNode();
errorLocation = constructor.Locations[0];
}
BoundExpression receiver = ThisReference(nonNullSyntax, initializerType, wasCompilerGenerated: true);
MemberResolutionResult<MethodSymbol> memberResolutionResult;
ImmutableArray<MethodSymbol> candidateConstructors;
if (TryPerformConstructorOverloadResolution(
initializerType,
analyzedArguments,
WellKnownMemberNames.InstanceConstructorName,
errorLocation,
false, // Don't suppress result diagnostics
diagnostics,
out memberResolutionResult,
out candidateConstructors,
allowProtectedConstructorsOfBaseType: true))
{
bool hasErrors = false;
MethodSymbol resultMember = memberResolutionResult.Member;
if (resultMember == constructor)
{
Debug.Assert(initializerType.IsErrorType() ||
(initializerArgumentListOpt != null && initializerArgumentListOpt.Parent.Kind() == SyntaxKind.ThisConstructorInitializer));
diagnostics.Add(ErrorCode.ERR_RecursiveConstructorCall,
((ConstructorInitializerSyntax)initializerArgumentListOpt.Parent).ThisOrBaseKeyword.GetLocation(),
constructor);
hasErrors = true; // prevent recursive constructor from being emitted
}
else if (resultMember.HasUnsafeParameter())
{
// What if some of the arguments are implicit? Dev10 reports unsafe errors
// if the implied argument would have an unsafe type. We need to check
// the parameters explicitly, since there won't be bound nodes for the implied
// arguments until lowering.
// Don't worry about double reporting (i.e. for both the argument and the parameter)
// because only one unsafe diagnostic is allowed per scope - the others are suppressed.
hasErrors = ReportUnsafeIfNotAllowed(errorLocation, diagnostics);
}
ReportDiagnosticsIfObsolete(diagnostics, resultMember, nonNullSyntax, hasBaseReceiver: isBaseConstructorInitializer);
var arguments = analyzedArguments.Arguments.ToImmutable();
var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull();
var argsToParamsOpt = memberResolutionResult.Result.ArgsToParamsOpt;
if (!hasErrors)
{
hasErrors = !CheckInvocationArgMixing(
nonNullSyntax,
resultMember,
receiver,
resultMember.Parameters,
arguments,
argsToParamsOpt,
this.LocalScopeDepth,
diagnostics);
}
return new BoundCall(
nonNullSyntax,
receiver,
resultMember,
arguments,
analyzedArguments.GetNames(),
refKinds,
isDelegateCall: false,
expanded: memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm,
invokedAsExtensionMethod: false,
argsToParamsOpt: argsToParamsOpt,
resultKind: LookupResultKind.Viable,
binderOpt: this,
type: constructorReturnType,
hasErrors: hasErrors)
{ WasCompilerGenerated = initializerArgumentListOpt == null };
}
else
{
var result = CreateBadCall(
node: nonNullSyntax,
name: WellKnownMemberNames.InstanceConstructorName,
receiver: receiver,
methods: candidateConstructors,
resultKind: LookupResultKind.OverloadResolutionFailure,
typeArgumentsWithAnnotations: ImmutableArray<TypeWithAnnotations>.Empty,
analyzedArguments: analyzedArguments,
invokedAsExtensionMethod: false,
isDelegate: false);
result.WasCompilerGenerated = initializerArgumentListOpt == null;
return result;
}
}
finally
{
analyzedArguments.Free();
}
}
protected BoundExpression BindObjectCreationExpression(ObjectCreationExpressionSyntax node, DiagnosticBag diagnostics)
{
var typeWithAnnotations = BindType(node.Type, diagnostics);
var type = typeWithAnnotations.Type;
var originalType = type;
if (typeWithAnnotations.NullableAnnotation.IsAnnotated() && !type.IsNullableType())
{
diagnostics.Add(ErrorCode.ERR_AnnotationDisallowedInObjectCreation, node.Location, type);
}
switch (type.TypeKind)
{
case TypeKind.Struct:
case TypeKind.Class:
case TypeKind.Enum:
case TypeKind.Error:
return BindClassCreationExpression(node, (NamedTypeSymbol)type, GetName(node.Type), diagnostics, originalType);
case TypeKind.Delegate:
return BindDelegateCreationExpression(node, (NamedTypeSymbol)type, diagnostics);
case TypeKind.Interface:
return BindInterfaceCreationExpression(node, (NamedTypeSymbol)type, diagnostics);
case TypeKind.TypeParameter:
return BindTypeParameterCreationExpression(node, (TypeParameterSymbol)type, diagnostics);
case TypeKind.Submission:
// script class is synthesized and should not be used as a type of a new expression:
throw ExceptionUtilities.UnexpectedValue(type.TypeKind);
case TypeKind.Pointer:
type = new ExtendedErrorTypeSymbol(type, LookupResultKind.NotCreatable,
diagnostics.Add(ErrorCode.ERR_UnsafeTypeInObjectCreation, node.Location, type));
goto case TypeKind.Class;
case TypeKind.Dynamic:
// we didn't find any type called "dynamic" so we are using the builtin dynamic type, which has no constructors:
case TypeKind.Array:
// ex: new ref[]
type = new ExtendedErrorTypeSymbol(type, LookupResultKind.NotCreatable,
diagnostics.Add(ErrorCode.ERR_InvalidObjectCreation, node.Type.Location, type));
goto case TypeKind.Class;
default:
throw ExceptionUtilities.UnexpectedValue(type.TypeKind);
}
}
private BoundExpression BindDelegateCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, DiagnosticBag diagnostics)
{
// Get the bound arguments and the argument names.
AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance();
try
{
BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, isDelegateCreation: true);
bool hasErrors = false;
if (analyzedArguments.HasErrors)
{
// Let's skip this part of further error checking without marking hasErrors = true here,
// as the argument could be an unbound lambda, and the error could come from inside.
// We'll check analyzedArguments.HasErrors again after we find if this is not the case.
}
else if (node.ArgumentList == null || analyzedArguments.Arguments.Count == 0)
{
diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, node.Location, type, 0);
hasErrors = true;
}
else if (analyzedArguments.Names.Count != 0 || analyzedArguments.RefKinds.Count != 0 || analyzedArguments.Arguments.Count != 1)
{
// Use a smaller span that excludes the parens.
var argSyntax = analyzedArguments.Arguments[0].Syntax;
var start = argSyntax.SpanStart;
var end = analyzedArguments.Arguments[analyzedArguments.Arguments.Count - 1].Syntax.Span.End;
var errorSpan = new TextSpan(start, end - start);
var loc = new SourceLocation(argSyntax.SyntaxTree, errorSpan);
diagnostics.Add(ErrorCode.ERR_MethodNameExpected, loc);
hasErrors = true;
}
if (node.Initializer != null)
{
Error(diagnostics, ErrorCode.ERR_ObjectOrCollectionInitializerWithDelegateCreation, node);
hasErrors = true;
}
BoundExpression argument = analyzedArguments.Arguments.Count >= 1 ? analyzedArguments.Arguments[0] : null;
if (hasErrors)
{
// skip the rest of this binding
}
// There are four cases for a delegate creation expression (7.6.10.5):
// 1. An anonymous function is treated as a conversion from the anonymous function to the delegate type.
else if (argument is UnboundLambda)
{
// analyzedArguments.HasErrors could be true,
// but here the argument is an unbound lambda, the error comes from inside
// eg: new Action<int>(x => x.)
// We should try to bind it anyway in order for intellisense to work.
UnboundLambda unboundLambda = (UnboundLambda)argument;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
var conversion = this.Conversions.ClassifyConversionFromExpression(unboundLambda, type, ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
// Attempting to make the conversion caches the diagnostics and the bound state inside
// the unbound lambda. Fetch the result from the cache.
BoundLambda boundLambda = unboundLambda.Bind(type);
if (!conversion.IsImplicit || !conversion.IsValid)
{
GenerateImplicitConversionError(diagnostics, unboundLambda.Syntax, conversion, unboundLambda, type);
}
else
{
// We're not going to produce an error, but it is possible that the conversion from
// the lambda to the delegate type produced a warning, which we have not reported.
// Instead, we've cached it in the bound lambda. Report it now.
diagnostics.AddRange(boundLambda.Diagnostics);
}
// Just stuff the bound lambda into the delegate creation expression. When we lower the lambda to
// its method form we will rewrite this expression to refer to the method.
return new BoundDelegateCreationExpression(node, boundLambda, methodOpt: null, isExtensionMethod: false, type: type, hasErrors: !conversion.IsImplicit);
}
else if (analyzedArguments.HasErrors)
{
// There is no hope, skip.
}
// 2. A method group
else if (argument.Kind == BoundKind.MethodGroup)
{
Conversion conversion;
BoundMethodGroup methodGroup = (BoundMethodGroup)argument;
hasErrors = MethodGroupConversionDoesNotExistOrHasErrors(methodGroup, type, node.Location, diagnostics, out conversion);
methodGroup = FixMethodGroupWithTypeOrValue(methodGroup, conversion, diagnostics);
return new BoundDelegateCreationExpression(node, methodGroup, conversion.Method, conversion.IsExtensionMethod, type, hasErrors);
}
else if ((object)argument.Type == null)
{
diagnostics.Add(ErrorCode.ERR_MethodNameExpected, argument.Syntax.Location);
}
// 3. A value of the compile-time type dynamic (which is dynamically case 4), or
else if (argument.HasDynamicType())
{
return new BoundDelegateCreationExpression(node, argument, methodOpt: null, isExtensionMethod: false, type: type);
}
// 4. A delegate type.
else if (argument.Type.TypeKind == TypeKind.Delegate)
{
var sourceDelegate = (NamedTypeSymbol)argument.Type;
MethodGroup methodGroup = MethodGroup.GetInstance();
try
{
if (ReportDelegateInvokeUseSiteDiagnostic(diagnostics, argument.Type, node: node))
{
// We want failed "new" expression to use the constructors as their symbols.
return new BoundBadExpression(node, LookupResultKind.NotInvocable, StaticCast<Symbol>.From(type.InstanceConstructors), ImmutableArray.Create(argument), type);
}
methodGroup.PopulateWithSingleMethod(argument, sourceDelegate.DelegateInvokeMethod);
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
Conversion conv = Conversions.MethodGroupConversion(argument.Syntax, methodGroup, type, ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
if (!conv.Exists)
{
var boundMethodGroup = new BoundMethodGroup(
argument.Syntax, default, WellKnownMemberNames.DelegateInvokeName, ImmutableArray.Create(sourceDelegate.DelegateInvokeMethod),
sourceDelegate.DelegateInvokeMethod, null, BoundMethodGroupFlags.None, argument, LookupResultKind.Viable);
if (!Conversions.ReportDelegateMethodGroupDiagnostics(this, boundMethodGroup, type, diagnostics))
{
// If we could not produce a more specialized diagnostic, we report
// No overload for '{0}' matches delegate '{1}'
diagnostics.Add(ErrorCode.ERR_MethDelegateMismatch, node.Location,
sourceDelegate.DelegateInvokeMethod,
type);
}
}
else
{
Debug.Assert(!conv.IsExtensionMethod);
Debug.Assert(conv.IsValid); // i.e. if it exists, then it is valid.
if (!this.MethodGroupConversionHasErrors(argument.Syntax, conv, argument, conv.IsExtensionMethod, type, diagnostics))
{
// we do not place the "Invoke" method in the node, indicating that it did not appear in source.
return new BoundDelegateCreationExpression(node, argument, methodOpt: null, isExtensionMethod: false, type: type);
}
}
}
finally
{
methodGroup.Free();
}
}
// Not a valid delegate creation expression
else
{
diagnostics.Add(ErrorCode.ERR_MethodNameExpected, argument.Syntax.Location);
}
// Note that we want failed "new" expression to use the constructors as their symbols.
var childNodes = BuildArgumentsForErrorRecovery(analyzedArguments);
return new BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, StaticCast<Symbol>.From(type.InstanceConstructors), childNodes, type);
}
finally
{
analyzedArguments.Free();
}
}
private BoundExpression BindClassCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, string typeName, DiagnosticBag diagnostics, TypeSymbol initializerType = null)
{
// Get the bound arguments and the argument names.
AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance();
try
{
// new C(__arglist()) is legal
BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: true);
// No point in performing overload resolution if the type is static or a tuple literal.
// Just return a bad expression containing the arguments.
if (type.IsStatic)
{
diagnostics.Add(ErrorCode.ERR_InstantiatingStaticClass, node.Location, type);
return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, diagnostics);
}
else if (node.Type.Kind() == SyntaxKind.TupleType)
{
diagnostics.Add(ErrorCode.ERR_NewWithTupleTypeSyntax, node.Type.GetLocation());
return MakeBadExpressionForObjectCreation(node, type, analyzedArguments, diagnostics);
}
return BindClassCreationExpression(node, typeName, node.Type, type, analyzedArguments, diagnostics, node.Initializer, initializerType);
}
finally
{
analyzedArguments.Free();
}
}
private BoundExpression MakeBadExpressionForObjectCreation(ObjectCreationExpressionSyntax node, TypeSymbol type, AnalyzedArguments analyzedArguments, DiagnosticBag diagnostics)
{
var children = ArrayBuilder<BoundExpression>.GetInstance();
children.AddRange(BuildArgumentsForErrorRecovery(analyzedArguments));
if (node.Initializer != null)
{
var boundInitializer = BindInitializerExpression(syntax: node.Initializer,
type: type,
typeSyntax: node.Type,
diagnostics: diagnostics);
children.Add(boundInitializer);
}
return new BoundBadExpression(node, LookupResultKind.NotCreatable, ImmutableArray.Create<Symbol>(type), children.ToImmutableAndFree(), type);
}
private BoundObjectInitializerExpressionBase BindInitializerExpression(
InitializerExpressionSyntax syntax,
TypeSymbol type,
SyntaxNode typeSyntax,
DiagnosticBag diagnostics)
{
Debug.Assert(syntax != null);
Debug.Assert((object)type != null);
switch (syntax.Kind())
{
case SyntaxKind.ObjectInitializerExpression:
{
var implicitReceiver = new BoundImplicitReceiver(typeSyntax, type) { WasCompilerGenerated = true };
return BindObjectInitializerExpression(syntax, type, diagnostics, implicitReceiver);
}
case SyntaxKind.CollectionInitializerExpression:
{
var implicitReceiver = new BoundImplicitReceiver(typeSyntax, type) { WasCompilerGenerated = true };
return BindCollectionInitializerExpression(syntax, type, diagnostics, implicitReceiver);
}
default:
throw ExceptionUtilities.Unreachable;
}
}
private BoundExpression BindInitializerExpressionOrValue(
ExpressionSyntax syntax,
TypeSymbol type,
SyntaxNode typeSyntax,
DiagnosticBag diagnostics)
{
Debug.Assert(syntax != null);
Debug.Assert((object)type != null);
switch (syntax.Kind())
{
case SyntaxKind.ObjectInitializerExpression:
case SyntaxKind.CollectionInitializerExpression:
return BindInitializerExpression((InitializerExpressionSyntax)syntax, type, typeSyntax, diagnostics);
default:
return BindValue(syntax, diagnostics, BindValueKind.RValue);
}
}
private BoundObjectInitializerExpression BindObjectInitializerExpression(
InitializerExpressionSyntax initializerSyntax,
TypeSymbol initializerType,
DiagnosticBag diagnostics,
BoundImplicitReceiver implicitReceiver)
{
// SPEC: 7.6.10.2 Object initializers
//
// SPEC: An object initializer consists of a sequence of member initializers, enclosed by { and } tokens and separated by commas.
// SPEC: Each member initializer must name an accessible field or property of the object being initialized, followed by an equals sign and
// SPEC: an expression or an object initializer or collection initializer.
Debug.Assert(initializerSyntax.Kind() == SyntaxKind.ObjectInitializerExpression);
Debug.Assert((object)initializerType != null);
var initializerBuilder = ArrayBuilder<BoundExpression>.GetInstance();
// Member name map to report duplicate assignments to a field/property.
var memberNameMap = new HashSet<string>();
// We use a location specific binder for binding object initializer field/property access to generate object initializer specific diagnostics:
// 1) CS1914 (ERR_StaticMemberInObjectInitializer)
// 2) CS1917 (ERR_ReadonlyValueTypeInObjectInitializer)
// 3) CS1918 (ERR_ValueTypePropertyInObjectInitializer)
// Note that this is only used for the LHS of the assignment - these diagnostics do not apply on the RHS.
// For this reason, we will actually need two binders: this and this.WithAdditionalFlags.
var objectInitializerMemberBinder = this.WithAdditionalFlags(BinderFlags.ObjectInitializerMember);
foreach (var memberInitializer in initializerSyntax.Expressions)
{
BoundExpression boundMemberInitializer = BindObjectInitializerMemberAssignment(
memberInitializer, initializerType, objectInitializerMemberBinder, diagnostics, implicitReceiver);
initializerBuilder.Add(boundMemberInitializer);
ReportDuplicateObjectMemberInitializers(boundMemberInitializer, memberNameMap, diagnostics);
}
return new BoundObjectInitializerExpression(initializerSyntax, initializerBuilder.ToImmutableAndFree(), initializerType);
}
private BoundExpression BindObjectInitializerMemberAssignment(
ExpressionSyntax memberInitializer,
TypeSymbol initializerType,
Binder objectInitializerMemberBinder,
DiagnosticBag diagnostics,
BoundImplicitReceiver implicitReceiver)
{
// SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (spec 7.17.1) to the field or property.
if (memberInitializer.Kind() == SyntaxKind.SimpleAssignmentExpression)
{
var initializer = (AssignmentExpressionSyntax)memberInitializer;
// Bind member initializer identifier, i.e. left part of assignment
BoundExpression boundLeft = null;
var leftSyntax = initializer.Left;
if (initializerType.IsDynamic() && leftSyntax.Kind() == SyntaxKind.IdentifierName)
{
{
// D = { ..., <identifier> = <expr>, ... }, where D : dynamic
var memberName = ((IdentifierNameSyntax)leftSyntax).Identifier.Text;
boundLeft = new BoundDynamicObjectInitializerMember(leftSyntax, memberName, implicitReceiver.Type, initializerType, hasErrors: false);
}
}
else
{
// We use a location specific binder for binding object initializer field/property access to generate object initializer specific diagnostics:
// 1) CS1914 (ERR_StaticMemberInObjectInitializer)
// 2) CS1917 (ERR_ReadonlyValueTypeInObjectInitializer)
// 3) CS1918 (ERR_ValueTypePropertyInObjectInitializer)
// See comments in BindObjectInitializerExpression for more details.
Debug.Assert(objectInitializerMemberBinder != null);
Debug.Assert(objectInitializerMemberBinder.Flags.Includes(BinderFlags.ObjectInitializerMember));
boundLeft = objectInitializerMemberBinder.BindObjectInitializerMember(initializer, implicitReceiver, diagnostics);
}
if (boundLeft != null)
{
Debug.Assert((object)boundLeft.Type != null);
// Bind member initializer value, i.e. right part of assignment
BoundExpression boundRight = BindInitializerExpressionOrValue(
syntax: initializer.Right,
type: boundLeft.Type,
typeSyntax: boundLeft.Syntax,
diagnostics: diagnostics);
// Bind member initializer assignment expression
return BindAssignment(initializer, boundLeft, boundRight, isRef: false, diagnostics);
}
}
var boundExpression = BindValue(memberInitializer, diagnostics, BindValueKind.RValue);
Error(diagnostics, ErrorCode.ERR_InvalidInitializerElementInitializer, memberInitializer);
return ToBadExpression(boundExpression, LookupResultKind.NotAValue);
}
// returns BadBoundExpression or BoundObjectInitializerMember
private BoundExpression BindObjectInitializerMember(
AssignmentExpressionSyntax namedAssignment,
BoundImplicitReceiver implicitReceiver,
DiagnosticBag diagnostics)
{
BoundExpression boundMember;
LookupResultKind resultKind;
bool hasErrors;
if (namedAssignment.Left.Kind() == SyntaxKind.IdentifierName)
{
var memberName = (IdentifierNameSyntax)namedAssignment.Left;
// SPEC: Each member initializer must name an accessible field or property of the object being initialized, followed by an equals sign and
// SPEC: an expression or an object initializer or collection initializer.
// SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (7.17.1) to the field or property.
// SPEC VIOLATION: Native compiler also allows initialization of field-like events in object initializers, so we allow it as well.
boundMember = BindInstanceMemberAccess(
node: memberName,
right: memberName,
boundLeft: implicitReceiver,
rightName: memberName.Identifier.ValueText,
rightArity: 0,
typeArgumentsSyntax: default(SeparatedSyntaxList<TypeSyntax>),
typeArgumentsWithAnnotations: default(ImmutableArray<TypeWithAnnotations>),
invoked: false,
indexed: false,
diagnostics: diagnostics);
resultKind = boundMember.ResultKind;
hasErrors = boundMember.HasAnyErrors || implicitReceiver.HasAnyErrors;
if (boundMember.Kind == BoundKind.PropertyGroup)
{
boundMember = BindIndexedPropertyAccess((BoundPropertyGroup)boundMember, mustHaveAllOptionalParameters: true, diagnostics: diagnostics);
if (boundMember.HasAnyErrors)
{
hasErrors = true;
}
}
}
else if (namedAssignment.Left.Kind() == SyntaxKind.ImplicitElementAccess)
{
var implicitIndexing = (ImplicitElementAccessSyntax)namedAssignment.Left;
boundMember = BindElementAccess(implicitIndexing, implicitReceiver, implicitIndexing.ArgumentList, diagnostics);
resultKind = boundMember.ResultKind;
hasErrors = boundMember.HasAnyErrors || implicitReceiver.HasAnyErrors;
}
else
{
return null;
}
// SPEC: A member initializer that specifies an object initializer after the equals sign is a nested object initializer,
// SPEC: i.e. an initialization of an embedded object. Instead of assigning a new value to the field or property,
// SPEC: the assignments in the nested object initializer are treated as assignments to members of the field or property.
// SPEC: Nested object initializers cannot be applied to properties with a value type, or to read-only fields with a value type.
// NOTE: The dev11 behavior does not match the spec that was current at the time (quoted above). However, in the roslyn
// NOTE: timeframe, the spec will be updated to apply the same restriction to nested collection initializers. Therefore,
// NOTE: roslyn will implement the dev11 behavior and it will be spec-compliant.
// NOTE: In the roslyn timeframe, an additional restriction will (likely) be added to the spec - it is not sufficient for the
// NOTE: type of the member to not be a value type - it must actually be a reference type (i.e. unconstrained type parameters
// NOTE: should be prohibited). To avoid breaking existing code, roslyn will not implement this new spec clause.
// TODO: If/when we have a way to version warnings, we should add a warning for this.
BoundKind boundMemberKind = boundMember.Kind;
SyntaxKind rhsKind = namedAssignment.Right.Kind();
bool isRhsNestedInitializer = rhsKind == SyntaxKind.ObjectInitializerExpression || rhsKind == SyntaxKind.CollectionInitializerExpression;
BindValueKind valueKind = isRhsNestedInitializer ? BindValueKind.RValue : BindValueKind.Assignable;
ImmutableArray<BoundExpression> arguments = ImmutableArray<BoundExpression>.Empty;
ImmutableArray<string> argumentNamesOpt = default(ImmutableArray<string>);
ImmutableArray<int> argsToParamsOpt = default(ImmutableArray<int>);
ImmutableArray<RefKind> argumentRefKindsOpt = default(ImmutableArray<RefKind>);
bool expanded = false;
switch (boundMemberKind)
{
case BoundKind.FieldAccess:
{
var fieldSymbol = ((BoundFieldAccess)boundMember).FieldSymbol;
if (isRhsNestedInitializer && fieldSymbol.IsReadOnly && fieldSymbol.Type.IsValueType)
{
if (!hasErrors)
{
// TODO: distinct error code for collection initializers? (Dev11 doesn't have one.)
Error(diagnostics, ErrorCode.ERR_ReadonlyValueTypeInObjectInitializer, namedAssignment.Left, fieldSymbol, fieldSymbol.Type);
hasErrors = true;
}
resultKind = LookupResultKind.NotAValue;
}
break;
}
case BoundKind.EventAccess:
break;
case BoundKind.PropertyAccess:
hasErrors |= isRhsNestedInitializer && !CheckNestedObjectInitializerPropertySymbol(((BoundPropertyAccess)boundMember).PropertySymbol, namedAssignment.Left, diagnostics, hasErrors, ref resultKind);
break;
case BoundKind.IndexerAccess:
{
var indexer = (BoundIndexerAccess)boundMember;
hasErrors |= isRhsNestedInitializer && !CheckNestedObjectInitializerPropertySymbol(indexer.Indexer, namedAssignment.Left, diagnostics, hasErrors, ref resultKind);
arguments = indexer.Arguments;
argumentNamesOpt = indexer.ArgumentNamesOpt;
argsToParamsOpt = indexer.ArgsToParamsOpt;
argumentRefKindsOpt = indexer.ArgumentRefKindsOpt;
expanded = indexer.Expanded;
break;
}
case BoundKind.DynamicIndexerAccess:
{
var indexer = (BoundDynamicIndexerAccess)boundMember;
arguments = indexer.Arguments;
argumentNamesOpt = indexer.ArgumentNamesOpt;
argumentRefKindsOpt = indexer.ArgumentRefKindsOpt;
}
break;
case BoundKind.ArrayAccess:
case BoundKind.PointerElementAccess:
return boundMember;
default:
return BadObjectInitializerMemberAccess(boundMember, implicitReceiver, namedAssignment.Left, diagnostics, valueKind, hasErrors);
}
if (!hasErrors)
{
// CheckValueKind to generate possible diagnostics for invalid initializers non-viable member lookup result:
// 1) CS0154 (ERR_PropertyLacksGet)
// 2) CS0200 (ERR_AssgReadonlyProp)
Debug.Assert(Flags.Includes(CSharp.BinderFlags.ObjectInitializerMember));
if (!CheckValueKind(boundMember.Syntax, boundMember, valueKind, checkingReceiver: false, diagnostics: diagnostics))
{
hasErrors = true;
resultKind = isRhsNestedInitializer ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable;
}
}
return new BoundObjectInitializerMember(
namedAssignment.Left,
boundMember.ExpressionSymbol,
arguments,
argumentNamesOpt,
argumentRefKindsOpt,
expanded,
argsToParamsOpt,
resultKind,
implicitReceiver.Type,
binderOpt: this,
type: boundMember.Type,
hasErrors: hasErrors);
}
private static bool CheckNestedObjectInitializerPropertySymbol(
PropertySymbol propertySymbol,
ExpressionSyntax memberNameSyntax,
DiagnosticBag diagnostics,
bool suppressErrors,
ref LookupResultKind resultKind)
{
bool hasErrors = false;
if (propertySymbol.Type.IsValueType)
{
if (!suppressErrors)
{
// TODO: distinct error code for collection initializers? (Dev11 doesn't have one.)
Error(diagnostics, ErrorCode.ERR_ValueTypePropertyInObjectInitializer, memberNameSyntax, propertySymbol, propertySymbol.Type);
hasErrors = true;
}
resultKind = LookupResultKind.NotAValue;
}
return !hasErrors;
}
private BoundExpression BadObjectInitializerMemberAccess(
BoundExpression boundMember,
BoundImplicitReceiver implicitReceiver,
ExpressionSyntax memberNameSyntax,
DiagnosticBag diagnostics,
BindValueKind valueKind,
bool suppressErrors)
{
if (!suppressErrors)
{
string member;
var identName = memberNameSyntax as IdentifierNameSyntax;
if (identName != null)
{
member = identName.Identifier.ValueText;
}
else
{
member = memberNameSyntax.ToString();
}
switch (boundMember.ResultKind)
{
case LookupResultKind.Empty:
Error(diagnostics, ErrorCode.ERR_NoSuchMember, memberNameSyntax, implicitReceiver.Type, member);
break;
case LookupResultKind.Inaccessible:
boundMember = CheckValue(boundMember, valueKind, diagnostics);
Debug.Assert(boundMember.HasAnyErrors);
break;
default:
Error(diagnostics, ErrorCode.ERR_MemberCannotBeInitialized, memberNameSyntax, member);
break;
}
}
return ToBadExpression(boundMember, (valueKind == BindValueKind.RValue) ? LookupResultKind.NotAValue : LookupResultKind.NotAVariable);
}
private static void ReportDuplicateObjectMemberInitializers(BoundExpression boundMemberInitializer, HashSet<string> memberNameMap, DiagnosticBag diagnostics)
{
Debug.Assert(memberNameMap != null);
// SPEC: It is an error for an object initializer to include more than one member initializer for the same field or property.
if (!boundMemberInitializer.HasAnyErrors)
{
// SPEC: A member initializer that specifies an expression after the equals sign is processed in the same way as an assignment (7.17.1) to the field or property.
var memberInitializerSyntax = boundMemberInitializer.Syntax;
Debug.Assert(memberInitializerSyntax.Kind() == SyntaxKind.SimpleAssignmentExpression);
var namedAssignment = (AssignmentExpressionSyntax)memberInitializerSyntax;
var memberNameSyntax = namedAssignment.Left as IdentifierNameSyntax;
if (memberNameSyntax != null)
{
var memberName = memberNameSyntax.Identifier.ValueText;
if (!memberNameMap.Add(memberName))
{
Error(diagnostics, ErrorCode.ERR_MemberAlreadyInitialized, memberNameSyntax, memberName);
}
}
}
}
private BoundCollectionInitializerExpression BindCollectionInitializerExpression(
InitializerExpressionSyntax initializerSyntax,
TypeSymbol initializerType,
DiagnosticBag diagnostics,
BoundImplicitReceiver implicitReceiver)
{
// SPEC: 7.6.10.3 Collection initializers
//
// SPEC: A collection initializer consists of a sequence of element initializers, enclosed by { and } tokens and separated by commas.
// SPEC: The following is an example of an object creation expression that includes a collection initializer:
// SPEC: List<int> digits = new List<int> { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9 };
// SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or
// SPEC: a compile-time error occurs. For each specified element in order, the collection initializer invokes an Add method on the target object
// SPEC: with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation.
// SPEC: Thus, the collection object must contain an applicable Add method for each element initializer.
Debug.Assert(initializerSyntax.Kind() == SyntaxKind.CollectionInitializerExpression);
Debug.Assert(initializerSyntax.Expressions.Any());
Debug.Assert((object)initializerType != null);
var initializerBuilder = ArrayBuilder<BoundExpression>.GetInstance();
// SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or
// SPEC: a compile-time error occurs.
bool hasEnumerableInitializerType = CollectionInitializerTypeImplementsIEnumerable(initializerType, initializerSyntax, diagnostics);
if (!hasEnumerableInitializerType && !initializerSyntax.HasErrors && !initializerType.IsErrorType())
{
Error(diagnostics, ErrorCode.ERR_CollectionInitRequiresIEnumerable, initializerSyntax, initializerType);
}
// We use a location specific binder for binding collection initializer Add method to generate specific overload resolution diagnostics:
// 1) CS1921 (ERR_InitializerAddHasWrongSignature)
// 2) CS1950 (ERR_BadArgTypesForCollectionAdd)
// 3) CS1954 (ERR_InitializerAddHasParamModifiers)
var collectionInitializerAddMethodBinder = this.WithAdditionalFlags(BinderFlags.CollectionInitializerAddMethod);
foreach (var elementInitializer in initializerSyntax.Expressions)
{
// NOTE: collectionInitializerAddMethodBinder is used only for binding the Add method invocation expression, but not the entire initializer.
// NOTE: Hence it is being passed as a parameter to BindCollectionInitializerElement().
// NOTE: Ideally we would want to avoid this and bind the entire initializer with the collectionInitializerAddMethodBinder.
// NOTE: However, this approach has few issues. These issues also occur when binding object initializer member assignment.
// NOTE: See comments for objectInitializerMemberBinder in BindObjectInitializerExpression method for details about the pitfalls of alternate approaches.
BoundExpression boundElementInitializer = BindCollectionInitializerElement(elementInitializer, initializerType,
hasEnumerableInitializerType, collectionInitializerAddMethodBinder, diagnostics, implicitReceiver);
initializerBuilder.Add(boundElementInitializer);
}
return new BoundCollectionInitializerExpression(initializerSyntax, initializerBuilder.ToImmutableAndFree(), initializerType);
}
private bool CollectionInitializerTypeImplementsIEnumerable(TypeSymbol initializerType, CSharpSyntaxNode node, DiagnosticBag diagnostics)
{
// SPEC: The collection object to which a collection initializer is applied must be of a type that implements System.Collections.IEnumerable or
// SPEC: a compile-time error occurs.
if (initializerType.IsDynamic())
{
// We cannot determine at compile time if initializerType implements System.Collections.IEnumerable, we must assume that it does.
return true;
}
else if (!initializerType.IsErrorType())
{
TypeSymbol collectionsIEnumerableType = this.GetSpecialType(SpecialType.System_Collections_IEnumerable, diagnostics, node);
// NOTE: Ideally, to check if the initializer type implements System.Collections.IEnumerable we can walk through
// NOTE: its implemented interfaces. However the native compiler checks to see if there is conversion from initializer
// NOTE: type to the predefined System.Collections.IEnumerable type, so we do the same.
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
var result = Conversions.ClassifyImplicitConversionFromType(initializerType, collectionsIEnumerableType, ref useSiteDiagnostics).IsValid;
diagnostics.Add(node, useSiteDiagnostics);
return result;
}
else
{
return false;
}
}
private BoundExpression BindCollectionInitializerElement(
ExpressionSyntax elementInitializer,
TypeSymbol initializerType,
bool hasEnumerableInitializerType,
Binder collectionInitializerAddMethodBinder,
DiagnosticBag diagnostics,
BoundImplicitReceiver implicitReceiver)
{
// SPEC: Each element initializer specifies an element to be added to the collection object being initialized, and consists of
// SPEC: a list of expressions enclosed by { and } tokens and separated by commas.
// SPEC: A single-expression element initializer can be written without braces, but cannot then be an assignment expression,
// SPEC: to avoid ambiguity with member initializers. The non-assignment-expression production is defined in 7.18.
if (elementInitializer.Kind() == SyntaxKind.ComplexElementInitializerExpression)
{
return BindComplexElementInitializerExpression(
(InitializerExpressionSyntax)elementInitializer,
diagnostics,
hasEnumerableInitializerType,
collectionInitializerAddMethodBinder,
implicitReceiver);
}
else
{
// Must be a non-assignment expression.
if (SyntaxFacts.IsAssignmentExpression(elementInitializer.Kind()))
{
Error(diagnostics, ErrorCode.ERR_InvalidInitializerElementInitializer, elementInitializer);
}
var boundElementInitializer = BindInitializerExpressionOrValue(elementInitializer, initializerType, implicitReceiver.Syntax, diagnostics);
BoundExpression result = BindCollectionInitializerElementAddMethod(
elementInitializer,
ImmutableArray.Create(boundElementInitializer),
hasEnumerableInitializerType,
collectionInitializerAddMethodBinder,
diagnostics,
implicitReceiver);
result.WasCompilerGenerated = true;
return result;
}
}
private BoundExpression BindComplexElementInitializerExpression(
InitializerExpressionSyntax elementInitializer,
DiagnosticBag diagnostics,
bool hasEnumerableInitializerType,
Binder collectionInitializerAddMethodBinder = null,
BoundImplicitReceiver implicitReceiver = null)
{
var elementInitializerExpressions = elementInitializer.Expressions;
if (elementInitializerExpressions.Any())
{
var exprBuilder = ArrayBuilder<BoundExpression>.GetInstance();
foreach (var childElementInitializer in elementInitializerExpressions)
{
exprBuilder.Add(BindValue(childElementInitializer, diagnostics, BindValueKind.RValue));
}
return BindCollectionInitializerElementAddMethod(
elementInitializer,
exprBuilder.ToImmutableAndFree(),
hasEnumerableInitializerType,
collectionInitializerAddMethodBinder,
diagnostics,
implicitReceiver);
}
else
{
Error(diagnostics, ErrorCode.ERR_EmptyElementInitializer, elementInitializer);
return BadExpression(elementInitializer, LookupResultKind.NotInvocable);
}
}
private BoundExpression BindUnexpectedComplexElementInitializer(InitializerExpressionSyntax node, DiagnosticBag diagnostics)
{
Debug.Assert(node.Kind() == SyntaxKind.ComplexElementInitializerExpression);
return BindComplexElementInitializerExpression(node, diagnostics, hasEnumerableInitializerType: false);
}
private BoundExpression BindCollectionInitializerElementAddMethod(
ExpressionSyntax elementInitializer,
ImmutableArray<BoundExpression> boundElementInitializerExpressions,
bool hasEnumerableInitializerType,
Binder collectionInitializerAddMethodBinder,
DiagnosticBag diagnostics,
BoundImplicitReceiver implicitReceiver)
{
// SPEC: For each specified element in order, the collection initializer invokes an Add method on the target object
// SPEC: with the expression list of the element initializer as argument list, applying normal overload resolution for each invocation.
// SPEC: Thus, the collection object must contain an applicable Add method for each element initializer.
// We use a location specific binder for binding collection initializer Add method to generate specific overload resolution diagnostics.
// 1) CS1921 (ERR_InitializerAddHasWrongSignature)
// 2) CS1950 (ERR_BadArgTypesForCollectionAdd)
// 3) CS1954 (ERR_InitializerAddHasParamModifiers)
// See comments in BindCollectionInitializerExpression for more details.
Debug.Assert(!boundElementInitializerExpressions.IsEmpty);
if (!hasEnumerableInitializerType)
{
return BadExpression(elementInitializer, LookupResultKind.NotInvocable, ImmutableArray<Symbol>.Empty, boundElementInitializerExpressions);
}
Debug.Assert(collectionInitializerAddMethodBinder != null);
Debug.Assert(collectionInitializerAddMethodBinder.Flags.Includes(BinderFlags.CollectionInitializerAddMethod));
Debug.Assert(implicitReceiver != null);
Debug.Assert((object)implicitReceiver.Type != null);
if (implicitReceiver.Type.IsDynamic())
{
var hasErrors = ReportBadDynamicArguments(elementInitializer, boundElementInitializerExpressions, refKinds: default, diagnostics, queryClause: null);
return new BoundDynamicCollectionElementInitializer(
elementInitializer,
applicableMethods: ImmutableArray<MethodSymbol>.Empty,
implicitReceiver,
arguments: boundElementInitializerExpressions,
type: GetSpecialType(SpecialType.System_Void, diagnostics, elementInitializer),
hasErrors: hasErrors);
}
// Receiver is early bound, find method Add and invoke it (may still be a dynamic invocation):
var addMethodInvocation = collectionInitializerAddMethodBinder.MakeInvocationExpression(
elementInitializer,
implicitReceiver,
methodName: WellKnownMemberNames.CollectionInitializerAddMethodName,
args: boundElementInitializerExpressions,
diagnostics: diagnostics);
if (addMethodInvocation.Kind == BoundKind.DynamicInvocation)
{
var dynamicInvocation = (BoundDynamicInvocation)addMethodInvocation;
return new BoundDynamicCollectionElementInitializer(
elementInitializer,
dynamicInvocation.ApplicableMethods,
implicitReceiver,
dynamicInvocation.Arguments,
dynamicInvocation.Type,
hasErrors: dynamicInvocation.HasAnyErrors);
}
else if (addMethodInvocation.Kind == BoundKind.Call)
{
var boundCall = (BoundCall)addMethodInvocation;
// Either overload resolution succeeded for this call or it did not. If it
// did not succeed then we've stashed the original method symbols from the
// method group, and we should use those as the symbols displayed for the
// call. If it did succeed then we did not stash any symbols.
if (boundCall.HasErrors && !boundCall.OriginalMethodsOpt.IsDefault)
{
return boundCall;
}
return new BoundCollectionElementInitializer(
elementInitializer,
boundCall.Method,
boundCall.Arguments,
boundCall.ReceiverOpt,
boundCall.Expanded,
boundCall.ArgsToParamsOpt,
boundCall.InvokedAsExtensionMethod,
boundCall.ResultKind,
binderOpt: boundCall.BinderOpt,
boundCall.Type,
boundCall.HasAnyErrors)
{ WasCompilerGenerated = true };
}
else
{
Debug.Assert(addMethodInvocation.Kind == BoundKind.BadExpression);
return addMethodInvocation;
}
}
internal ImmutableArray<MethodSymbol> FilterInaccessibleConstructors(ImmutableArray<MethodSymbol> constructors, bool allowProtectedConstructorsOfBaseType, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
ArrayBuilder<MethodSymbol> builder = null;
for (int i = 0; i < constructors.Length; i++)
{
MethodSymbol constructor = constructors[i];
if (!IsConstructorAccessible(constructor, ref useSiteDiagnostics, allowProtectedConstructorsOfBaseType))
{
if (builder == null)
{
builder = ArrayBuilder<MethodSymbol>.GetInstance();
builder.AddRange(constructors, i);
}
}
else
{
builder?.Add(constructor);
}
}
return builder == null ? constructors : builder.ToImmutableAndFree();
}
private bool IsConstructorAccessible(MethodSymbol constructor, ref HashSet<DiagnosticInfo> useSiteDiagnostics, bool allowProtectedConstructorsOfBaseType = false)
{
Debug.Assert((object)constructor != null);
Debug.Assert(constructor.MethodKind == MethodKind.Constructor || constructor.MethodKind == MethodKind.StaticConstructor);
NamedTypeSymbol containingType = this.ContainingType;
if ((object)containingType != null)
{
// SPEC VIOLATION: The specification implies that when considering
// SPEC VIOLATION: instance methods or instance constructors, we first
// SPEC VIOLATION: do overload resolution on the accessible members, and
// SPEC VIOLATION: then if the best method chosen is protected and accessed
// SPEC VIOLATION: through the wrong type, then an error occurs. The native
// SPEC VIOLATION: compiler however does it in the opposite order. First it
// SPEC VIOLATION: filters out the protected methods that cannot be called
// SPEC VIOLATION: through the given type, and then it does overload resolution
// SPEC VIOLATION: on the rest.
//
// That said, it is somewhat odd that the same rule applies to constructors
// as instance methods. A protected constructor is never going to be called
// via an instance of a *more derived but different class* the way a
// virtual method might be. Nevertheless, that's what we do.
//
// A constructor is accessed through an instance of the type being constructed:
return allowProtectedConstructorsOfBaseType ?
this.IsAccessible(constructor, ref useSiteDiagnostics, null) :
this.IsSymbolAccessibleConditional(constructor, containingType, ref useSiteDiagnostics, constructor.ContainingType);
}
else
{
Debug.Assert((object)this.Compilation.Assembly != null);
return IsSymbolAccessibleConditional(constructor, this.Compilation.Assembly, ref useSiteDiagnostics);
}
}
protected BoundExpression BindClassCreationExpression(
CSharpSyntaxNode node,
string typeName,
CSharpSyntaxNode typeNode,
NamedTypeSymbol type,
AnalyzedArguments analyzedArguments,
DiagnosticBag diagnostics,
InitializerExpressionSyntax initializerSyntaxOpt = null,
TypeSymbol initializerTypeOpt = null)
{
BoundExpression result = null;
bool hasErrors = type.IsErrorType();
if (type.IsAbstract)
{
// Report error for new of abstract type.
diagnostics.Add(ErrorCode.ERR_NoNewAbstract, node.Location, type);
hasErrors = true;
}
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
BoundObjectInitializerExpressionBase boundInitializerOpt = null;
// If we have a dynamic argument then do overload resolution to see if there are one or more
// applicable candidates. If there are, then this is a dynamic object creation; we'll work out
// which ctor to call at runtime. If we have a dynamic argument but no applicable candidates
// then we do the analysis again for error reporting purposes.
if (analyzedArguments.HasDynamicArgument)
{
OverloadResolutionResult<MethodSymbol> overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance();
this.OverloadResolution.ObjectCreationOverloadResolution(GetAccessibleConstructorsForOverloadResolution(type, ref useSiteDiagnostics), analyzedArguments, overloadResolutionResult, ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
useSiteDiagnostics = null;
if (overloadResolutionResult.HasAnyApplicableMember)
{
var argArray = BuildArgumentsForDynamicInvocation(analyzedArguments, diagnostics);
var refKindsArray = analyzedArguments.RefKinds.ToImmutableOrNull();
hasErrors &= ReportBadDynamicArguments(node, argArray, refKindsArray, diagnostics, queryClause: null);
boundInitializerOpt = makeBoundInitializerOpt();
result = new BoundDynamicObjectCreationExpression(
node,
typeName,
argArray,
analyzedArguments.GetNames(),
refKindsArray,
boundInitializerOpt,
overloadResolutionResult.GetAllApplicableMembers(),
type,
hasErrors);
}
overloadResolutionResult.Free();
if (result != null)
{
return result;
}
}
MemberResolutionResult<MethodSymbol> memberResolutionResult;
ImmutableArray<MethodSymbol> candidateConstructors;
if (TryPerformConstructorOverloadResolution(
type,
analyzedArguments,
typeName,
typeNode.Location,
hasErrors, //don't cascade in these cases
diagnostics,
out memberResolutionResult,
out candidateConstructors,
allowProtectedConstructorsOfBaseType: false))
{
var method = memberResolutionResult.Member;
bool hasError = false;
// What if some of the arguments are implicit? Dev10 reports unsafe errors
// if the implied argument would have an unsafe type. We need to check
// the parameters explicitly, since there won't be bound nodes for the implied
// arguments until lowering.
if (method.HasUnsafeParameter())
{
// Don't worry about double reporting (i.e. for both the argument and the parameter)
// because only one unsafe diagnostic is allowed per scope - the others are suppressed.
hasError = ReportUnsafeIfNotAllowed(node, diagnostics) || hasError;
}
ReportDiagnosticsIfObsolete(diagnostics, method, node, hasBaseReceiver: false);
// NOTE: Use-site diagnostics were reported during overload resolution.
ConstantValue constantValueOpt = (initializerSyntaxOpt == null && method.IsDefaultValueTypeConstructor()) ?
FoldParameterlessValueTypeConstructor(type) :
null;
var arguments = analyzedArguments.Arguments.ToImmutable();
var refKinds = analyzedArguments.RefKinds.ToImmutableOrNull();
var argToParams = memberResolutionResult.Result.ArgsToParamsOpt;
if (!hasError)
{
hasError = !CheckInvocationArgMixing(
node,
method,
null,
method.Parameters,
arguments,
argToParams,
this.LocalScopeDepth,
diagnostics);
}
boundInitializerOpt = makeBoundInitializerOpt();
result = new BoundObjectCreationExpression(
node,
method,
candidateConstructors,
arguments,
analyzedArguments.GetNames(),
refKinds,
memberResolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm,
argToParams,
constantValueOpt,
boundInitializerOpt,
this,
type,
hasError);
// CONSIDER: Add ResultKind field to BoundObjectCreationExpression to avoid wrapping result with BoundBadExpression.
if (type.IsAbstract)
{
result = BadExpression(node, LookupResultKind.NotCreatable, result);
}
return result;
}
LookupResultKind resultKind;
if (type.IsAbstract)
{
resultKind = LookupResultKind.NotCreatable;
}
else if (memberResolutionResult.IsValid && !IsConstructorAccessible(memberResolutionResult.Member, ref useSiteDiagnostics))
{
resultKind = LookupResultKind.Inaccessible;
}
else
{
resultKind = LookupResultKind.OverloadResolutionFailure;
}
diagnostics.Add(node, useSiteDiagnostics);
ArrayBuilder<Symbol> symbols = ArrayBuilder<Symbol>.GetInstance();
symbols.AddRange(candidateConstructors);
// NOTE: The use site diagnostics of the candidate constructors have already been reported (in PerformConstructorOverloadResolution).
var childNodes = ArrayBuilder<BoundExpression>.GetInstance();
childNodes.AddRange(BuildArgumentsForErrorRecovery(analyzedArguments, candidateConstructors));
if (initializerSyntaxOpt != null)
{
childNodes.Add(boundInitializerOpt ?? makeBoundInitializerOpt());
}
return new BoundBadExpression(node, resultKind, symbols.ToImmutableAndFree(), childNodes.ToImmutableAndFree(), type);
BoundObjectInitializerExpressionBase makeBoundInitializerOpt()
{
if (initializerSyntaxOpt != null)
{
return BindInitializerExpression(syntax: initializerSyntaxOpt,
type: initializerTypeOpt ?? type,
typeSyntax: typeNode,
diagnostics: diagnostics);
}
return null;
}
}
private BoundExpression BindInterfaceCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, DiagnosticBag diagnostics)
{
Debug.Assert((object)type != null);
// COM interfaces which have ComImportAttribute and CoClassAttribute can be instantiated with "new".
// CoClassAttribute contains the type information of the original CoClass for the interface.
// We replace the interface creation with CoClass object creation for this case.
// NOTE: We don't attempt binding interface creation to CoClass creation if we are within an attribute argument.
// NOTE: This is done to prevent a cycle in an error scenario where we have a "new InterfaceType" expression in an attribute argument.
// NOTE: Accessing IsComImport/ComImportCoClass properties on given type symbol would attempt ForceCompeteAttributes, which would again try binding all attributes on the symbol.
// NOTE: causing infinite recursion. We avoid this cycle by checking if we are within in context of an Attribute argument.
if (!this.InAttributeArgument && type.IsComImport)
{
NamedTypeSymbol coClassType = type.ComImportCoClass;
if ((object)coClassType != null)
{
return BindComImportCoClassCreationExpression(node, type, coClassType, diagnostics);
}
}
// interfaces can't be instantiated in C#
diagnostics.Add(ErrorCode.ERR_NoNewAbstract, node.Location, type);
return BindBadInterfaceCreationExpression(node, type, diagnostics);
}
private BoundExpression BindBadInterfaceCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol type, DiagnosticBag diagnostics)
{
AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance();
BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments);
ImmutableArray<BoundExpression> childNodes = BuildArgumentsForErrorRecovery(analyzedArguments);
BoundExpression result = new BoundBadExpression(node, LookupResultKind.NotCreatable, ImmutableArray.Create<Symbol>(type), childNodes, type);
analyzedArguments.Free();
return result;
}
private BoundExpression BindComImportCoClassCreationExpression(ObjectCreationExpressionSyntax node, NamedTypeSymbol interfaceType, NamedTypeSymbol coClassType, DiagnosticBag diagnostics)
{
Debug.Assert((object)interfaceType != null);
Debug.Assert(interfaceType.IsInterfaceType());
Debug.Assert((object)coClassType != null);
Debug.Assert(TypeSymbol.Equals(interfaceType.ComImportCoClass, coClassType, TypeCompareKind.ConsiderEverything2));
Debug.Assert(coClassType.TypeKind == TypeKind.Class || coClassType.TypeKind == TypeKind.Error);
if (coClassType.IsErrorType())
{
Error(diagnostics, ErrorCode.ERR_MissingCoClass, node, coClassType, interfaceType);
}
else if (coClassType.IsUnboundGenericType)
{
// BREAKING CHANGE: Dev10 allows the following code to compile, even though the output assembly is not verifiable and generates a runtime exception:
//
// [ComImport, Guid("00020810-0000-0000-C000-000000000046")]
// [CoClass(typeof(GenericClass<>))]
// public interface InterfaceType {}
// public class GenericClass<T>: InterfaceType {}
//
// public class Program
// {
// public static void Main() { var i = new InterfaceType(); }
// }
//
// We disallow CoClass creation if coClassType is an unbound generic type and report a compile time error.
Error(diagnostics, ErrorCode.ERR_BadCoClassSig, node, coClassType, interfaceType);
}
else
{
// NoPIA support
if (interfaceType.ContainingAssembly.IsLinked)
{
return BindNoPiaObjectCreationExpression(node, interfaceType, coClassType, diagnostics);
}
var classCreation = BindClassCreationExpression(node, coClassType, coClassType.Name, diagnostics, interfaceType);
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
Conversion conversion = this.Conversions.ClassifyConversionFromExpression(classCreation, interfaceType, ref useSiteDiagnostics, forCast: true);
diagnostics.Add(node, useSiteDiagnostics);
if (!conversion.IsValid)
{
SymbolDistinguisher distinguisher = new SymbolDistinguisher(this.Compilation, coClassType, interfaceType);
Error(diagnostics, ErrorCode.ERR_NoExplicitConv, node, distinguisher.First, distinguisher.Second);
}
// Bind the conversion, but drop the conversion node.
CreateConversion(classCreation, conversion, interfaceType, diagnostics);
// Override result type to be the interface type.
switch (classCreation.Kind)
{
case BoundKind.ObjectCreationExpression:
var creation = (BoundObjectCreationExpression)classCreation;
return creation.Update(creation.Constructor, creation.ConstructorsGroup, creation.Arguments, creation.ArgumentNamesOpt,
creation.ArgumentRefKindsOpt, creation.Expanded, creation.ArgsToParamsOpt, creation.ConstantValueOpt,
creation.InitializerExpressionOpt, creation.BinderOpt, interfaceType);
case BoundKind.BadExpression:
var bad = (BoundBadExpression)classCreation;
return bad.Update(bad.ResultKind, bad.Symbols, bad.ChildBoundNodes, interfaceType);
default:
throw ExceptionUtilities.UnexpectedValue(classCreation.Kind);
}
}
return BindBadInterfaceCreationExpression(node, interfaceType, diagnostics);
}
private BoundExpression BindNoPiaObjectCreationExpression(
ObjectCreationExpressionSyntax node,
NamedTypeSymbol interfaceType,
NamedTypeSymbol coClassType,
DiagnosticBag diagnostics)
{
string guidString;
if (!coClassType.GetGuidString(out guidString))
{
// At this point, VB reports ERRID_NoPIAAttributeMissing2 if guid isn't there.
// C# doesn't complain and instead uses zero guid.
guidString = System.Guid.Empty.ToString("D");
}
var boundInitializerOpt = node.Initializer == null ? null :
BindInitializerExpression(syntax: node.Initializer,
type: interfaceType,
typeSyntax: node.Type,
diagnostics: diagnostics);
var creation = new BoundNoPiaObjectCreationExpression(node, guidString, boundInitializerOpt, interfaceType);
// Get the bound arguments and the argument names, it is an error if any are present.
AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance();
try
{
BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments, allowArglist: false);
if (analyzedArguments.Arguments.Count > 0)
{
diagnostics.Add(ErrorCode.ERR_BadCtorArgCount, node.ArgumentList.Location, interfaceType, analyzedArguments.Arguments.Count);
var children = BuildArgumentsForErrorRecovery(analyzedArguments).Add(creation);
return new BoundBadExpression(node, LookupResultKind.OverloadResolutionFailure, ImmutableArray<Symbol>.Empty, children, creation.Type);
}
}
finally
{
analyzedArguments.Free();
}
return creation;
}
private BoundExpression BindTypeParameterCreationExpression(ObjectCreationExpressionSyntax node, TypeParameterSymbol typeParameter, DiagnosticBag diagnostics)
{
AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance();
BindArgumentsAndNames(node.ArgumentList, diagnostics, analyzedArguments);
bool hasArguments = analyzedArguments.Arguments.Count > 0;
try
{
if (!typeParameter.HasConstructorConstraint && !typeParameter.IsValueType)
{
diagnostics.Add(ErrorCode.ERR_NoNewTyvar, node.Location, typeParameter);
}
else if (hasArguments)
{
diagnostics.Add(ErrorCode.ERR_NewTyvarWithArgs, node.Location, typeParameter);
}
else
{
var boundInitializerOpt = node.Initializer == null ?
null :
BindInitializerExpression(
syntax: node.Initializer,
type: typeParameter,
typeSyntax: node.Type,
diagnostics: diagnostics);
return new BoundNewT(node, boundInitializerOpt, typeParameter);
}
return MakeBadExpressionForObjectCreation(node, typeParameter, analyzedArguments, diagnostics);
}
finally
{
analyzedArguments.Free();
}
}
/// <summary>
/// Given the type containing constructors, gets the list of candidate instance constructors and uses overload resolution to determine which one should be called.
/// </summary>
/// <param name="typeContainingConstructors">The containing type of the constructors.</param>
/// <param name="analyzedArguments">The already bound arguments to the constructor.</param>
/// <param name="errorName">The name to use in diagnostics if overload resolution fails.</param>
/// <param name="errorLocation">The location at which to report overload resolution result diagnostics.</param>
/// <param name="suppressResultDiagnostics">True to suppress overload resolution result diagnostics (but not argument diagnostics).</param>
/// <param name="diagnostics">Where diagnostics will be reported.</param>
/// <param name="memberResolutionResult">If this method returns true, then it will contain a valid MethodResolutionResult.
/// Otherwise, it may contain a MethodResolutionResult for an inaccessible constructor (in which case, it will incorrectly indicate success) or nothing at all.</param>
/// <param name="candidateConstructors">Candidate instance constructors of type <paramref name="typeContainingConstructors"/> used for overload resolution.</param>
/// <param name="allowProtectedConstructorsOfBaseType">It is always legal to access a protected base class constructor
/// via a constructor initializer, but not from an object creation expression.</param>
/// <returns>True if overload resolution successfully chose an accessible constructor.</returns>
/// <remarks>
/// The two-pass algorithm (accessible constructors, then all constructors) is the reason for the unusual signature
/// of this method (i.e. not populating a pre-existing <see cref="OverloadResolutionResult{MethodSymbol}"/>).
/// Presently, rationalizing this behavior is not worthwhile.
/// </remarks>
private bool TryPerformConstructorOverloadResolution(
NamedTypeSymbol typeContainingConstructors,
AnalyzedArguments analyzedArguments,
string errorName,
Location errorLocation,
bool suppressResultDiagnostics,
DiagnosticBag diagnostics,
out MemberResolutionResult<MethodSymbol> memberResolutionResult,
out ImmutableArray<MethodSymbol> candidateConstructors,
bool allowProtectedConstructorsOfBaseType) // Last to make named arguments more convenient.
{
// Get accessible constructors for performing overload resolution.
ImmutableArray<MethodSymbol> allInstanceConstructors;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
candidateConstructors = GetAccessibleConstructorsForOverloadResolution(typeContainingConstructors, allowProtectedConstructorsOfBaseType, out allInstanceConstructors, ref useSiteDiagnostics);
OverloadResolutionResult<MethodSymbol> result = OverloadResolutionResult<MethodSymbol>.GetInstance();
// Indicates whether overload resolution successfully chose an accessible constructor.
bool succeededConsideringAccessibility = false;
// Indicates whether overload resolution resulted in a single best match, even though it might be inaccessible.
bool succeededIgnoringAccessibility = false;
if (candidateConstructors.Any())
{
// We have at least one accessible candidate constructor, perform overload resolution with accessible candidateConstructors.
this.OverloadResolution.ObjectCreationOverloadResolution(candidateConstructors, analyzedArguments, result, ref useSiteDiagnostics);
if (result.Succeeded)
{
succeededConsideringAccessibility = true;
succeededIgnoringAccessibility = true;
}
}
if (!succeededConsideringAccessibility && allInstanceConstructors.Length > candidateConstructors.Length)
{
// Overload resolution failed on the accessible candidateConstructors, but we have at least one inaccessible constructor.
// We might have a best match constructor which is inaccessible.
// Try overload resolution with all instance constructors to generate correct diagnostics and semantic info for this case.
OverloadResolutionResult<MethodSymbol> inaccessibleResult = OverloadResolutionResult<MethodSymbol>.GetInstance();
this.OverloadResolution.ObjectCreationOverloadResolution(allInstanceConstructors, analyzedArguments, inaccessibleResult, ref useSiteDiagnostics);
if (inaccessibleResult.Succeeded)
{
succeededIgnoringAccessibility = true;
candidateConstructors = allInstanceConstructors;
result.Free();
result = inaccessibleResult;
}
else
{
inaccessibleResult.Free();
}
}
diagnostics.Add(errorLocation, useSiteDiagnostics);
useSiteDiagnostics = null;
if (succeededIgnoringAccessibility)
{
this.CoerceArguments<MethodSymbol>(result.ValidResult, analyzedArguments.Arguments, diagnostics);
}
// Fill in the out parameter with the result, if there was one; it might be inaccessible.
memberResolutionResult = succeededIgnoringAccessibility ?
result.ValidResult :
default(MemberResolutionResult<MethodSymbol>); // Invalid results are not interesting - we have enough info in candidateConstructors.
// If something failed and we are reporting errors, then report the right errors.
// * If the failure was due to inaccessibility, just report that.
// * If the failure was not due to inaccessibility then only report an error
// on the constructor if there were no errors on the arguments.
if (!succeededConsideringAccessibility && !suppressResultDiagnostics)
{
if (succeededIgnoringAccessibility)
{
// It is not legal to directly call a protected constructor on a base class unless
// the "this" of the call is known to be of the current type. That is, it is
// perfectly legal to say ": base()" to call a protected base class ctor, but
// it is not legal to say "new MyBase()" if the ctor is protected.
//
// The native compiler produces the error CS1540:
//
// Cannot access protected member 'MyBase.MyBase' via a qualifier of type 'MyBase';
// the qualifier must be of type 'Derived' (or derived from it)
//
// Though technically correct, this is a very confusing error message for this scenario;
// one does not typically think of the constructor as being a method that is
// called with an implicit "this" of a particular receiver type, even though of course
// that is exactly what it is.
//
// The better error message here is to simply say that the best possible ctor cannot
// be accessed because it is not accessible.
//
// CONSIDER: We might consider making up a new error message for this situation.
//
// CS0122: 'MyBase.MyBase' is inaccessible due to its protection level
diagnostics.Add(ErrorCode.ERR_BadAccess, errorLocation, result.ValidResult.Member);
}
else
{
result.ReportDiagnostics(
binder: this, location: errorLocation, nodeOpt: null, diagnostics,
name: errorName, receiver: null, invokedExpression: null, analyzedArguments,
memberGroup: candidateConstructors, typeContainingConstructors, delegateTypeBeingInvoked: null);
}
}
result.Free();
return succeededConsideringAccessibility;
}
private ImmutableArray<MethodSymbol> GetAccessibleConstructorsForOverloadResolution(NamedTypeSymbol type, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
ImmutableArray<MethodSymbol> allInstanceConstructors;
return GetAccessibleConstructorsForOverloadResolution(type, false, out allInstanceConstructors, ref useSiteDiagnostics);
}
private ImmutableArray<MethodSymbol> GetAccessibleConstructorsForOverloadResolution(NamedTypeSymbol type, bool allowProtectedConstructorsOfBaseType, out ImmutableArray<MethodSymbol> allInstanceConstructors, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
if (type.IsErrorType())
{
// For Caas, we want to supply the constructors even in error cases
// We may end up supplying the constructors of an unconstructed symbol,
// but that's better than nothing.
type = type.GetNonErrorGuess() as NamedTypeSymbol ?? type;
}
allInstanceConstructors = type.InstanceConstructors;
return FilterInaccessibleConstructors(allInstanceConstructors, allowProtectedConstructorsOfBaseType, ref useSiteDiagnostics);
}
private static ConstantValue FoldParameterlessValueTypeConstructor(NamedTypeSymbol type)
{
// DELIBERATE SPEC VIOLATION:
//
// Object creation expressions like "new int()" are not considered constant expressions
// by the specification but they are by the native compiler; we maintain compatibility
// with this bug.
//
// Additionally, it also treats "new X()", where X is an enum type, as a
// constant expression with default value 0, we maintain compatibility with it.
var specialType = type.SpecialType;
if (type.TypeKind == TypeKind.Enum)
{
specialType = type.EnumUnderlyingType.SpecialType;
}
switch (specialType)
{
case SpecialType.System_SByte:
case SpecialType.System_Int16:
case SpecialType.System_Int32:
case SpecialType.System_Int64:
case SpecialType.System_Byte:
case SpecialType.System_UInt16:
case SpecialType.System_UInt32:
case SpecialType.System_UInt64:
case SpecialType.System_Single:
case SpecialType.System_Double:
case SpecialType.System_Decimal:
case SpecialType.System_Boolean:
case SpecialType.System_Char:
return ConstantValue.Default(specialType);
}
return null;
}
private BoundLiteral BindLiteralConstant(LiteralExpressionSyntax node, DiagnosticBag diagnostics)
{
// bug.Assert(node.Kind == SyntaxKind.LiteralExpression);
var value = node.Token.Value;
ConstantValue cv;
TypeSymbol type = null;
if (value == null)
{
cv = ConstantValue.Null;
}
else
{
Debug.Assert(!value.GetType().GetTypeInfo().IsEnum);
var specialType = SpecialTypeExtensions.FromRuntimeTypeOfLiteralValue(value);
// C# literals can't be of type byte, sbyte, short, ushort:
Debug.Assert(
specialType != SpecialType.None &&
specialType != SpecialType.System_Byte &&
specialType != SpecialType.System_SByte &&
specialType != SpecialType.System_Int16 &&
specialType != SpecialType.System_UInt16);
cv = ConstantValue.Create(value, specialType);
type = GetSpecialType(specialType, diagnostics, node);
}
return new BoundLiteral(node, cv, type);
}
private BoundExpression BindCheckedExpression(CheckedExpressionSyntax node, DiagnosticBag diagnostics)
{
// the binder is not cached since we only cache statement level binders
return this.WithCheckedOrUncheckedRegion(node.Kind() == SyntaxKind.CheckedExpression).
BindParenthesizedExpression(node.Expression, diagnostics);
}
/// <summary>
/// Binds a member access expression
/// </summary>
private BoundExpression BindMemberAccess(
MemberAccessExpressionSyntax node,
bool invoked,
bool indexed,
DiagnosticBag diagnostics)
{
Debug.Assert(node != null);
BoundExpression boundLeft;
ExpressionSyntax exprSyntax = node.Expression;
if (node.Kind() == SyntaxKind.SimpleMemberAccessExpression)
{
// NOTE: CheckValue will be called explicitly in BindMemberAccessWithBoundLeft.
boundLeft = BindLeftOfPotentialColorColorMemberAccess(exprSyntax, diagnostics);
}
else
{
Debug.Assert(node.Kind() == SyntaxKind.PointerMemberAccessExpression);
boundLeft = this.BindExpression(exprSyntax, diagnostics); // Not Color Color issues with ->
// CONSIDER: another approach would be to construct a BoundPointerMemberAccess (assuming such a type existed),
// but that would be much more cumbersome because we'd be unable to build upon the BindMemberAccess infrastructure,
// which expects a receiver.
// Dereference before binding member;
TypeSymbol pointedAtType;
bool hasErrors;
BindPointerIndirectionExpressionInternal(node, boundLeft, diagnostics, out pointedAtType, out hasErrors);
// If there is no pointed-at type, fall back on the actual type (i.e. assume the user meant "." instead of "->").
if (ReferenceEquals(pointedAtType, null))
{
boundLeft = ToBadExpression(boundLeft);
}
else
{
boundLeft = new BoundPointerIndirectionOperator(exprSyntax, boundLeft, pointedAtType, hasErrors)
{
WasCompilerGenerated = true, // don't interfere with the type info for exprSyntax.
};
}
}
return BindMemberAccessWithBoundLeft(node, boundLeft, node.Name, node.OperatorToken, invoked, indexed, diagnostics);
}
/// <summary>
/// Attempt to bind the LHS of a member access expression. If this is a Color Color case (spec 7.6.4.1),
/// then return a BoundExpression if we can easily disambiguate or a BoundTypeOrValueExpression if we
/// cannot. If this is not a Color Color case, then return null.
/// </summary>
private BoundExpression BindLeftOfPotentialColorColorMemberAccess(ExpressionSyntax left, DiagnosticBag diagnostics)
{
// SPEC: 7.6.4.1 Identical simple names and type names
// SPEC: In a member access of the form E.I, if E is a single identifier, and if the meaning of E as
// SPEC: a simple-name (spec 7.6.2) is a constant, field, property, local variable, or parameter with the
// SPEC: same type as the meaning of E as a type-name (spec 3.8), then both possible meanings of E are
// SPEC: permitted. The two possible meanings of E.I are never ambiguous, since I must necessarily be
// SPEC: a member of the type E in both cases. In other words, the rule simply permits access to the
// SPEC: static members and nested types of E where a compile-time error would otherwise have occurred.
if (left.Kind() == SyntaxKind.IdentifierName)
{
var node = (IdentifierNameSyntax)left;
var valueDiagnostics = DiagnosticBag.GetInstance();
var boundValue = BindIdentifier(node, invoked: false, indexed: false, diagnostics: valueDiagnostics);
Symbol leftSymbol;
if (boundValue.Kind == BoundKind.Conversion)
{
// BindFieldAccess may insert a conversion if binding occurs
// within an enum member initializer.
leftSymbol = ((BoundConversion)boundValue).Operand.ExpressionSymbol;
}
else
{
leftSymbol = boundValue.ExpressionSymbol;
}
if ((object)leftSymbol != null)
{
switch (leftSymbol.Kind)
{
case SymbolKind.Field:
case SymbolKind.Local:
case SymbolKind.Parameter:
case SymbolKind.Property:
case SymbolKind.RangeVariable:
var leftType = boundValue.Type;
Debug.Assert((object)leftType != null);
var leftName = node.Identifier.ValueText;
if (leftType.Name == leftName || IsUsingAliasInScope(leftName))
{
var typeDiagnostics = new DiagnosticBag();
var boundType = BindNamespaceOrType(node, typeDiagnostics);
if (TypeSymbol.Equals(boundType.Type, leftType, TypeCompareKind.ConsiderEverything2))
{
// NOTE: ReplaceTypeOrValueReceiver will call CheckValue explicitly.
var newValueDiagnostics = new DiagnosticBag();
newValueDiagnostics.AddRangeAndFree(valueDiagnostics);
return new BoundTypeOrValueExpression(left, new BoundTypeOrValueData(leftSymbol, boundValue, newValueDiagnostics, boundType, typeDiagnostics), leftType);
}
}
break;
// case SymbolKind.Event: //SPEC: 7.6.4.1 (a.k.a. Color Color) doesn't cover events
}
}
// Not a Color Color case; return the bound member.
// NOTE: it is up to the caller to call CheckValue on the result.
diagnostics.AddRangeAndFree(valueDiagnostics);
return boundValue;
}
// NOTE: it is up to the caller to call CheckValue on the result.
return BindExpression(left, diagnostics);
}
// returns true if name matches a using alias in scope
// NOTE: when true is returned, the corresponding using is also marked as "used"
private bool IsUsingAliasInScope(string name)
{
var isSemanticModel = this.IsSemanticModelBinder;
for (var chain = this.ImportChain; chain != null; chain = chain.ParentOpt)
{
if (chain.Imports.IsUsingAlias(name, isSemanticModel))
{
return true;
}
}
return false;
}
private BoundExpression BindDynamicMemberAccess(
ExpressionSyntax node,
BoundExpression boundLeft,
SimpleNameSyntax right,
bool invoked,
bool indexed,
DiagnosticBag diagnostics)
{
// We have an expression of the form "dynExpr.Name" or "dynExpr.Name<X>"
SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax = right.Kind() == SyntaxKind.GenericName ?
((GenericNameSyntax)right).TypeArgumentList.Arguments :
default(SeparatedSyntaxList<TypeSyntax>);
bool rightHasTypeArguments = typeArgumentsSyntax.Count > 0;
ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations = rightHasTypeArguments ?
BindTypeArguments(typeArgumentsSyntax, diagnostics) :
default(ImmutableArray<TypeWithAnnotations>);
bool hasErrors = false;
if (!invoked && rightHasTypeArguments)
{
// error CS0307: The property 'P' cannot be used with type arguments
Error(diagnostics, ErrorCode.ERR_TypeArgsNotAllowed, right, right.Identifier.Text, SymbolKind.Property.Localize());
hasErrors = true;
}
if (rightHasTypeArguments)
{
for (int i = 0; i < typeArgumentsWithAnnotations.Length; ++i)
{
var typeArgument = typeArgumentsWithAnnotations[i];
if ((typeArgument.Type.IsPointerType()) || typeArgument.Type.IsRestrictedType())
{
// "The type '{0}' may not be used as a type argument"
Error(diagnostics, ErrorCode.ERR_BadTypeArgument, typeArgumentsSyntax[i], typeArgument.Type);
hasErrors = true;
}
}
}
return new BoundDynamicMemberAccess(
syntax: node,
receiver: boundLeft,
typeArgumentsOpt: typeArgumentsWithAnnotations,
name: right.Identifier.ValueText,
invoked: invoked,
indexed: indexed,
type: Compilation.DynamicType,
hasErrors: hasErrors);
}
/// <summary>
/// Bind the RHS of a member access expression, given the bound LHS.
/// It is assumed that CheckValue has not been called on the LHS.
/// </summary>
private BoundExpression BindMemberAccessWithBoundLeft(
ExpressionSyntax node,
BoundExpression boundLeft,
SimpleNameSyntax right,
SyntaxToken operatorToken,
bool invoked,
bool indexed,
DiagnosticBag diagnostics)
{
Debug.Assert(node != null);
Debug.Assert(boundLeft != null);
boundLeft = MakeMemberAccessValue(boundLeft, diagnostics);
TypeSymbol leftType = boundLeft.Type;
if ((object)leftType != null && leftType.IsDynamic())
{
// There are some sources of a `dynamic` typed value that can be known before runtime
// to be invalid. For example, accessing a set-only property whose type is dynamic:
// dynamic Goo { set; }
// If Goo itself is a dynamic thing (e.g. in `x.Goo.Bar`, `x` is dynamic, and we're
// currently checking Bar), then CheckValue will do nothing.
boundLeft = CheckValue(boundLeft, BindValueKind.RValue, diagnostics);
return BindDynamicMemberAccess(node, boundLeft, right, invoked, indexed, diagnostics);
}
// No member accesses on void
if ((object)leftType != null && leftType.IsVoidType())
{
diagnostics.Add(ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), SyntaxFacts.GetText(operatorToken.Kind()), leftType);
return BadExpression(node, boundLeft);
}
// No member accesses on default
if (boundLeft.IsLiteralDefault())
{
DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadUnaryOp, SyntaxFacts.GetText(operatorToken.Kind()), "default");
diagnostics.Add(new CSDiagnostic(diagnosticInfo, operatorToken.GetLocation()));
return BadExpression(node, boundLeft);
}
if (boundLeft.Kind == BoundKind.UnboundLambda)
{
Debug.Assert((object)leftType == null);
var msgId = ((UnboundLambda)boundLeft).MessageID;
diagnostics.Add(ErrorCode.ERR_BadUnaryOp, node.Location, SyntaxFacts.GetText(operatorToken.Kind()), msgId.Localize());
return BadExpression(node, boundLeft);
}
var lookupResult = LookupResult.GetInstance();
try
{
LookupOptions options = LookupOptions.AllMethodsOnArityZero;
if (invoked)
{
options |= LookupOptions.MustBeInvocableIfMember;
}
var typeArgumentsSyntax = right.Kind() == SyntaxKind.GenericName ? ((GenericNameSyntax)right).TypeArgumentList.Arguments : default(SeparatedSyntaxList<TypeSyntax>);
bool rightHasTypeArguments = typeArgumentsSyntax.Count > 0;
var typeArguments = rightHasTypeArguments ? BindTypeArguments(typeArgumentsSyntax, diagnostics) : default(ImmutableArray<TypeWithAnnotations>);
// A member-access consists of a primary-expression, a predefined-type, or a
// qualified-alias-member, followed by a "." token, followed by an identifier,
// optionally followed by a type-argument-list.
// A member-access is either of the form E.I or of the form E.I<A1, ..., AK>, where
// E is a primary-expression, I is a single identifier and <A1, ..., AK> is an
// optional type-argument-list. When no type-argument-list is specified, consider K
// to be zero.
// UNDONE: A member-access with a primary-expression of type dynamic is dynamically bound.
// UNDONE: In this case the compiler classifies the member access as a property access of
// UNDONE: type dynamic. The rules below to determine the meaning of the member-access are
// UNDONE: then applied at run-time, using the run-time type instead of the compile-time
// UNDONE: type of the primary-expression. If this run-time classification leads to a method
// UNDONE: group, then the member access must be the primary-expression of an invocation-expression.
// The member-access is evaluated and classified as follows:
var rightName = right.Identifier.ValueText;
var rightArity = right.Arity;
switch (boundLeft.Kind)
{
case BoundKind.NamespaceExpression:
{
// If K is zero and E is a namespace and E contains a nested namespace with name I,
// then the result is that namespace.
var ns = ((BoundNamespaceExpression)boundLeft).NamespaceSymbol;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
this.LookupMembersWithFallback(lookupResult, ns, rightName, rightArity, ref useSiteDiagnostics, options: options);
diagnostics.Add(right, useSiteDiagnostics);
ArrayBuilder<Symbol> symbols = lookupResult.Symbols;
if (lookupResult.IsMultiViable)
{
bool wasError;
Symbol sym = ResultSymbol(lookupResult, rightName, rightArity, node, diagnostics, false, out wasError, ns, options);
if (wasError)
{
return new BoundBadExpression(node, LookupResultKind.Ambiguous, lookupResult.Symbols.AsImmutable(), ImmutableArray.Create(boundLeft), CreateErrorType(rightName), hasErrors: true);
}
else if (sym.Kind == SymbolKind.Namespace)
{
return new BoundNamespaceExpression(node, (NamespaceSymbol)sym);
}
else
{
Debug.Assert(sym.Kind == SymbolKind.NamedType);
var type = (NamedTypeSymbol)sym;
if (rightHasTypeArguments)
{
type = ConstructNamedTypeUnlessTypeArgumentOmitted(right, type, typeArgumentsSyntax, typeArguments, diagnostics);
}
ReportDiagnosticsIfObsolete(diagnostics, type, node, hasBaseReceiver: false);
return new BoundTypeExpression(node, null, type);
}
}
else if (lookupResult.Kind == LookupResultKind.WrongArity)
{
Debug.Assert(symbols.Count > 0);
Debug.Assert(symbols[0].Kind == SymbolKind.NamedType);
Error(diagnostics, lookupResult.Error, right);
return new BoundTypeExpression(node, null,
new ExtendedErrorTypeSymbol(GetContainingNamespaceOrType(symbols[0]), symbols.ToImmutable(), lookupResult.Kind, lookupResult.Error, rightArity));
}
else if (lookupResult.Kind == LookupResultKind.Empty)
{
Debug.Assert(lookupResult.IsClear, "If there's a legitimate reason for having candidates without a reason, then we should produce something intelligent in such cases.");
Debug.Assert(lookupResult.Error == null);
NotFound(node, rightName, rightArity, rightName, diagnostics, aliasOpt: null, qualifierOpt: ns, options: options);
return new BoundBadExpression(node, lookupResult.Kind, symbols.AsImmutable(), ImmutableArray.Create(boundLeft), CreateErrorType(rightName), hasErrors: true);
}
break;
}
case BoundKind.TypeExpression:
{
Debug.Assert((object)leftType != null);
if (leftType.TypeKind == TypeKind.TypeParameter)
{
Error(diagnostics, ErrorCode.ERR_BadSKunknown, boundLeft.Syntax, leftType, MessageID.IDS_SK_TYVAR.Localize());
return BadExpression(node, LookupResultKind.NotAValue, boundLeft);
}
else if (this.EnclosingNameofArgument == node)
{
// Support selecting an extension method from a type name in nameof(.)
return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics);
}
else
{
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
this.LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteDiagnostics, basesBeingResolved: null, options: options);
diagnostics.Add(right, useSiteDiagnostics);
if (lookupResult.IsMultiViable)
{
return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArguments, lookupResult, BoundMethodGroupFlags.None, diagnostics: diagnostics);
}
}
break;
}
case BoundKind.TypeOrValueExpression:
{
// CheckValue call will occur in ReplaceTypeOrValueReceiver.
// NOTE: This means that we won't get CheckValue diagnostics in error scenarios,
// but they would be cascading anyway.
return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics);
}
default:
{
// Can't dot into the null literal
if (boundLeft.Kind == BoundKind.Literal && ((BoundLiteral)boundLeft).ConstantValueOpt == ConstantValue.Null)
{
if (!boundLeft.HasAnyErrors)
{
Error(diagnostics, ErrorCode.ERR_BadUnaryOp, node, operatorToken.Text, boundLeft.Display);
}
return BadExpression(node, boundLeft);
}
else if ((object)leftType != null)
{
// NB: We don't know if we really only need RValue access, or if we are actually
// passing the receiver implicitly by ref (e.g. in a struct instance method invocation).
// These checks occur later.
boundLeft = CheckValue(boundLeft, BindValueKind.RValue, diagnostics);
return BindInstanceMemberAccess(node, right, boundLeft, rightName, rightArity, typeArgumentsSyntax, typeArguments, invoked, indexed, diagnostics);
}
break;
}
}
this.BindMemberAccessReportError(node, right, rightName, boundLeft, lookupResult.Error, diagnostics);
return BindMemberAccessBadResult(node, rightName, boundLeft, lookupResult.Error, lookupResult.Symbols.ToImmutable(), lookupResult.Kind);
}
finally
{
lookupResult.Free();
}
}
private void WarnOnAccessOfOffDefault(SyntaxNode node, BoundExpression boundLeft, DiagnosticBag diagnostics)
{
if (boundLeft != null && boundLeft.Kind == BoundKind.DefaultExpression && boundLeft.ConstantValue == ConstantValue.Null &&
Compilation.LanguageVersion < MessageID.IDS_FeatureNullableReferenceTypes.RequiredVersion())
{
Error(diagnostics, ErrorCode.WRN_DotOnDefault, node, boundLeft.Type);
}
}
/// <summary>
/// Create a value from the expression that can be used as a left-hand-side
/// of a member access. This method special-cases method and property
/// groups only. All other expressions are returned as is.
/// </summary>
private BoundExpression MakeMemberAccessValue(BoundExpression expr, DiagnosticBag diagnostics)
{
switch (expr.Kind)
{
case BoundKind.MethodGroup:
{
var methodGroup = (BoundMethodGroup)expr;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
var resolution = this.ResolveMethodGroup(methodGroup, analyzedArguments: null, isMethodGroupConversion: false, useSiteDiagnostics: ref useSiteDiagnostics);
diagnostics.Add(expr.Syntax, useSiteDiagnostics);
if (!expr.HasAnyErrors)
{
diagnostics.AddRange(resolution.Diagnostics);
if (resolution.MethodGroup != null && !resolution.HasAnyErrors)
{
Debug.Assert(!resolution.IsEmpty);
var method = resolution.MethodGroup.Methods[0];
Error(diagnostics, ErrorCode.ERR_BadSKunknown, methodGroup.NameSyntax, method, MessageID.IDS_SK_METHOD.Localize());
}
}
expr = this.BindMemberAccessBadResult(methodGroup);
resolution.Free();
return expr;
}
case BoundKind.PropertyGroup:
return BindIndexedPropertyAccess((BoundPropertyGroup)expr, mustHaveAllOptionalParameters: false, diagnostics: diagnostics);
default:
return expr;
}
}
private BoundExpression BindInstanceMemberAccess(
SyntaxNode node,
SyntaxNode right,
BoundExpression boundLeft,
string rightName,
int rightArity,
SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax,
ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations,
bool invoked,
bool indexed,
DiagnosticBag diagnostics)
{
Debug.Assert(rightArity == (typeArgumentsWithAnnotations.IsDefault ? 0 : typeArgumentsWithAnnotations.Length));
var leftType = boundLeft.Type;
LookupOptions options = LookupOptions.AllMethodsOnArityZero;
if (invoked)
{
options |= LookupOptions.MustBeInvocableIfMember;
}
var lookupResult = LookupResult.GetInstance();
try
{
// If E is a property access, indexer access, variable, or value, the type of
// which is T, and a member lookup of I in T with K type arguments produces a
// match, then E.I is evaluated and classified as follows:
// UNDONE: Classify E as prop access, indexer access, variable or value
bool leftIsBaseReference = boundLeft.Kind == BoundKind.BaseReference;
if (leftIsBaseReference)
{
options |= LookupOptions.UseBaseReferenceAccessibility;
}
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
this.LookupMembersWithFallback(lookupResult, leftType, rightName, rightArity, ref useSiteDiagnostics, basesBeingResolved: null, options: options);
diagnostics.Add(right, useSiteDiagnostics);
// SPEC: Otherwise, an attempt is made to process E.I as an extension method invocation.
// SPEC: If this fails, E.I is an invalid member reference, and a binding-time error occurs.
var searchExtensionMethodsIfNecessary = !leftIsBaseReference;
BoundMethodGroupFlags flags = 0;
if (searchExtensionMethodsIfNecessary)
{
flags |= BoundMethodGroupFlags.SearchExtensionMethods;
}
if (lookupResult.IsMultiViable)
{
return BindMemberOfType(node, right, rightName, rightArity, indexed, boundLeft, typeArgumentsSyntax, typeArgumentsWithAnnotations, lookupResult, flags, diagnostics);
}
if (searchExtensionMethodsIfNecessary)
{
var boundMethodGroup = new BoundMethodGroup(
node,
typeArgumentsWithAnnotations,
boundLeft,
rightName,
lookupResult.Symbols.All(s => s.Kind == SymbolKind.Method) ? lookupResult.Symbols.SelectAsArray(s_toMethodSymbolFunc) : ImmutableArray<MethodSymbol>.Empty,
lookupResult,
flags);
if (!boundMethodGroup.HasErrors && boundMethodGroup.ResultKind == LookupResultKind.Empty && typeArgumentsSyntax.Any(SyntaxKind.OmittedTypeArgument))
{
Error(diagnostics, ErrorCode.ERR_BadArity, node, rightName, MessageID.IDS_MethodGroup.Localize(), typeArgumentsSyntax.Count);
}
return boundMethodGroup;
}
this.BindMemberAccessReportError(node, right, rightName, boundLeft, lookupResult.Error, diagnostics);
return BindMemberAccessBadResult(node, rightName, boundLeft, lookupResult.Error, lookupResult.Symbols.ToImmutable(), lookupResult.Kind);
}
finally
{
lookupResult.Free();
}
}
private void BindMemberAccessReportError(BoundMethodGroup node, DiagnosticBag diagnostics)
{
var nameSyntax = node.NameSyntax;
var syntax = node.MemberAccessExpressionSyntax ?? nameSyntax;
this.BindMemberAccessReportError(syntax, nameSyntax, node.Name, node.ReceiverOpt, node.LookupError, diagnostics);
}
/// <summary>
/// Report the error from member access lookup. Or, if there
/// was no explicit error from lookup, report "no such member".
/// </summary>
private void BindMemberAccessReportError(
SyntaxNode node,
SyntaxNode name,
string plainName,
BoundExpression boundLeft,
DiagnosticInfo lookupError,
DiagnosticBag diagnostics)
{
if (boundLeft.HasAnyErrors && boundLeft.Kind != BoundKind.TypeOrValueExpression)
{
return;
}
if (lookupError != null)
{
// CONSIDER: there are some cases where Dev10 uses the span of "node",
// rather than "right".
diagnostics.Add(new CSDiagnostic(lookupError, name.Location));
}
else if (node.IsQuery())
{
ReportQueryLookupFailed(node, boundLeft, plainName, ImmutableArray<Symbol>.Empty, diagnostics);
}
else
{
if ((object)boundLeft.Type == null)
{
Error(diagnostics, ErrorCode.ERR_NoSuchMember, name, boundLeft.Display, plainName);
}
else if (boundLeft.Kind == BoundKind.TypeExpression ||
boundLeft.Kind == BoundKind.BaseReference ||
node.Kind() == SyntaxKind.AwaitExpression && plainName == WellKnownMemberNames.GetResult)
{
Error(diagnostics, ErrorCode.ERR_NoSuchMember, name, boundLeft.Type, plainName);
}
else if (WouldUsingSystemFindExtension(boundLeft.Type, plainName))
{
Error(diagnostics, ErrorCode.ERR_NoSuchMemberOrExtensionNeedUsing, name, boundLeft.Type, plainName, "System");
}
else
{
Error(diagnostics, ErrorCode.ERR_NoSuchMemberOrExtension, name, boundLeft.Type, plainName);
}
}
}
private bool WouldUsingSystemFindExtension(TypeSymbol receiver, string methodName)
{
// we have a special case to make the diagnostic for await expressions more clear for Windows:
// if the receiver type is a windows RT async interface and the method name is GetAwaiter,
// then we would suggest a using directive for "System".
// TODO: we should check if such a using directive would actually help, or if there is already one in scope.
return methodName == WellKnownMemberNames.GetAwaiter && ImplementsWinRTAsyncInterface(receiver);
}
/// <summary>
/// Return true if the given type is or implements a WinRTAsyncInterface.
/// </summary>
private bool ImplementsWinRTAsyncInterface(TypeSymbol type)
{
return IsWinRTAsyncInterface(type) || type.AllInterfacesNoUseSiteDiagnostics.Any(i => IsWinRTAsyncInterface(i));
}
private bool IsWinRTAsyncInterface(TypeSymbol type)
{
if (!type.IsInterfaceType())
{
return false;
}
var namedType = ((NamedTypeSymbol)type).ConstructedFrom;
return
TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncAction), TypeCompareKind.ConsiderEverything2) ||
TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncActionWithProgress_T), TypeCompareKind.ConsiderEverything2) ||
TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncOperation_T), TypeCompareKind.ConsiderEverything2) ||
TypeSymbol.Equals(namedType, Compilation.GetWellKnownType(WellKnownType.Windows_Foundation_IAsyncOperationWithProgress_T2), TypeCompareKind.ConsiderEverything2);
}
private BoundExpression BindMemberAccessBadResult(BoundMethodGroup node)
{
var nameSyntax = node.NameSyntax;
var syntax = node.MemberAccessExpressionSyntax ?? nameSyntax;
return this.BindMemberAccessBadResult(syntax, node.Name, node.ReceiverOpt, node.LookupError, StaticCast<Symbol>.From(node.Methods), node.ResultKind);
}
/// <summary>
/// Return a BoundExpression representing the invalid member.
/// </summary>
private BoundExpression BindMemberAccessBadResult(
SyntaxNode node,
string nameString,
BoundExpression boundLeft,
DiagnosticInfo lookupError,
ImmutableArray<Symbol> symbols,
LookupResultKind lookupKind)
{
if (symbols.Length > 0 && symbols[0].Kind == SymbolKind.Method)
{
var builder = ArrayBuilder<MethodSymbol>.GetInstance();
foreach (var s in symbols)
{
var m = s as MethodSymbol;
if ((object)m != null) builder.Add(m);
}
var methods = builder.ToImmutableAndFree();
// Expose the invalid methods as a BoundMethodGroup.
// Since we do not want to perform further method
// lookup, searchExtensionMethods is set to false.
// Don't bother calling ConstructBoundMethodGroupAndReportOmittedTypeArguments -
// we've reported other errors.
return new BoundMethodGroup(
node,
default(ImmutableArray<TypeWithAnnotations>),
nameString,
methods,
methods.Length == 1 ? methods[0] : null,
lookupError,
flags: BoundMethodGroupFlags.None,
receiverOpt: boundLeft,
resultKind: lookupKind,
hasErrors: true);
}
var symbolOpt = symbols.Length == 1 ? symbols[0] : null;
return new BoundBadExpression(
node,
lookupKind,
(object)symbolOpt == null ? ImmutableArray<Symbol>.Empty : ImmutableArray.Create(symbolOpt),
boundLeft == null ? ImmutableArray<BoundExpression>.Empty : ImmutableArray.Create(boundLeft),
GetNonMethodMemberType(symbolOpt));
}
private TypeSymbol GetNonMethodMemberType(Symbol symbolOpt)
{
TypeSymbol resultType = null;
if ((object)symbolOpt != null)
{
switch (symbolOpt.Kind)
{
case SymbolKind.Field:
resultType = ((FieldSymbol)symbolOpt).GetFieldType(this.FieldsBeingBound).Type;
break;
case SymbolKind.Property:
resultType = ((PropertySymbol)symbolOpt).Type;
break;
case SymbolKind.Event:
resultType = ((EventSymbol)symbolOpt).Type;
break;
}
}
return resultType ?? CreateErrorType();
}
/// <summary>
/// Combine the receiver and arguments of an extension method
/// invocation into a single argument list to allow overload resolution
/// to treat the invocation as a static method invocation with no receiver.
/// </summary>
private static void CombineExtensionMethodArguments(BoundExpression receiver, AnalyzedArguments originalArguments, AnalyzedArguments extensionMethodArguments)
{
Debug.Assert(receiver != null);
Debug.Assert(extensionMethodArguments.Arguments.Count == 0);
Debug.Assert(extensionMethodArguments.Names.Count == 0);
Debug.Assert(extensionMethodArguments.RefKinds.Count == 0);
extensionMethodArguments.IsExtensionMethodInvocation = true;
extensionMethodArguments.Arguments.Add(receiver);
extensionMethodArguments.Arguments.AddRange(originalArguments.Arguments);
if (originalArguments.Names.Count > 0)
{
extensionMethodArguments.Names.Add(null);
extensionMethodArguments.Names.AddRange(originalArguments.Names);
}
if (originalArguments.RefKinds.Count > 0)
{
extensionMethodArguments.RefKinds.Add(RefKind.None);
extensionMethodArguments.RefKinds.AddRange(originalArguments.RefKinds);
}
}
/// <summary>
/// Binds a static or instance member access.
/// </summary>
private BoundExpression BindMemberOfType(
SyntaxNode node,
SyntaxNode right,
string plainName,
int arity,
bool indexed,
BoundExpression left,
SeparatedSyntaxList<TypeSyntax> typeArgumentsSyntax,
ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations,
LookupResult lookupResult,
BoundMethodGroupFlags methodGroupFlags,
DiagnosticBag diagnostics)
{
Debug.Assert(node != null);
Debug.Assert(left != null);
Debug.Assert(lookupResult.IsMultiViable);
Debug.Assert(lookupResult.Symbols.Any());
var members = ArrayBuilder<Symbol>.GetInstance();
BoundExpression result;
bool wasError;
Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, right, plainName, arity, members, diagnostics, out wasError);
if ((object)symbol == null)
{
Debug.Assert(members.Count > 0);
// If I identifies one or more methods, then the result is a method group with
// no associated instance expression. If a type argument list was specified, it
// is used in calling a generic method.
// (Note that for static methods, we are stashing away the type expression in
// the receiver of the method group, even though the spec notes that there is
// no associated instance expression.)
result = ConstructBoundMemberGroupAndReportOmittedTypeArguments(
node,
typeArgumentsSyntax,
typeArgumentsWithAnnotations,
left,
plainName,
members,
lookupResult,
methodGroupFlags,
wasError,
diagnostics);
}
else
{
// methods are special because of extension methods.
Debug.Assert(symbol.Kind != SymbolKind.Method);
left = ReplaceTypeOrValueReceiver(left, symbol.IsStatic || symbol.Kind == SymbolKind.NamedType, diagnostics);
// Events are handled later as we don't know yet if we are binding to the event or it's backing field.
if (symbol.Kind != SymbolKind.Event)
{
ReportDiagnosticsIfObsolete(diagnostics, symbol, node, hasBaseReceiver: left.Kind == BoundKind.BaseReference);
}
switch (symbol.Kind)
{
case SymbolKind.NamedType:
case SymbolKind.ErrorType:
if (IsInstanceReceiver(left) == true && !wasError)
{
// CS0572: 'B': cannot reference a type through an expression; try 'A.B' instead
Error(diagnostics, ErrorCode.ERR_BadTypeReference, right, plainName, symbol);
wasError = true;
}
// If I identifies a type, then the result is that type constructed with
// the given type arguments.
var type = (NamedTypeSymbol)symbol;
if (!typeArgumentsWithAnnotations.IsDefault)
{
type = ConstructNamedTypeUnlessTypeArgumentOmitted(right, type, typeArgumentsSyntax, typeArgumentsWithAnnotations, diagnostics);
}
result = new BoundTypeExpression(
syntax: node,
aliasOpt: null,
boundContainingTypeOpt: left as BoundTypeExpression,
boundDimensionsOpt: ImmutableArray<BoundExpression>.Empty,
typeWithAnnotations: TypeWithAnnotations.Create(type));
break;
case SymbolKind.Property:
// If I identifies a static property, then the result is a property
// access with no associated instance expression.
result = BindPropertyAccess(node, left, (PropertySymbol)symbol, diagnostics, lookupResult.Kind, hasErrors: wasError);
break;
case SymbolKind.Event:
// If I identifies a static event, then the result is an event
// access with no associated instance expression.
result = BindEventAccess(node, left, (EventSymbol)symbol, diagnostics, lookupResult.Kind, hasErrors: wasError);
break;
case SymbolKind.Field:
// If I identifies a static field:
// UNDONE: If the field is readonly and the reference occurs outside the static constructor of
// UNDONE: the class or struct in which the field is declared, then the result is a value, namely
// UNDONE: the value of the static field I in E.
// UNDONE: Otherwise, the result is a variable, namely the static field I in E.
// UNDONE: Need a way to mark an expression node as "I am a variable, not a value".
result = BindFieldAccess(node, left, (FieldSymbol)symbol, diagnostics, lookupResult.Kind, indexed, hasErrors: wasError);
break;
default:
throw ExceptionUtilities.UnexpectedValue(symbol.Kind);
}
}
members.Free();
return result;
}
private MethodGroupResolution BindExtensionMethod(
SyntaxNode expression,
string methodName,
AnalyzedArguments analyzedArguments,
BoundExpression left,
ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations,
bool isMethodGroupConversion,
RefKind returnRefKind,
TypeSymbol returnType)
{
var firstResult = new MethodGroupResolution();
AnalyzedArguments actualArguments = null;
foreach (var scope in new ExtensionMethodScopes(this))
{
var methodGroup = MethodGroup.GetInstance();
var diagnostics = DiagnosticBag.GetInstance();
this.PopulateExtensionMethodsFromSingleBinder(scope, methodGroup, expression, left, methodName, typeArgumentsWithAnnotations, diagnostics);
// Arguments will be null if the caller is resolving to the first method group that can accept
// that receiver, regardless of arguments, when the signature cannot
// be inferred. (In the case of nameof(o.M) or the error case of o.M = null; for instance.)
if (analyzedArguments == null)
{
if (expression == EnclosingNameofArgument)
{
for (int i = methodGroup.Methods.Count - 1; i >= 0; i--)
{
if ((object)methodGroup.Methods[i].ReduceExtensionMethod(left.Type) == null) methodGroup.Methods.RemoveAt(i);
}
}
if (methodGroup.Methods.Count != 0)
{
return new MethodGroupResolution(methodGroup, diagnostics.ToReadOnlyAndFree());
}
}
if (methodGroup.Methods.Count == 0)
{
methodGroup.Free();
diagnostics.Free();
continue;
}
if (actualArguments == null)
{
// Create a set of arguments for overload resolution of the
// extension methods that includes the "this" parameter.
actualArguments = AnalyzedArguments.GetInstance();
CombineExtensionMethodArguments(left, analyzedArguments, actualArguments);
}
var overloadResolutionResult = OverloadResolutionResult<MethodSymbol>.GetInstance();
bool allowRefOmittedArguments = methodGroup.Receiver.IsExpressionOfComImportType();
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
OverloadResolution.MethodInvocationOverloadResolution(
methods: methodGroup.Methods,
typeArguments: methodGroup.TypeArguments,
receiver: methodGroup.Receiver,
arguments: actualArguments,
result: overloadResolutionResult,
useSiteDiagnostics: ref useSiteDiagnostics,
isMethodGroupConversion: isMethodGroupConversion,
allowRefOmittedArguments: allowRefOmittedArguments,
returnRefKind: returnRefKind,
returnType: returnType);
diagnostics.Add(expression, useSiteDiagnostics);
var sealedDiagnostics = diagnostics.ToReadOnlyAndFree();
// Note: the MethodGroupResolution instance is responsible for freeing its copy of actual arguments
var result = new MethodGroupResolution(methodGroup, null, overloadResolutionResult, AnalyzedArguments.GetInstance(actualArguments), methodGroup.ResultKind, sealedDiagnostics);
// If the search in the current scope resulted in any applicable method (regardless of whether a best
// applicable method could be determined) then our search is complete. Otherwise, store aside the
// first non-applicable result and continue searching for an applicable result.
if (result.HasAnyApplicableMethod)
{
if (!firstResult.IsEmpty)
{
firstResult.MethodGroup.Free();
firstResult.OverloadResolutionResult.Free();
}
return result;
}
else if (firstResult.IsEmpty)
{
firstResult = result;
}
else
{
// Neither the first result, nor applicable. No need to save result.
overloadResolutionResult.Free();
methodGroup.Free();
}
}
Debug.Assert((actualArguments == null) || !firstResult.IsEmpty);
actualArguments?.Free();
return firstResult;
}
private void PopulateExtensionMethodsFromSingleBinder(
ExtensionMethodScope scope,
MethodGroup methodGroup,
SyntaxNode node,
BoundExpression left,
string rightName,
ImmutableArray<TypeWithAnnotations> typeArgumentsWithAnnotations,
DiagnosticBag diagnostics)
{
int arity;
LookupOptions options;
if (typeArgumentsWithAnnotations.IsDefault)
{
arity = 0;
options = LookupOptions.AllMethodsOnArityZero;
}
else
{
arity = typeArgumentsWithAnnotations.Length;
options = LookupOptions.Default;
}
var lookupResult = LookupResult.GetInstance();
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
this.LookupExtensionMethodsInSingleBinder(scope, lookupResult, rightName, arity, options, ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
if (lookupResult.IsMultiViable)
{
Debug.Assert(lookupResult.Symbols.Any());
var members = ArrayBuilder<Symbol>.GetInstance();
bool wasError;
Symbol symbol = GetSymbolOrMethodOrPropertyGroup(lookupResult, node, rightName, arity, members, diagnostics, out wasError);
Debug.Assert((object)symbol == null);
Debug.Assert(members.Count > 0);
methodGroup.PopulateWithExtensionMethods(left, members, typeArgumentsWithAnnotations, lookupResult.Kind);
members.Free();
}
lookupResult.Free();
}
protected BoundExpression BindFieldAccess(
SyntaxNode node,
BoundExpression receiver,
FieldSymbol fieldSymbol,
DiagnosticBag diagnostics,
LookupResultKind resultKind,
bool indexed,
bool hasErrors)
{
bool hasError = false;
NamedTypeSymbol type = fieldSymbol.ContainingType;
var isEnumField = (fieldSymbol.IsStatic && type.IsEnumType());
if (isEnumField && !type.IsValidEnumType())
{
Error(diagnostics, ErrorCode.ERR_BindToBogus, node, fieldSymbol);
hasError = true;
}
if (!hasError)
{
hasError = this.CheckInstanceOrStatic(node, receiver, fieldSymbol, ref resultKind, diagnostics);
}
if (!hasError && fieldSymbol.IsFixedSizeBuffer && !IsInsideNameof)
{
// SPEC: In a member access of the form E.I, if E is of a struct type and a member lookup of I in
// that struct type identifies a fixed size member, then E.I is evaluated an classified as follows:
// * If the expression E.I does not occur in an unsafe context, a compile-time error occurs.
// * If E is classified as a value, a compile-time error occurs.
// * Otherwise, if E is a moveable variable and the expression E.I is not a fixed_pointer_initializer,
// a compile-time error occurs.
// * Otherwise, E references a fixed variable and the result of the expression is a pointer to the
// first element of the fixed size buffer member I in E. The result is of type S*, where S is
// the element type of I, and is classified as a value.
TypeSymbol receiverType = receiver.Type;
// Reflect errors that have been reported elsewhere...
hasError = (object)receiverType == null || !receiverType.IsValueType;
if (!hasError)
{
var isFixedStatementExpression = SyntaxFacts.IsFixedStatementExpression(node);
if (IsMoveableVariable(receiver, out Symbol accessedLocalOrParameterOpt) != isFixedStatementExpression)
{
if (indexed)
{
// SPEC C# 7.3: If the fixed size buffer access is the receiver of an element_access_expression,
// E may be either fixed or moveable
CheckFeatureAvailability(node, MessageID.IDS_FeatureIndexingMovableFixedBuffers, diagnostics);
}
else
{
Error(diagnostics, isFixedStatementExpression ? ErrorCode.ERR_FixedNotNeeded : ErrorCode.ERR_FixedBufferNotFixed, node);
hasErrors = hasError = true;
}
}
}
if (!hasError)
{
hasError = !CheckValueKind(node, receiver, BindValueKind.FixedReceiver, checkingReceiver: false, diagnostics: diagnostics);
}
}
ConstantValue constantValueOpt = null;
if (fieldSymbol.IsConst && !IsInsideNameof)
{
constantValueOpt = fieldSymbol.GetConstantValue(this.ConstantFieldsInProgress, this.IsEarlyAttributeBinder);
if (constantValueOpt == ConstantValue.Unset)
{
// Evaluating constant expression before dependencies
// have been evaluated. Treat this as a Bad value.
constantValueOpt = ConstantValue.Bad;
}
}
if (!fieldSymbol.IsStatic)
{
WarnOnAccessOfOffDefault(node, receiver, diagnostics);
}
if (!IsBadBaseAccess(node, receiver, fieldSymbol, diagnostics))
{
CheckRuntimeSupportForSymbolAccess(node, receiver, fieldSymbol, diagnostics);
}
TypeSymbol fieldType = fieldSymbol.GetFieldType(this.FieldsBeingBound).Type;
BoundExpression expr = new BoundFieldAccess(node, receiver, fieldSymbol, constantValueOpt, resultKind, fieldType, hasErrors: (hasErrors || hasError));
// Spec 14.3: "Within an enum member initializer, values of other enum members are
// always treated as having the type of their underlying type"
if (this.InEnumMemberInitializer())
{
NamedTypeSymbol enumType = null;
if (isEnumField)
{
// This is an obvious consequence of the spec.
// It is for cases like:
// enum E {
// A,
// B = A + 1, //A is implicitly converted to int (underlying type)
// }
enumType = type;
}
else if (constantValueOpt != null && fieldType.IsEnumType())
{
// This seems like a borderline SPEC VIOLATION that we're preserving for back compat.
// It is for cases like:
// const E e = E.A;
// enum E {
// A,
// B = e + 1, //e is implicitly converted to int (underlying type)
// }
enumType = (NamedTypeSymbol)fieldType;
}
if ((object)enumType != null)
{
NamedTypeSymbol underlyingType = enumType.EnumUnderlyingType;
Debug.Assert((object)underlyingType != null);
expr = new BoundConversion(
node,
expr,
Conversion.ImplicitNumeric,
@checked: true,
explicitCastInCode: false,
conversionGroupOpt: null,
constantValueOpt: expr.ConstantValue,
type: underlyingType);
}
}
return expr;
}
private bool InEnumMemberInitializer()
{
var containingType = this.ContainingType;
return this.InFieldInitializer && (object)containingType != null && containingType.IsEnumType();
}
private BoundExpression BindPropertyAccess(
SyntaxNode node,
BoundExpression receiver,
PropertySymbol propertySymbol,
DiagnosticBag diagnostics,
LookupResultKind lookupResult,
bool hasErrors)
{
bool hasError = this.CheckInstanceOrStatic(node, receiver, propertySymbol, ref lookupResult, diagnostics);
if (!propertySymbol.IsStatic)
{
WarnOnAccessOfOffDefault(node, receiver, diagnostics);
}
return new BoundPropertyAccess(node, receiver, propertySymbol, lookupResult, propertySymbol.Type, hasErrors: (hasErrors || hasError));
}
private void CheckRuntimeSupportForSymbolAccess(SyntaxNode node, BoundExpression receiverOpt, Symbol symbol, DiagnosticBag diagnostics)
{
if (symbol.ContainingType?.IsInterface == true && !Compilation.Assembly.RuntimeSupportsDefaultInterfaceImplementation && Compilation.SourceModule != symbol.ContainingModule)
{
if (!symbol.IsStatic && !(symbol is TypeSymbol) &&
!symbol.IsImplementableInterfaceMember())
{
Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportDefaultInterfaceImplementation, node);
}
else
{
switch (symbol.DeclaredAccessibility)
{
case Accessibility.Protected:
case Accessibility.ProtectedOrInternal:
case Accessibility.ProtectedAndInternal:
Error(diagnostics, ErrorCode.ERR_RuntimeDoesNotSupportProtectedAccessForInterfaceMember, node);
break;
}
}
}
}
private BoundExpression BindEventAccess(
SyntaxNode node,
BoundExpression receiver,
EventSymbol eventSymbol,
DiagnosticBag diagnostics,
LookupResultKind lookupResult,
bool hasErrors)
{
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
bool isUsableAsField = eventSymbol.HasAssociatedField && this.IsAccessible(eventSymbol.AssociatedField, ref useSiteDiagnostics, (receiver != null) ? receiver.Type : null);
diagnostics.Add(node, useSiteDiagnostics);
bool hasError = this.CheckInstanceOrStatic(node, receiver, eventSymbol, ref lookupResult, diagnostics);
if (!eventSymbol.IsStatic)
{
WarnOnAccessOfOffDefault(node, receiver, diagnostics);
}
return new BoundEventAccess(node, receiver, eventSymbol, isUsableAsField, lookupResult, eventSymbol.Type, hasErrors: (hasErrors || hasError));
}
// Say if the receive is an instance or a type, or could be either (returns null).
private static bool? IsInstanceReceiver(BoundExpression receiver)
{
if (receiver == null)
{
return false;
}
else
{
switch (receiver.Kind)
{
case BoundKind.PreviousSubmissionReference:
// Could be either instance or static reference.
return null;
case BoundKind.TypeExpression:
return false;
case BoundKind.QueryClause:
return IsInstanceReceiver(((BoundQueryClause)receiver).Value);
default:
return true;
}
}
}
private bool CheckInstanceOrStatic(
SyntaxNode node,
BoundExpression receiver,
Symbol symbol,
ref LookupResultKind resultKind,
DiagnosticBag diagnostics)
{
bool? instanceReceiver = IsInstanceReceiver(receiver);
if (symbol.IsStatic)
{
if (instanceReceiver == true)
{
ErrorCode errorCode = this.Flags.Includes(BinderFlags.ObjectInitializerMember) ?
ErrorCode.ERR_StaticMemberInObjectInitializer :
ErrorCode.ERR_ObjectProhibited;
Error(diagnostics, errorCode, node, symbol);
resultKind = LookupResultKind.StaticInstanceMismatch;
return true;
}
}
else
{
if (instanceReceiver == false && !IsInsideNameof)
{
Error(diagnostics, ErrorCode.ERR_ObjectRequired, node, symbol);
resultKind = LookupResultKind.StaticInstanceMismatch;
return true;
}
}
return false;
}
/// <summary>
/// Given a viable LookupResult, report any ambiguity errors and return either a single
/// non-method symbol or a method or property group. If the result set represents a
/// collection of methods or a collection of properties where at least one of the properties
/// is an indexed property, then 'methodOrPropertyGroup' is populated with the method or
/// property group and the method returns null. Otherwise, the method returns a single
/// symbol and 'methodOrPropertyGroup' is empty. (Since the result set is viable, there
/// must be at least one symbol.) If the result set is ambiguous - either containing multiple
/// members of different member types, or multiple properties but no indexed properties -
/// then a diagnostic is reported for the ambiguity and a single symbol is returned.
/// </summary>
private Symbol GetSymbolOrMethodOrPropertyGroup(LookupResult result, SyntaxNode node, string plainName, int arity, ArrayBuilder<Symbol> methodOrPropertyGroup, DiagnosticBag diagnostics, out bool wasError)
{
Debug.Assert(!methodOrPropertyGroup.Any());
node = GetNameSyntax(node) ?? node;
wasError = false;
Debug.Assert(result.Kind != LookupResultKind.Empty);
Debug.Assert(!result.Symbols.Any(s => s.IsIndexer()));
Symbol other = null; // different member type from 'methodOrPropertyGroup'
// Populate 'methodOrPropertyGroup' with a set of methods if any,
// or a set of properties if properties but no methods. If there are
// other member types, 'other' will be set to one of those members.
foreach (var symbol in result.Symbols)
{
var kind = symbol.Kind;
if (methodOrPropertyGroup.Count > 0)
{
var existingKind = methodOrPropertyGroup[0].Kind;
if (existingKind != kind)
{
// Mix of different member kinds. Prefer methods over
// properties and properties over other members.
if ((existingKind == SymbolKind.Method) ||
((existingKind == SymbolKind.Property) && (kind != SymbolKind.Method)))
{
other = symbol;
continue;
}
other = methodOrPropertyGroup[0];
methodOrPropertyGroup.Clear();
}
}
if ((kind == SymbolKind.Method) || (kind == SymbolKind.Property))
{
// SPEC VIOLATION: The spec states "Members that include an override modifier are excluded from the set"
// SPEC VIOLATION: However, we are not going to do that here; we will keep the overriding member
// SPEC VIOLATION: in the method group. The reason is because for features like "go to definition"
// SPEC VIOLATION: we wish to go to the overriding member, not to the member of the base class.
// SPEC VIOLATION: Or, for code generation of a call to Int32.ToString() we want to generate
// SPEC VIOLATION: code that directly calls the Int32.ToString method with an int on the stack,
// SPEC VIOLATION: rather than making a virtual call to ToString on a boxed int.
methodOrPropertyGroup.Add(symbol);
}
else
{
other = symbol;
}
}
Debug.Assert(methodOrPropertyGroup.Any() || ((object)other != null));
if ((methodOrPropertyGroup.Count > 0) &&
IsMethodOrPropertyGroup(methodOrPropertyGroup))
{
// Ambiguities between methods and non-methods are reported here,
// but all other ambiguities, including those between properties and
// non-methods, are reported in ResultSymbol.
if ((methodOrPropertyGroup[0].Kind == SymbolKind.Method) || ((object)other == null))
{
// Result will be treated as a method or property group. Any additional
// checks, such as use-site errors, must be handled by the caller when
// converting to method invocation or property access.
if (result.Error != null)
{
Error(diagnostics, result.Error, node);
wasError = (result.Error.Severity == DiagnosticSeverity.Error);
}
return null;
}
}
methodOrPropertyGroup.Clear();
return ResultSymbol(result, plainName, arity, node, diagnostics, false, out wasError);
}
private static bool IsMethodOrPropertyGroup(ArrayBuilder<Symbol> members)
{
Debug.Assert(members.Count > 0);
var member = members[0];
// Members should be a consistent type.
Debug.Assert(members.All(m => m.Kind == member.Kind));
switch (member.Kind)
{
case SymbolKind.Method:
return true;
case SymbolKind.Property:
Debug.Assert(members.All(m => !m.IsIndexer()));
// Do not treat a set of non-indexed properties as a property group, to
// avoid the overhead of a BoundPropertyGroup node and overload
// resolution for the common property access case. If there are multiple
// non-indexed properties (two properties P that differ by custom attributes
// for instance), the expectation is that the caller will report an ambiguity
// and choose one for error recovery.
foreach (PropertySymbol property in members)
{
if (property.IsIndexedProperty)
{
return true;
}
}
return false;
default:
throw ExceptionUtilities.UnexpectedValue(member.Kind);
}
}
private BoundExpression BindElementAccess(ElementAccessExpressionSyntax node, DiagnosticBag diagnostics)
{
BoundExpression receiver = BindExpression(node.Expression, diagnostics: diagnostics, invoked: false, indexed: true);
return BindElementAccess(node, receiver, node.ArgumentList, diagnostics);
}
private BoundExpression BindElementAccess(ExpressionSyntax node, BoundExpression receiver, BracketedArgumentListSyntax argumentList, DiagnosticBag diagnostics)
{
AnalyzedArguments analyzedArguments = AnalyzedArguments.GetInstance();
try
{
BindArgumentsAndNames(argumentList, diagnostics, analyzedArguments);
if (receiver.Kind == BoundKind.PropertyGroup)
{
var propertyGroup = (BoundPropertyGroup)receiver;
return BindIndexedPropertyAccess(node, propertyGroup.ReceiverOpt, propertyGroup.Properties, analyzedArguments, diagnostics);
}
receiver = CheckValue(receiver, BindValueKind.RValue, diagnostics);
return BindElementOrIndexerAccess(node, receiver, analyzedArguments, diagnostics);
}
finally
{
analyzedArguments.Free();
}
}
private BoundExpression BindElementOrIndexerAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, DiagnosticBag diagnostics)
{
if ((object)expr.Type == null)
{
return BadIndexerExpression(node, expr, analyzedArguments, null, diagnostics);
}
WarnOnAccessOfOffDefault(node, expr, diagnostics);
// Did we have any errors?
if (analyzedArguments.HasErrors || expr.HasAnyErrors)
{
// At this point we definitely have reported an error, but we still might be
// able to get more semantic analysis of the indexing operation. We do not
// want to report cascading errors.
DiagnosticBag tmp = DiagnosticBag.GetInstance();
BoundExpression result = BindElementAccessCore(node, expr, analyzedArguments, tmp);
tmp.Free();
return result;
}
return BindElementAccessCore(node, expr, analyzedArguments, diagnostics);
}
private BoundExpression BadIndexerExpression(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, DiagnosticInfo errorOpt, DiagnosticBag diagnostics)
{
if (!expr.HasAnyErrors)
{
diagnostics.Add(errorOpt ?? new CSDiagnosticInfo(ErrorCode.ERR_BadIndexLHS, expr.Display), node.Location);
}
var childBoundNodes = BuildArgumentsForErrorRecovery(analyzedArguments).Add(expr);
return new BoundBadExpression(node, LookupResultKind.Empty, ImmutableArray<Symbol>.Empty, childBoundNodes, CreateErrorType(), hasErrors: true);
}
private BoundExpression BindElementAccessCore(
ExpressionSyntax node,
BoundExpression expr,
AnalyzedArguments arguments,
DiagnosticBag diagnostics)
{
Debug.Assert(node != null);
Debug.Assert(expr != null);
Debug.Assert((object)expr.Type != null);
Debug.Assert(arguments != null);
var exprType = expr.Type;
switch (exprType.TypeKind)
{
case TypeKind.Array:
return BindArrayAccess(node, expr, arguments, diagnostics);
case TypeKind.Dynamic:
return BindDynamicIndexer(node, expr, arguments, ImmutableArray<PropertySymbol>.Empty, diagnostics);
case TypeKind.Pointer:
return BindPointerElementAccess(node, expr, arguments, diagnostics);
case TypeKind.Class:
case TypeKind.Struct:
case TypeKind.Interface:
case TypeKind.TypeParameter:
return BindIndexerAccess(node, expr, arguments, diagnostics);
case TypeKind.Submission: // script class is synthesized and should not be used as a type of an indexer expression:
default:
return BadIndexerExpression(node, expr, arguments, null, diagnostics);
}
}
private BoundExpression BindArrayAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments arguments, DiagnosticBag diagnostics)
{
Debug.Assert(node != null);
Debug.Assert(expr != null);
Debug.Assert(arguments != null);
// For an array access, the primary-no-array-creation-expression of the element-access
// must be a value of an array-type. Furthermore, the argument-list of an array access
// is not allowed to contain named arguments.The number of expressions in the
// argument-list must be the same as the rank of the array-type, and each expression
// must be of type int, uint, long, ulong, or must be implicitly convertible to one or
// more of these types.
if (arguments.Names.Count > 0)
{
Error(diagnostics, ErrorCode.ERR_NamedArgumentForArray, node);
}
bool hasErrors = ReportRefOrOutArgument(arguments, diagnostics);
var arrayType = (ArrayTypeSymbol)expr.Type;
// Note that the spec says to determine which of {int, uint, long, ulong} *each* index
// expression is convertible to. That is not what C# 1 through 4 did; the
// implementations instead determined which of those four types *all* of the index
// expressions converted to.
int rank = arrayType.Rank;
if (arguments.Arguments.Count != rank)
{
Error(diagnostics, ErrorCode.ERR_BadIndexCount, node, rank);
return new BoundArrayAccess(node, expr, BuildArgumentsForErrorRecovery(arguments), arrayType.ElementType, hasErrors: true);
}
// Convert all the arguments to the array index type.
BoundExpression[] convertedArguments = new BoundExpression[arguments.Arguments.Count];
for (int i = 0; i < arguments.Arguments.Count; ++i)
{
BoundExpression argument = arguments.Arguments[i];
BoundExpression index = ConvertToArrayIndex(argument, node, diagnostics, allowIndexAndRange: rank == 1);
convertedArguments[i] = index;
// NOTE: Dev10 only warns if rank == 1
// Question: Why do we limit this warning to one-dimensional arrays?
// Answer: Because multidimensional arrays can have nonzero lower bounds in the CLR.
if (rank == 1 && !index.HasAnyErrors)
{
ConstantValue constant = index.ConstantValue;
if (constant != null && constant.IsNegativeNumeric)
{
Error(diagnostics, ErrorCode.WRN_NegativeArrayIndex, index.Syntax);
}
}
}
TypeSymbol resultType = rank == 1 &&
TypeSymbol.Equals(
convertedArguments[0].Type,
Compilation.GetWellKnownType(WellKnownType.System_Range),
TypeCompareKind.ConsiderEverything)
? arrayType
: arrayType.ElementType;
return new BoundArrayAccess(node, expr, convertedArguments.AsImmutableOrNull(), resultType, hasErrors);
}
private BoundExpression ConvertToArrayIndex(BoundExpression index, SyntaxNode node, DiagnosticBag diagnostics, bool allowIndexAndRange)
{
Debug.Assert(index != null);
if (index.Kind == BoundKind.OutVariablePendingInference)
{
return ((OutVariablePendingInference)index).FailInference(this, diagnostics);
}
else if (index.Kind == BoundKind.DiscardExpression && !index.HasExpressionType())
{
return ((BoundDiscardExpression)index).FailInference(this, diagnostics);
}
var result =
TryImplicitConversionToArrayIndex(index, SpecialType.System_Int32, node, diagnostics) ??
TryImplicitConversionToArrayIndex(index, SpecialType.System_UInt32, node, diagnostics) ??
TryImplicitConversionToArrayIndex(index, SpecialType.System_Int64, node, diagnostics) ??
TryImplicitConversionToArrayIndex(index, SpecialType.System_UInt64, node, diagnostics);
if (result is null && allowIndexAndRange)
{
result = TryImplicitConversionToArrayIndex(index, WellKnownType.System_Index, node, diagnostics);
if (result is null)
{
result = TryImplicitConversionToArrayIndex(index, WellKnownType.System_Range, node, diagnostics);
if (!(result is null))
{
// This member is needed for lowering and should produce an error if not present
_ = GetWellKnownTypeMember(
Compilation,
WellKnownMember.System_Runtime_CompilerServices_RuntimeHelpers__GetSubArray_T,
diagnostics,
syntax: node);
}
}
else
{
// This member is needed for lowering and should produce an error if not present
_ = GetWellKnownTypeMember(
Compilation,
WellKnownMember.System_Index__GetOffset,
diagnostics,
syntax: node);
}
}
if (result is null)
{
// Give the error that would be given upon conversion to int32.
NamedTypeSymbol int32 = GetSpecialType(SpecialType.System_Int32, diagnostics, node);
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
Conversion failedConversion = this.Conversions.ClassifyConversionFromExpression(index, int32, ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
GenerateImplicitConversionError(diagnostics, node, failedConversion, index, int32);
// Suppress any additional diagnostics
return CreateConversion(index.Syntax, index, failedConversion, isCast: false, conversionGroupOpt: null, destination: int32, diagnostics: new DiagnosticBag());
}
return result;
}
private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, WellKnownType wellKnownType, SyntaxNode node, DiagnosticBag diagnostics)
{
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
TypeSymbol type = GetWellKnownType(wellKnownType, ref useSiteDiagnostics);
if (type.IsErrorType())
{
return null;
}
var attemptDiagnostics = DiagnosticBag.GetInstance();
var result = TryImplicitConversionToArrayIndex(expr, type, node, attemptDiagnostics);
if (!(result is null))
{
diagnostics.AddRange(attemptDiagnostics);
}
attemptDiagnostics.Free();
return result;
}
private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, SpecialType specialType, SyntaxNode node, DiagnosticBag diagnostics)
{
DiagnosticBag attemptDiagnostics = DiagnosticBag.GetInstance();
TypeSymbol type = GetSpecialType(specialType, attemptDiagnostics, node);
var result = TryImplicitConversionToArrayIndex(expr, type, node, attemptDiagnostics);
if (!(result is null))
{
diagnostics.AddRange(attemptDiagnostics);
}
attemptDiagnostics.Free();
return result;
}
private BoundExpression TryImplicitConversionToArrayIndex(BoundExpression expr, TypeSymbol targetType, SyntaxNode node, DiagnosticBag diagnostics)
{
Debug.Assert(expr != null);
Debug.Assert((object)targetType != null);
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
Conversion conversion = this.Conversions.ClassifyImplicitConversionFromExpression(expr, targetType, ref useSiteDiagnostics);
diagnostics.Add(node, useSiteDiagnostics);
if (!conversion.Exists)
{
return null;
}
if (conversion.IsDynamic)
{
conversion = conversion.SetArrayIndexConversionForDynamic();
}
BoundExpression result = CreateConversion(expr.Syntax, expr, conversion, isCast: false, conversionGroupOpt: null, destination: targetType, diagnostics); // UNDONE: was cast?
Debug.Assert(result != null); // If this ever fails (it shouldn't), then put a null-check around the diagnostics update.
return result;
}
private BoundExpression BindPointerElementAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, DiagnosticBag diagnostics)
{
Debug.Assert(node != null);
Debug.Assert(expr != null);
Debug.Assert(analyzedArguments != null);
bool hasErrors = false;
if (analyzedArguments.Names.Count > 0)
{
// CONSIDER: the error text for this error code mentions "arrays". It might be nice if we had
// a separate error code for pointer element access.
Error(diagnostics, ErrorCode.ERR_NamedArgumentForArray, node);
hasErrors = true;
}
hasErrors = hasErrors || ReportRefOrOutArgument(analyzedArguments, diagnostics);
Debug.Assert(expr.Type.IsPointerType());
PointerTypeSymbol pointerType = (PointerTypeSymbol)expr.Type;
TypeSymbol pointedAtType = pointerType.PointedAtType;
ArrayBuilder<BoundExpression> arguments = analyzedArguments.Arguments;
if (arguments.Count != 1)
{
if (!hasErrors)
{
Error(diagnostics, ErrorCode.ERR_PtrIndexSingle, node);
}
return new BoundPointerElementAccess(node, expr, BadExpression(node, BuildArgumentsForErrorRecovery(analyzedArguments)).MakeCompilerGenerated(),
CheckOverflowAtRuntime, pointedAtType, hasErrors: true);
}
if (pointedAtType.IsVoidType())
{
Error(diagnostics, ErrorCode.ERR_VoidError, expr.Syntax);
hasErrors = true;
}
BoundExpression index = arguments[0];
index = ConvertToArrayIndex(index, index.Syntax, diagnostics, allowIndexAndRange: false);
return new BoundPointerElementAccess(node, expr, index, CheckOverflowAtRuntime, pointedAtType, hasErrors);
}
private static bool ReportRefOrOutArgument(AnalyzedArguments analyzedArguments, DiagnosticBag diagnostics)
{
int numArguments = analyzedArguments.Arguments.Count;
for (int i = 0; i < numArguments; i++)
{
RefKind refKind = analyzedArguments.RefKind(i);
if (refKind != RefKind.None)
{
Error(diagnostics, ErrorCode.ERR_BadArgExtraRef, analyzedArguments.Argument(i).Syntax, i + 1, refKind.ToArgumentDisplayString());
return true;
}
}
return false;
}
private BoundExpression BindIndexerAccess(ExpressionSyntax node, BoundExpression expr, AnalyzedArguments analyzedArguments, DiagnosticBag diagnostics)
{
Debug.Assert(node != null);
Debug.Assert(expr != null);
Debug.Assert((object)expr.Type != null);
Debug.Assert(analyzedArguments != null);
LookupResult lookupResult = LookupResult.GetInstance();
LookupOptions lookupOptions = expr.Kind == BoundKind.BaseReference ? LookupOptions.UseBaseReferenceAccessibility : LookupOptions.Default;
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
this.LookupMembersWithFallback(lookupResult, expr.Type, WellKnownMemberNames.Indexer, arity: 0, useSiteDiagnostics: ref useSiteDiagnostics, options: lookupOptions);
diagnostics.Add(node, useSiteDiagnostics);
// Store, rather than return, so that we can release resources.
BoundExpression indexerAccessExpression;
if (!lookupResult.IsMultiViable)
{
if (TryBindIndexOrRangeIndexer(
node,
expr,
analyzedArguments.Arguments,
diagnostics,
out var patternIndexerAccess))
{
indexerAccessExpression = patternIndexerAccess;
}
else
{
indexerAccessExpression = BadIndexerExpression(node, expr, analyzedArguments, lookupResult.Error, diagnostics);
}
}
else
{
ArrayBuilder<PropertySymbol> indexerGroup = ArrayBuilder<PropertySymbol>.GetInstance();
foreach (Symbol symbol in lookupResult.Symbols)
{
Debug.Assert(symbol.IsIndexer());
indexerGroup.Add((PropertySymbol)symbol);
}
indexerAccessExpression = BindIndexerOrIndexedPropertyAccess(node, expr, indexerGroup, analyzedArguments, diagnostics);
indexerGroup.Free();
}
lookupResult.Free();
return indexerAccessExpression;
}
private static readonly Func<PropertySymbol, bool> s_isIndexedPropertyWithNonOptionalArguments = property =>
{
if (property.IsIndexer || !property.IsIndexedProperty)
{
return false;
}
Debug.Assert(property.ParameterCount > 0);
var parameter = property.Parameters[0];
return !parameter.IsOptional && !parameter.IsParams;
};
private static readonly SymbolDisplayFormat s_propertyGroupFormat =
new SymbolDisplayFormat(
globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Omitted,
memberOptions:
SymbolDisplayMemberOptions.IncludeContainingType,
miscellaneousOptions:
SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers |
SymbolDisplayMiscellaneousOptions.UseSpecialTypes);
private BoundExpression BindIndexedPropertyAccess(BoundPropertyGroup propertyGroup, bool mustHaveAllOptionalParameters, DiagnosticBag diagnostics)
{
var syntax = propertyGroup.Syntax;
var receiverOpt = propertyGroup.ReceiverOpt;
var properties = propertyGroup.Properties;
if (properties.All(s_isIndexedPropertyWithNonOptionalArguments))
{
Error(diagnostics,
mustHaveAllOptionalParameters ? ErrorCode.ERR_IndexedPropertyMustHaveAllOptionalParams : ErrorCode.ERR_IndexedPropertyRequiresParams,
syntax,
properties[0].ToDisplayString(s_propertyGroupFormat));
return BoundIndexerAccess.ErrorAccess(
syntax,
receiverOpt,
CreateErrorPropertySymbol(properties),
ImmutableArray<BoundExpression>.Empty,
default(ImmutableArray<string>),
default(ImmutableArray<RefKind>),
properties);
}
var arguments = AnalyzedArguments.GetInstance();
var result = BindIndexedPropertyAccess(syntax, receiverOpt, properties, arguments, diagnostics);
arguments.Free();
return result;
}
private BoundExpression BindIndexedPropertyAccess(SyntaxNode syntax, BoundExpression receiverOpt, ImmutableArray<PropertySymbol> propertyGroup, AnalyzedArguments arguments, DiagnosticBag diagnostics)
{
// TODO: We're creating an extra copy of the properties array in BindIndexerOrIndexedProperty
// converting the ArrayBuilder to ImmutableArray. Avoid the extra copy.
var properties = ArrayBuilder<PropertySymbol>.GetInstance();
properties.AddRange(propertyGroup);
var result = BindIndexerOrIndexedPropertyAccess(syntax, receiverOpt, properties, arguments, diagnostics);
properties.Free();
return result;
}
private BoundExpression BindDynamicIndexer(
SyntaxNode syntax,
BoundExpression receiverOpt,
AnalyzedArguments arguments,
ImmutableArray<PropertySymbol> applicableProperties,
DiagnosticBag diagnostics)
{
bool hasErrors = false;
if (receiverOpt != null)
{
BoundKind receiverKind = receiverOpt.Kind;
if (receiverKind == BoundKind.BaseReference)
{
Error(diagnostics, ErrorCode.ERR_NoDynamicPhantomOnBaseIndexer, syntax);
hasErrors = true;
}
else if (receiverKind == BoundKind.TypeOrValueExpression)
{
var typeOrValue = (BoundTypeOrValueExpression)receiverOpt;
// Unfortunately, the runtime binder doesn't have APIs that would allow us to pass both "type or value".
// Ideally the runtime binder would choose between type and value based on the result of the overload resolution.
// We need to pick one or the other here. Dev11 compiler passes the type only if the value can't be accessed.
bool inStaticContext;
bool useType = IsInstance(typeOrValue.Data.ValueSymbol) && !HasThis(isExplicit: false, inStaticContext: out inStaticContext);
receiverOpt = ReplaceTypeOrValueReceiver(typeOrValue, useType, diagnostics);
}
}
var argArray = BuildArgumentsForDynamicInvocation(arguments, diagnostics);
var refKindsArray = arguments.RefKinds.ToImmutableOrNull();
hasErrors &= ReportBadDynamicArguments(syntax, argArray, refKindsArray, diagnostics, queryClause: null);
return new BoundDynamicIndexerAccess(
syntax,
receiverOpt,
argArray,
arguments.GetNames(),
refKindsArray,
applicableProperties,
AssemblySymbol.DynamicType,
hasErrors);
}
private BoundExpression BindIndexerOrIndexedPropertyAccess(
SyntaxNode syntax,
BoundExpression receiverOpt,
ArrayBuilder<PropertySymbol> propertyGroup,
AnalyzedArguments analyzedArguments,
DiagnosticBag diagnostics)
{
OverloadResolutionResult<PropertySymbol> overloadResolutionResult = OverloadResolutionResult<PropertySymbol>.GetInstance();
bool allowRefOmittedArguments = receiverOpt.IsExpressionOfComImportType();
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
this.OverloadResolution.PropertyOverloadResolution(propertyGroup, receiverOpt, analyzedArguments, overloadResolutionResult, allowRefOmittedArguments, ref useSiteDiagnostics);
diagnostics.Add(syntax, useSiteDiagnostics);
BoundExpression propertyAccess;
if (analyzedArguments.HasDynamicArgument && overloadResolutionResult.HasAnyApplicableMember)
{
// Note that the runtime binder may consider candidates that haven't passed compile-time final validation
// and an ambiguity error may be reported. Also additional checks are performed in runtime final validation
// that are not performed at compile-time.
// Only if the set of final applicable candidates is empty we know for sure the call will fail at runtime.
var finalApplicableCandidates = GetCandidatesPassingFinalValidation(syntax, overloadResolutionResult, receiverOpt, default(ImmutableArray<TypeWithAnnotations>), diagnostics);
overloadResolutionResult.Free();
return BindDynamicIndexer(syntax, receiverOpt, analyzedArguments, finalApplicableCandidates, diagnostics);
}
ImmutableArray<string> argumentNames = analyzedArguments.GetNames();
ImmutableArray<RefKind> argumentRefKinds = analyzedArguments.RefKinds.ToImmutableOrNull();
if (!overloadResolutionResult.Succeeded)
{
// If the arguments had an error reported about them then suppress further error
// reporting for overload resolution.
ImmutableArray<PropertySymbol> candidates = propertyGroup.ToImmutable();
if (!analyzedArguments.HasErrors)
{
if (TryBindIndexOrRangeIndexer(
syntax,
receiverOpt,
analyzedArguments.Arguments,
diagnostics,
out var patternIndexerAccess))
{
return patternIndexerAccess;
}
else
{
// Dev10 uses the "this" keyword as the method name for indexers.
var candidate = candidates[0];
var name = candidate.IsIndexer ? SyntaxFacts.GetText(SyntaxKind.ThisKeyword) : candidate.Name;
overloadResolutionResult.ReportDiagnostics(
binder: this,
location: syntax.Location,
nodeOpt: syntax,
diagnostics: diagnostics,
name: name,
receiver: null,
invokedExpression: null,
arguments: analyzedArguments,
memberGroup: candidates,
typeContainingConstructor: null,
delegateTypeBeingInvoked: null);
}
}
ImmutableArray<BoundExpression> arguments = BuildArgumentsForErrorRecovery(analyzedArguments, candidates);
// A bad BoundIndexerAccess containing an ErrorPropertySymbol will produce better flow analysis results than
// a BoundBadExpression containing the candidate indexers.
PropertySymbol property = (candidates.Length == 1) ? candidates[0] : CreateErrorPropertySymbol(candidates);
propertyAccess = BoundIndexerAccess.ErrorAccess(
syntax,
receiverOpt,
property,
arguments,
argumentNames,
argumentRefKinds,
candidates);
}
else
{
MemberResolutionResult<PropertySymbol> resolutionResult = overloadResolutionResult.ValidResult;
PropertySymbol property = resolutionResult.Member;
this.CoerceArguments<PropertySymbol>(resolutionResult, analyzedArguments.Arguments, diagnostics);
var isExpanded = resolutionResult.Result.Kind == MemberResolutionKind.ApplicableInExpandedForm;
var argsToParams = resolutionResult.Result.ArgsToParamsOpt;
ReportDiagnosticsIfObsolete(diagnostics, property, syntax, hasBaseReceiver: receiverOpt != null && receiverOpt.Kind == BoundKind.BaseReference);
// Make sure that the result of overload resolution is valid.
var gotError = MemberGroupFinalValidationAccessibilityChecks(receiverOpt, property, syntax, diagnostics, invokedAsExtensionMethod: false);
var receiver = ReplaceTypeOrValueReceiver(receiverOpt, property.IsStatic, diagnostics);
if (!gotError && receiver != null && receiver.Kind == BoundKind.ThisReference && receiver.WasCompilerGenerated)
{
gotError = IsRefOrOutThisParameterCaptured(syntax, diagnostics);
}
var arguments = analyzedArguments.Arguments.ToImmutable();
if (!gotError)
{
gotError = !CheckInvocationArgMixing(
syntax,
property,
receiver,
property.Parameters,
arguments,
argsToParams,
this.LocalScopeDepth,
diagnostics);
}
propertyAccess = new BoundIndexerAccess(
syntax,
receiver,
property,
arguments,
argumentNames,
argumentRefKinds,
isExpanded,
argsToParams,
this,
false,
property.Type,
gotError);
}
overloadResolutionResult.Free();
return propertyAccess;
}
private bool TryBindIndexOrRangeIndexer(
SyntaxNode syntax,
BoundExpression receiverOpt,
ArrayBuilder<BoundExpression> arguments,
DiagnosticBag diagnostics,
out BoundIndexOrRangePatternIndexerAccess patternIndexerAccess)
{
patternIndexerAccess = null;
// Verify a few things up-front, namely that we have a single argument
// to this indexer that has an Index or Range type and that there is
// a real receiver with a known type
if (arguments.Count != 1)
{
return false;
}
var argType = arguments[0].Type;
bool argIsIndex = TypeSymbol.Equals(argType,
Compilation.GetWellKnownType(WellKnownType.System_Index),
TypeCompareKind.ConsiderEverything);
bool argIsRange = !argIsIndex && TypeSymbol.Equals(argType,
Compilation.GetWellKnownType(WellKnownType.System_Range),
TypeCompareKind.ConsiderEverything);
if ((!argIsIndex && !argIsRange) ||
!(receiverOpt?.Type is TypeSymbol receiverType))
{
return false;
}
// SPEC:
// An indexer invocation with a single argument of System.Index or System.Range will
// succeed if the receiver type conforms to an appropriate pattern, namely
// 1. The receiver type's original definition has an accessible property getter that returns
// an int and has the name Length or Count
// 2. For Index: Has an accessible indexer with a single int parameter
// For Range: Has an accessible Slice method that takes two int parameters
PropertySymbol lengthOrCountProperty;
var lookupResult = LookupResult.GetInstance();
HashSet<DiagnosticInfo> useSiteDiagnostics = null;
// Look for Length first
if (!tryLookupLengthOrCount(WellKnownMemberNames.LengthPropertyName, out lengthOrCountProperty) &&
!tryLookupLengthOrCount(WellKnownMemberNames.CountPropertyName, out lengthOrCountProperty))
{
return false;
}
Debug.Assert(lengthOrCountProperty is { });
if (argIsIndex)
{
// Look for `T this[int i]` indexer
LookupMembersInType(
lookupResult,
receiverType,
WellKnownMemberNames.Indexer,
arity: 0,
basesBeingResolved: null,
LookupOptions.Default,
originalBinder: this,
diagnose: false,
ref useSiteDiagnostics);
if (lookupResult.IsMultiViable)
{
foreach (var candidate in lookupResult.Symbols)
{
if (!candidate.IsStatic &&
candidate is PropertySymbol property &&
IsAccessible(property, ref useSiteDiagnostics) &&
property.OriginalDefinition is { ParameterCount: 1 } original &&
isIntNotByRef(original.Parameters[0]))
{
patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess(
syntax,
receiverOpt,
lengthOrCountProperty,
property,
arguments[0],
property.Type);
break;
}
}
}
}
else if (receiverType.SpecialType == SpecialType.System_String)
{
Debug.Assert(argIsRange);
// Look for Substring
var substring = (MethodSymbol)Compilation.GetSpecialTypeMember(SpecialMember.System_String__Substring);
if (substring is object)
{
patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess(
syntax,
receiverOpt,
lengthOrCountProperty,
substring,
arguments[0],
substring.ReturnType);
}
}
else
{
Debug.Assert(argIsRange);
// Look for `T Slice(int, int)` indexer
LookupMembersInType(
lookupResult,
receiverType,
WellKnownMemberNames.SliceMethodName,
arity: 0,
basesBeingResolved: null,
LookupOptions.Default,
originalBinder: this,
diagnose: false,
ref useSiteDiagnostics);
if (lookupResult.IsMultiViable)
{
foreach (var candidate in lookupResult.Symbols)
{
if (!candidate.IsStatic &&
IsAccessible(candidate, ref useSiteDiagnostics) &&
candidate is MethodSymbol method &&
method.OriginalDefinition is var original &&
original.ParameterCount == 2 &&
isIntNotByRef(original.Parameters[0]) &&
isIntNotByRef(original.Parameters[1]))
{
patternIndexerAccess = new BoundIndexOrRangePatternIndexerAccess(
syntax,
receiverOpt,
lengthOrCountProperty,
method,
arguments[0],
method.ReturnType);
break;
}
}
}
}
cleanup(lookupResult, ref useSiteDiagnostics);
if (patternIndexerAccess is null)
{
return false;
}
_ = MessageID.IDS_FeatureIndexOperator.CheckFeatureAvailability(diagnostics, syntax.Location);
// Check for some required well-known members. They may not be needed
// during lowering, but it's simpler to always require them to prevent
// the user from getting surprising errors when optimizations fail
_ = GetWellKnownTypeMember(Compilation, WellKnownMember.System_Index__GetOffset, diagnostics, syntax: syntax);
return true;
static void cleanup(LookupResult lookupResult, ref HashSet<DiagnosticInfo> useSiteDiagnostics)
{
lookupResult.Free();
useSiteDiagnostics = null;
}
static bool isIntNotByRef(ParameterSymbol param)
=> param.Type.SpecialType == SpecialType.System_Int32 &&
param.RefKind == RefKind.None;
bool tryLookupLengthOrCount(string propertyName, out PropertySymbol valid)
{
LookupMembersInType(
lookupResult,
receiverType,
propertyName,
arity: 0,
basesBeingResolved: null,
LookupOptions.Default,
originalBinder: this,
diagnose: false,
useSiteDiagnostics: ref useSiteDiagnostics);
if (lookupResult.IsSingleViable &&
lookupResult.Symbols[0] is PropertySymbol property &&
property.GetOwnOrInheritedGetMethod()?.OriginalDefinition is MethodSymbol getMethod &&
getMethod.ReturnType.SpecialType == SpecialType.System_Int32 &&
getMethod.RefKind == RefKind.None &&
!getMethod.IsStatic &&
IsAccessible(getMethod, ref useSiteDiagnostics))
{
lookupResult.Clear();
useSiteDiagnostics = null;
valid = property;
return true;
}
lookupResult.Clear();
useSiteDiagnostics = null;
valid = null;
return false;
}
}
private ErrorPropertySymbol CreateErrorPropertySymbol(ImmutableArray<PropertySymbol> propertyGroup)
{
TypeSymbol propertyType = GetCommonTypeOrReturnType(propertyGroup) ?? CreateErrorType();
var candidate = propertyGroup[0];
return new ErrorPropertySymbol(candidate.ContainingType, propertyType, candidate.Name, candidate.IsIndexer, candidate.IsIndexedProperty);
}
/// <summary>
/// Perform lookup and overload resolution on methods defined directly on the class and any
/// extension methods in scope. Lookup will occur for extension methods in all nested scopes
/// as necessary until an appropriate method is found. If analyzedArguments is null, the first
/// method group is returned, without overload resolution being performed. That method group
/// will either be the methods defined on the receiver class directly (no extension methods)
/// or the first set of extension methods.
/// </summary>
/// <param name="node">The node associated with the method group</param>
/// <param name="analyzedArguments">The arguments of the invocation (or the delegate type, if a method group conversion)</param>
/// <param name="isMethodGroupConversion">True if it is a method group conversion</param>
/// <param name="useSiteDiagnostics"></param>
/// <param name="inferWithDynamic"></param>
/// <param name="returnRefKind">If a method group conversion, the desired ref kind of the delegate</param>
/// <param name="returnType">If a method group conversion, the desired return type of the delegate.
/// May be null during inference if the return type of the delegate needs to be computed.</param>
internal MethodGroupResolution ResolveMethodGroup(
BoundMethodGroup node,
AnalyzedArguments analyzedArguments,
bool isMethodGroupConversion,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
bool inferWithDynamic = false,
RefKind returnRefKind = default,
TypeSymbol returnType = null)
{
return ResolveMethodGroup(
node, node.Syntax, node.Name, analyzedArguments, isMethodGroupConversion, ref useSiteDiagnostics,
inferWithDynamic: inferWithDynamic, returnRefKind: returnRefKind, returnType: returnType);
}
internal MethodGroupResolution ResolveMethodGroup(
BoundMethodGroup node,
SyntaxNode expression,
string methodName,
AnalyzedArguments analyzedArguments,
bool isMethodGroupConversion,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
bool inferWithDynamic = false,
bool allowUnexpandedForm = true,
RefKind returnRefKind = default,
TypeSymbol returnType = null)
{
var methodResolution = ResolveMethodGroupInternal(
node, expression, methodName, analyzedArguments, isMethodGroupConversion, ref useSiteDiagnostics,
inferWithDynamic: inferWithDynamic, allowUnexpandedForm: allowUnexpandedForm,
returnRefKind: returnRefKind, returnType: returnType);
if (methodResolution.IsEmpty && !methodResolution.HasAnyErrors)
{
Debug.Assert(node.LookupError == null);
var diagnostics = DiagnosticBag.GetInstance();
diagnostics.AddRange(methodResolution.Diagnostics); // Could still have use site warnings.
BindMemberAccessReportError(node, diagnostics);
// Note: no need to free `methodResolution`, we're transferring the pooled objects it owned
return new MethodGroupResolution(methodResolution.MethodGroup, methodResolution.OtherSymbol, methodResolution.OverloadResolutionResult, methodResolution.AnalyzedArguments, methodResolution.ResultKind, diagnostics.ToReadOnlyAndFree());
}
return methodResolution;
}
private MethodGroupResolution ResolveMethodGroupInternal(
BoundMethodGroup methodGroup,
SyntaxNode expression,
string methodName,
AnalyzedArguments analyzedArguments,
bool isMethodGroupConversion,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
bool inferWithDynamic = false,
bool allowUnexpandedForm = true,
RefKind returnRefKind = default,
TypeSymbol returnType = null)
{
var methodResolution = ResolveDefaultMethodGroup(
methodGroup, analyzedArguments, isMethodGroupConversion, ref useSiteDiagnostics,
inferWithDynamic: inferWithDynamic, allowUnexpandedForm: allowUnexpandedForm,
returnRefKind: returnRefKind, returnType: returnType);
// If the method group's receiver is dynamic then there is no point in looking for extension methods;
// it's going to be a dynamic invocation.
if (!methodGroup.SearchExtensionMethods || methodResolution.HasAnyApplicableMethod || methodGroup.MethodGroupReceiverIsDynamic())
{
return methodResolution;
}
var extensionMethodResolution = BindExtensionMethod(
expression, methodName, analyzedArguments, methodGroup.ReceiverOpt, methodGroup.TypeArgumentsOpt, isMethodGroupConversion,
returnRefKind: returnRefKind, returnType: returnType);
bool preferExtensionMethodResolution = false;
if (extensionMethodResolution.HasAnyApplicableMethod)
{
preferExtensionMethodResolution = true;
}
else if (extensionMethodResolution.IsEmpty)
{
preferExtensionMethodResolution = false;
}
else if (methodResolution.IsEmpty)
{
preferExtensionMethodResolution = true;
}
else
{
// At this point, both method group resolutions are non-empty but neither contains any applicable method.
// Choose the MethodGroupResolution with the better (i.e. less worse) result kind.
Debug.Assert(!methodResolution.HasAnyApplicableMethod);
Debug.Assert(!extensionMethodResolution.HasAnyApplicableMethod);
Debug.Assert(!methodResolution.IsEmpty);
Debug.Assert(!extensionMethodResolution.IsEmpty);
LookupResultKind methodResultKind = methodResolution.ResultKind;
LookupResultKind extensionMethodResultKind = extensionMethodResolution.ResultKind;
if (methodResultKind != extensionMethodResultKind &&
methodResultKind == extensionMethodResultKind.WorseResultKind(methodResultKind))
{
preferExtensionMethodResolution = true;
}
}
if (preferExtensionMethodResolution)
{
methodResolution.Free();
Debug.Assert(!extensionMethodResolution.IsEmpty);
return extensionMethodResolution; //NOTE: the first argument of this MethodGroupResolution could be a BoundTypeOrValueExpression
}
extensionMethodResolution.Free();
return methodResolution;
}
private MethodGroupResolution ResolveDefaultMethodGroup(
BoundMethodGroup node,
AnalyzedArguments analyzedArguments,
bool isMethodGroupConversion,
ref HashSet<DiagnosticInfo> useSiteDiagnostics,
bool inferWithDynamic = false,
bool allowUnexpandedForm = true,
RefKind returnRefKind = default,
TypeSymbol returnType = null)
{
var methods = node.Methods;
if (methods.Length == 0)
{
var method = node.LookupSymbolOpt as MethodSymbol;
if ((object)method != null)
{
methods = ImmutableArray.Create(method);
}
}
ImmutableArray<Diagnostic> sealedDiagnostics = ImmutableArray<Diagnostic>.Empty;
if (node.LookupError != null)
{
DiagnosticBag diagnostics = DiagnosticBag.GetInstance();
Error(diagnostics, node.LookupError, node.NameSyntax);
sealedDiagnostics = diagnostics.ToReadOnlyAndFree();
}
if (methods.Length == 0)
{
return new MethodGroupResolution(node.LookupSymbolOpt, node.ResultKind, sealedDiagnostics);
}
var methodGroup = MethodGroup.GetInstance();
// NOTE: node.ReceiverOpt could be a BoundTypeOrValueExpression - users need to check.
methodGroup.PopulateWithNonExtensionMethods(node.ReceiverOpt, methods, node.TypeArgumentsOpt, node.ResultKind, node.LookupError);
if (node.LookupError != null)
{
return new MethodGroupResolution(methodGroup, sealedDiagnostics);
}
// Arguments will be null if the caller is resolving to the first available
// method group, regardless of arguments, when the signature cannot
// be inferred. (In the error case of o.M = null; for instance.)
if (analyzedArguments == null)
{
return new MethodGroupResolution(methodGroup, sealedDiagnostics);
}
else
{
var result = OverloadResolutionResult<MethodSymbol>.GetInstance();
bool allowRefOmittedArguments = methodGroup.Receiver.IsExpressionOfComImportType();
OverloadResolution.MethodInvocationOverloadResolution(
methods: methodGroup.Methods,
typeArguments: methodGroup.TypeArguments,
receiver: methodGroup.Receiver,
arguments: analyzedArguments,
result: result,
useSiteDiagnostics: ref useSiteDiagnostics,
isMethodGroupConversion: isMethodGroupConversion,
allowRefOmittedArguments: allowRefOmittedArguments,
inferWithDynamic: inferWithDynamic,
allowUnexpandedForm: allowUnexpandedForm,
returnRefKind: returnRefKind,
returnType: returnType);
// Note: the MethodGroupResolution instance is responsible for freeing its copy of analyzed arguments
return new MethodGroupResolution(methodGroup, null, result, AnalyzedArguments.GetInstance(analyzedArguments), methodGroup.ResultKind, sealedDiagnostics);
}
}
internal static bool ReportDelegateInvokeUseSiteDiagnostic(DiagnosticBag diagnostics, TypeSymbol possibleDelegateType,
Location location = null, SyntaxNode node = null)
{
Debug.Assert((location == null) ^ (node == null));
if (!possibleDelegateType.IsDelegateType())
{
return false;
}
MethodSymbol invoke = possibleDelegateType.DelegateInvokeMethod();
if ((object)invoke == null)
{
diagnostics.Add(new CSDiagnosticInfo(ErrorCode.ERR_InvalidDelegateType, possibleDelegateType), location ?? node.Location);
return true;
}
DiagnosticInfo info = invoke.GetUseSiteDiagnostic();
if (info == null)
{
return false;
}
if (location == null)
{
location = node.Location;
}
if (info.Code == (int)ErrorCode.ERR_InvalidDelegateType)
{
diagnostics.Add(new CSDiagnostic(new CSDiagnosticInfo(ErrorCode.ERR_InvalidDelegateType, possibleDelegateType), location));
return true;
}
return Symbol.ReportUseSiteDiagnostic(info, diagnostics, location);
}
private BoundConditionalAccess BindConditionalAccessExpression(ConditionalAccessExpressionSyntax node, DiagnosticBag diagnostics)
{
BoundExpression receiver = BindConditionalAccessReceiver(node, diagnostics);
var conditionalAccessBinder = new BinderWithConditionalReceiver(this, receiver);
var access = conditionalAccessBinder.BindValue(node.WhenNotNull, diagnostics, BindValueKind.RValue);
if (receiver.HasAnyErrors || access.HasAnyErrors)
{
return new BoundConditionalAccess(node, receiver, access, CreateErrorType(), hasErrors: true);
}
var receiverType = receiver.Type;
Debug.Assert((object)receiverType != null);
// access cannot be a method group
if (access.Kind == BoundKind.MethodGroup)
{
return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics);
}
var accessType = access.Type;
// access cannot have no type
if ((object)accessType == null)
{
return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics);
}
// The resulting type must be either a reference type T or Nullable<T>
// Therefore we must reject cases resulting in types that are not reference types and cannot be lifted into nullable.
// - access cannot have unconstrained generic type
// - access cannot be a pointer
// - access cannot be a restricted type
if ((!accessType.IsReferenceType && !accessType.IsValueType) || accessType.IsPointerType() || accessType.IsRestrictedType())
{
// Result type of the access is void when result value cannot be made nullable.
// For improved diagnostics we detect the cases where the value will be used and produce a
// more specific (though not technically correct) diagnostic here:
// "Error CS0023: Operator '?' cannot be applied to operand of type 'T'"
bool resultIsUsed = true;
CSharpSyntaxNode parent = node.Parent;
if (parent != null)
{
switch (parent.Kind())
{
case SyntaxKind.ExpressionStatement:
resultIsUsed = ((ExpressionStatementSyntax)parent).Expression != node;
break;
case SyntaxKind.SimpleLambdaExpression:
resultIsUsed = (((SimpleLambdaExpressionSyntax)parent).Body != node) || ContainingMethodOrLambdaRequiresValue();
break;
case SyntaxKind.ParenthesizedLambdaExpression:
resultIsUsed = (((ParenthesizedLambdaExpressionSyntax)parent).Body != node) || ContainingMethodOrLambdaRequiresValue();
break;
case SyntaxKind.ArrowExpressionClause:
resultIsUsed = (((ArrowExpressionClauseSyntax)parent).Expression != node) || ContainingMethodOrLambdaRequiresValue();
break;
case SyntaxKind.ForStatement:
// Incrementors and Initializers doesn't have to produce a value
var loop = (ForStatementSyntax)parent;
resultIsUsed = !loop.Incrementors.Contains(node) && !loop.Initializers.Contains(node);
break;
}
}
if (resultIsUsed)
{
return GenerateBadConditionalAccessNodeError(node, receiver, access, diagnostics);
}
accessType = GetSpecialType(SpecialType.System_Void, diagnostics, node);
}
// if access has value type, the type of the conditional access is nullable of that
// https://github.com/dotnet/roslyn/issues/35075: The test `accessType.IsValueType && !accessType.IsNullableType()`
// should probably be `accessType.IsNonNullableValueType()`
if (accessType.IsValueType && !accessType.IsNullableType() && !accessType.IsVoidType())
{
accessType = GetSpecialType(SpecialType.System_Nullable_T, diagnostics, node).Construct(accessType);
}
return new BoundConditionalAccess(node, receiver, access, accessType);
}
private bool ContainingMethodOrLambdaRequiresValue()
{
var containingMethod = ContainingMemberOrLambda as MethodSymbol;
return
(object)containingMethod == null ||
!containingMethod.ReturnsVoid &&
!containingMethod.IsTaskReturningAsync(this.Compilation);
}
private BoundConditionalAccess GenerateBadConditionalAccessNodeError(ConditionalAccessExpressionSyntax node, BoundExpression receiver, BoundExpression access, DiagnosticBag diagnostics)
{
var operatorToken = node.OperatorToken;
// TODO: need a special ERR for this.
// conditional access is not really a binary operator.
DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadUnaryOp, SyntaxFacts.GetText(operatorToken.Kind()), access.Display);
diagnostics.Add(new CSDiagnostic(diagnosticInfo, operatorToken.GetLocation()));
access = BadExpression(access.Syntax, access);
return new BoundConditionalAccess(node, receiver, access, CreateErrorType(), hasErrors: true);
}
private BoundExpression BindMemberBindingExpression(MemberBindingExpressionSyntax node, bool invoked, bool indexed, DiagnosticBag diagnostics)
{
BoundExpression receiver = GetReceiverForConditionalBinding(node, diagnostics);
var memberAccess = BindMemberAccessWithBoundLeft(node, receiver, node.Name, node.OperatorToken, invoked, indexed, diagnostics);
return memberAccess;
}
private BoundExpression BindElementBindingExpression(ElementBindingExpressionSyntax node, DiagnosticBag diagnostics)
{
BoundExpression receiver = GetReceiverForConditionalBinding(node, diagnostics);
var memberAccess = BindElementAccess(node, receiver, node.ArgumentList, diagnostics);
return memberAccess;
}
private static CSharpSyntaxNode GetConditionalReceiverSyntax(ConditionalAccessExpressionSyntax node)
{
Debug.Assert(node != null);
Debug.Assert(node.Expression != null);
var receiver = node.Expression;
while (receiver.IsKind(SyntaxKind.ParenthesizedExpression))
{
receiver = ((ParenthesizedExpressionSyntax)receiver).Expression;
Debug.Assert(receiver != null);
}
return receiver;
}
private BoundExpression GetReceiverForConditionalBinding(ExpressionSyntax binding, DiagnosticBag diagnostics)
{
var conditionalAccessNode = SyntaxFactory.FindConditionalAccessNodeForBinding(binding);
Debug.Assert(conditionalAccessNode != null);
BoundExpression receiver = this.ConditionalReceiverExpression;
if (receiver?.Syntax != GetConditionalReceiverSyntax(conditionalAccessNode))
{
// this can happen when semantic model binds parts of a Call or a broken access expression.
// We may not have receiver available in such cases.
// Not a problem - we only need receiver to get its type and we can bind it here.
receiver = BindConditionalAccessReceiver(conditionalAccessNode, diagnostics);
}
// create surrogate receiver
var receiverType = receiver.Type;
if (receiverType?.IsNullableType() == true)
{
receiverType = receiverType.GetNullableUnderlyingType();
}
receiver = new BoundConditionalReceiver(receiver.Syntax, 0, receiverType ?? CreateErrorType(), hasErrors: receiver.HasErrors) { WasCompilerGenerated = true };
return receiver;
}
private BoundExpression BindConditionalAccessReceiver(ConditionalAccessExpressionSyntax node, DiagnosticBag diagnostics)
{
var receiverSyntax = node.Expression;
var receiver = BindValue(receiverSyntax, diagnostics, BindValueKind.RValue);
receiver = MakeMemberAccessValue(receiver, diagnostics);
if (receiver.HasAnyErrors)
{
return receiver;
}
var operatorToken = node.OperatorToken;
if (receiver.Kind == BoundKind.UnboundLambda)
{
var msgId = ((UnboundLambda)receiver).MessageID;
DiagnosticInfo diagnosticInfo = new CSDiagnosticInfo(ErrorCode.ERR_BadUnaryOp, SyntaxFacts.GetText(operatorToken.Kind()), msgId.Localize());
diagnostics.Add(new CSDiagnostic(diagnosticInfo, node.Location));
return BadExpression(receiverSyntax, receiver);
}
var receiverType = receiver.Type;
// Can't dot into the null literal or anything that has no type
if ((object)receiverType == null)
{
Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiver.Display);
return BadExpression(receiverSyntax, receiver);
}
// No member accesses on void
if (receiverType.IsVoidType())
{
Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiverType);
return BadExpression(receiverSyntax, receiver);
}
if (receiverType.IsValueType && !receiverType.IsNullableType())
{
// must be nullable or reference type
Error(diagnostics, ErrorCode.ERR_BadUnaryOp, operatorToken.GetLocation(), operatorToken.Text, receiverType);
return BadExpression(receiverSyntax, receiver);
}
return receiver;
}
}
}
| 49.46743 | 262 | 0.589301 | [
"Apache-2.0"
] | avodovnik/roslyn | src/Compilers/CSharp/Portable/Binder/Binder_Expressions.cs | 401,727 | C# |
using UnityEngine;
#if UNITY_EDITOR // this preprocessor directive is required to avoid some errors and warnings in the console
using UnityEditor;
/// <summary>
/// Popup Window for Isaac Tools Editor Extension
/// Notice that it inherits from EditorWindow. We do this so we can access a bunch of Unity Editor functionality
/// This allows us to customize the Unity editor to create custom tools that we want.
/// </summary>
public class UnitPopupWindow: EditorWindow
{
string unitName;
string unitType;
Object unitSprite;
string[] unitTypes = { "infantry", "tank", "helicopter" };
int index = 0;
public static void Init()
{
// this function will be called by the isaac menu tool. It will initialize and show this popup window.
UnitPopupWindow window = ScriptableObject.CreateInstance<UnitPopupWindow>(); // create a new instance of this class
window.position = new Rect(Screen.width / 2, Screen.height / 2, 256, 256); // set the position of the window when it opens
window.ShowPopup(); // called EditorWindow.ShowPopup() to open the window in the editor.
}
void OnGUI()
{
// OnGUI is called even when the game is not playing. This allows us to create functionality that updates in editor mode
this.Repaint(); // refresh the popup window
// Create a text field for the name of the prefab we want to make. Assign tileName to the string that's in the name text field.
unitName = EditorGUILayout.TextField("Tile Name", unitName);
GUILayout.Space(10); // create some space on the window. Allows us to space out our ui elements
index = EditorGUILayout.Popup("Unit Type", index, unitTypes);
unitType = unitTypes[index];
GUILayout.Space(10);
// create a sprite field. Allows user to select a sprite to use for the tile. Assign tileSprite to this object
unitSprite = EditorGUILayout.ObjectField("Sprite", unitSprite, typeof(Sprite), true);
GUILayout.Space(10);
if (GUILayout.Button("Accept"))
{
// Create Accept button. When user presses this button, we want to call our ScriptableObjectUtility to create a prefab.
ScriptableObjectUtility.CreateUnit(unitName, unitType, unitSprite);
this.Close(); // close window
}
else if (GUILayout.Button("Cancel"))
this.Close();
}
}
#endif | 38.016949 | 129 | 0.738743 | [
"MIT"
] | Photoperiod/TurnBasedStrategy | Assets/Scripts/EditorScripts/UnitPopupWindow.cs | 2,245 | C# |
namespace CefGlue
{
using System;
using CefGlue.Interop;
unsafe partial class CefV8Value
{
/// <summary>
/// Create a new CefV8Value object of type undefined.
/// </summary>
public static CefV8Value CreateUndefined()
{
return CefV8Value.From(
NativeMethods.cef_v8value_create_undefined()
);
}
/// <summary>
/// Create a new CefV8Value object of type null.
/// </summary>
public static CefV8Value CreateNull()
{
return CefV8Value.From(
NativeMethods.cef_v8value_create_null()
);
}
/// <summary>
/// Create a new CefV8Value object of type bool.
/// </summary>
public static CefV8Value CreateBool(bool value)
{
return CefV8Value.From(
NativeMethods.cef_v8value_create_bool(value ? 1 : 0)
);
}
/// <summary>
/// Create a new CefV8Value object of type int.
/// </summary>
public static CefV8Value CreateInt(int value)
{
return CefV8Value.From(
NativeMethods.cef_v8value_create_int(value)
);
}
/// <summary>
/// Create a new CefV8Value object of type unsigned int.
/// </summary>
public static CefV8Value CreateUInt(uint value)
{
return CefV8Value.From(
NativeMethods.cef_v8value_create_uint(value)
);
}
/// <summary>
/// Create a new CefV8Value object of type double.
/// </summary>
public static CefV8Value CreateDouble(double value)
{
return CefV8Value.From(
NativeMethods.cef_v8value_create_double(value)
);
}
/// <summary>
/// Create a new CefV8Value object of type Date.
/// </summary>
public static CefV8Value CreateDate(DateTime value)
{
cef_time_t n_date = new cef_time_t(value);
return CefV8Value.From(
NativeMethods.cef_v8value_create_date(&n_date)
);
}
/// <summary>
/// Create a new CefV8Value object of type string.
/// </summary>
public static CefV8Value CreateString(string value)
{
fixed (char* value_str = value)
{
var n_value = new cef_string_t(value_str, value != null ? value.Length : 0);
return CefV8Value.From(
NativeMethods.cef_v8value_create_string(&n_value)
);
}
}
/// <summary>
/// Create a new CefV8Value object of type object.
/// </summary>
public static CefV8Value CreateObject()
{
return CreateObject(null);
}
/// <summary>
/// Create a new CefV8Value object of type object with accessors.
/// </summary>
public static CefV8Value CreateObject(CefV8Accessor accessor)
{
return CefV8Value.From(NativeMethods.cef_v8value_create_object(
accessor != null ? accessor.GetNativePointerAndAddRef() : null
));
}
/// <summary>
/// Create a new CefV8Value object of type array.
/// </summary>
public static CefV8Value CreateArray(int length)
{
return CefV8Value.From(
NativeMethods.cef_v8value_create_array(length)
);
}
/// <summary>
/// Create a new CefV8Value object of type function.
/// </summary>
public static CefV8Value CreateFunction(string name, CefV8Handler handler)
{
fixed (char* name_str = name)
{
var n_name = new cef_string_t(name_str, name != null ? name.Length : 0);
return CefV8Value.From(
NativeMethods.cef_v8value_create_function(&n_name, handler.GetNativePointerAndAddRef())
);
}
}
/// <summary>
/// Returns true if this object is valid. Do not call any other methods if this
/// method returns false.
/// </summary>
public bool IsValid
{
get
{
return cef_v8value_t.invoke_is_valid(this.ptr) != 0;
}
}
private void ThrowIfObjectIsInvalid()
{
if (!this.IsValid)
throw new InvalidOperationException();
}
/// <summary>
/// True if the value type is undefined.
/// </summary>
public bool IsUndefined
{
get
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_is_undefined(this.ptr) != 0;
}
}
/// <summary>
/// True if the value type is null.
/// </summary>
public bool IsNull
{
get
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_is_null(this.ptr) != 0;
}
}
/// <summary>
/// True if the value type is bool.
/// </summary>
public bool IsBool
{
get
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_is_bool(this.ptr) != 0;
}
}
/// <summary>
/// True if the value type is int.
/// </summary>
public bool IsInt
{
get
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_is_int(this.ptr) != 0;
}
}
/// <summary>
/// True if the value type is unsigned int.
/// </summary>
public bool IsUInt
{
get
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_is_uint(this.ptr) != 0;
}
}
/// <summary>
/// True if the value type is double.
/// </summary>
public bool IsDouble
{
get
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_is_double(this.ptr) != 0;
}
}
/// <summary>
/// True if the value type is Date.
/// </summary>
public bool IsDate
{
get
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_is_date(this.ptr) != 0;
}
}
/// <summary>
/// True if the value type is string.
/// </summary>
public bool IsString
{
get
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_is_string(this.ptr) != 0;
}
}
/// <summary>
/// True if the value type is object.
/// </summary>
public bool IsObject
{
get
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_is_object(this.ptr) != 0;
}
}
/// <summary>
/// True if the value type is array.
/// </summary>
public bool IsArray
{
get
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_is_array(this.ptr) != 0;
}
}
/// <summary>
/// True if the value type is function.
/// </summary>
public bool IsFunction
{
get
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_is_function(this.ptr) != 0;
}
}
/// <summary>
/// Returns true if this is a user created object.
/// </summary>
public bool IsUserCreated
{
get
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_is_user_created(this.ptr) != 0;
}
}
/// <summary>
/// Returns true if the last method call resulted in an exception. This
/// attribute exists only in the scope of the current CEF value object.
/// </summary>
public bool HasException
{
get
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_has_exception(this.ptr) != 0;
}
}
/// <summary>
/// Returns true if this object will re-throw future exceptions. This attribute
/// exists only in the scope of the current CEF value object.
/// </summary>
public bool WillRethrowExceptions
{
get
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_will_rethrow_exceptions(this.ptr) != 0;
}
}
/// <summary>
/// Returns true if this object is pointing to the same handle as |that| object.
/// </summary>
public bool IsSame(CefV8Value that)
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_is_same(this.ptr, that.GetNativePointerAndAddRef()) != 0;
}
/// <summary>
/// Return a bool value.
/// The underlying data will be converted to if necessary.
/// </summary>
public bool GetBoolValue()
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_get_bool_value(this.ptr) != 0;
}
/// <summary>
/// Return an int value.
/// The underlying data will be converted to if necessary.
/// </summary>
public int GetIntValue()
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_get_int_value(this.ptr);
}
/// <summary>
/// Return an unsigned int value.
/// The underlying data will be converted to if necessary.
/// </summary>
public uint GetUIntValue()
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_get_uint_value(this.ptr);
}
/// <summary>
/// Return a double value.
/// The underlying data will be converted to if necessary.
/// </summary>
public double GetDoubleValue()
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_get_double_value(this.ptr);
}
/// <summary>
/// Return a Date value.
/// The underlying data will be converted to if necessary.
/// </summary>
public DateTime GetDateValue()
{
ThrowIfObjectIsInvalid();
var n_result = cef_v8value_t.invoke_get_date_value(this.ptr);
return n_result.ToDateTime();
}
/// <summary>
/// Return a string value.
/// The underlying data will be converted to if necessary.
/// </summary>
public string GetStringValue()
{
ThrowIfObjectIsInvalid();
var nResult = cef_v8value_t.invoke_get_string_value(this.ptr);
return cef_string_userfree.GetStringAndFree(nResult);
}
// OBJECT METHODS - These methods are only available on objects. Arrays
// and functions are also objects. String- and integer-based keys can be
// used interchangably with the framework converting between them as
// necessary. Keys beginning with "Cef::" and "v8::" are reserved by the
// system.
/// <summary>
/// Returns true if the object has a value with the specified identifier.
/// </summary>
public bool HasValue(string key)
{
ThrowIfObjectIsInvalid();
fixed (char* key_str = key)
{
var n_key = new cef_string_t(key_str, key != null ? key.Length : 0);
return cef_v8value_t.invoke_has_value_bykey(this.ptr, &n_key) != 0;
}
}
/// <summary>
/// Returns true if the object has a value with the specified identifier.
/// </summary>
public bool HasValue(int index)
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_has_value_byindex(this.ptr, index) != 0;
}
/// <summary>
/// Delete the value with the specified identifier and returns true on
/// success. Returns false if this method is called incorrectly or an exception
/// is thrown. For read-only and don't-delete values this method will return
/// true even though deletion failed.
/// </summary>
public bool DeleteValue(string key)
{
ThrowIfObjectIsInvalid();
fixed (char* key_str = key)
{
var n_key = new cef_string_t(key_str, key != null ? key.Length : 0);
return cef_v8value_t.invoke_delete_value_bykey(this.ptr, &n_key) != 0;
}
}
/// <summary>
/// Delete the value with the specified identifier and returns true on
/// success. Returns false if this method is called incorrectly, deletion fails
/// or an exception is thrown. For read-only and don't-delete values this
/// method will return true even though deletion failed.
/// </summary>
public bool DeleteValue(int index)
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_delete_value_byindex(this.ptr, index) != 0;
}
/// <summary>
/// Returns the value with the specified identifier on success. Returns null
/// if this method is called incorrectly or an exception is thrown.
/// </summary>
public CefV8Value GetValue(string key)
{
ThrowIfObjectIsInvalid();
fixed (char* key_str = key)
{
var n_key = new cef_string_t(key_str, key != null ? key.Length : 0);
return CefV8Value.From(
cef_v8value_t.invoke_get_value_bykey(this.ptr, &n_key)
);
}
}
/// <summary>
/// Returns the value with the specified identifier on success. Returns null
/// if this method is called incorrectly or an exception is thrown.
/// </summary>
public CefV8Value GetValue(int index)
{
ThrowIfObjectIsInvalid();
return CefV8Value.From(
cef_v8value_t.invoke_get_value_byindex(this.ptr, index)
);
}
/// <summary>
/// Associates a value with the specified identifier and returns true on
/// success. Returns false if this method is called incorrectly or an exception
/// is thrown. For read-only values this method will return true even though
/// assignment failed.
/// </summary>
public bool SetValue(string key, CefV8Value value, CefV8PropertyAttribute attribute = CefV8PropertyAttribute.None)
{
ThrowIfObjectIsInvalid();
fixed (char* key_str = key)
{
var n_key = new cef_string_t(key_str, key != null ? key.Length : 0);
return cef_v8value_t.invoke_set_value_bykey(this.ptr, &n_key, value.GetNativePointerAndAddRef(), (cef_v8_propertyattribute_t)attribute) != 0;
}
}
/// <summary>
/// Associates a value with the specified identifier and returns true on
/// success. Returns false if this method is called incorrectly or an exception
/// is thrown. For read-only values this method will return true even though
/// assignment failed.
/// </summary>
public bool SetValue(int index, CefV8Value value)
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_set_value_byindex(this.ptr, index, value.GetNativePointerAndAddRef()) != 0;
}
/// <summary>
/// Registers an identifier and returns true on success. Access to the
/// identifier will be forwarded to the CefV8Accessor instance passed to
/// CefV8Value::CreateObject(). Returns false if this method is called
/// incorrectly or an exception is thrown. For read-only values this method
/// will return true even though assignment failed.
/// </summary>
public bool SetValue(string key, CefV8AccessControl settings, CefV8PropertyAttribute attribute)
{
ThrowIfObjectIsInvalid();
fixed (char* key_str = key)
{
var n_key = new cef_string_t(key_str, key != null ? key.Length : 0);
return cef_v8value_t.invoke_set_value_byaccessor(this.ptr, &n_key, (cef_v8_accesscontrol_t)settings, (cef_v8_propertyattribute_t)attribute) != 0;
}
}
/// <summary>
/// Read the keys for the object's values into the specified vector.
/// Integer- based keys will also be returned as strings.
/// </summary>
public bool TryGetKeys(out CefStringList keys)
{
ThrowIfObjectIsInvalid();
var nList = CefStringList.CreateHandle();
var success = cef_v8value_t.invoke_get_keys(this.ptr, nList) != 0;
if (success)
{
keys = CefStringList.From(nList, true);
return true;
}
else
{
CefStringList.DestroyHandle(nList);
keys = null;
return false;
}
}
/// <summary>
/// Read the keys for the object's values into the specified vector.
/// Integer- based keys will also be returned as strings.
/// </summary>
public CefStringList GetKeys()
{
ThrowIfObjectIsInvalid();
CefStringList keys;
if (TryGetKeys(out keys))
{
return keys;
}
else throw new CefException("CefV8Value.GetKeys failed.");
}
/// <summary>
/// Sets the user data for this object and returns true on success. Returns
/// false if this method is called incorrectly. This method can only be called
/// on user created objects.
/// </summary>
public bool SetUserData(CefUserData userData)
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_set_user_data(
this.ptr,
(cef_base_t*)userData.GetNativePointerAndAddRef()
) != 0;
}
/// <summary>
/// Returns the user data, if any, specified when the object was created.
/// </summary>
public CefUserData GetUserData()
{
ThrowIfObjectIsInvalid();
var n_base = cef_v8value_t.invoke_get_user_data(this.ptr);
if (n_base == null) return null;
return CefUserData.FromOrDefault((cefglue_userdata_t*)n_base);
}
/// <summary>
/// Returns the amount of externally allocated memory registered for the
/// object.
/// </summary>
public int GetExternallyAllocatedMemory()
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_get_externally_allocated_memory(this.ptr);
}
/// <summary>
/// Adjusts the amount of registered external memory for the object. Used to
/// give V8 an indication of the amount of externally allocated memory that is
/// kept alive by JavaScript objects. V8 uses this information to decide when
/// to perform global garbage collection. Each CefV8Value tracks the amount of
/// external memory associated with it and automatically decreases the global
/// total by the appropriate amount on its destruction. |change_in_bytes|
/// specifies the number of bytes to adjust by. This method returns the number
/// of bytes associated with the object after the adjustment. This method can
/// only be called on user created objects.
/// </summary>
public int AdjustExternallyAllocatedMemory(int change_in_bytes)
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_adjust_externally_allocated_memory(this.ptr, change_in_bytes);
}
// ARRAY METHODS - These methods are only available on arrays.
/// <summary>
/// Returns the number of elements in the array.
/// </summary>
public int GetArrayLength()
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_get_array_length(this.ptr);
}
// FUNCTION METHODS - These methods are only available on functions.
/// <summary>
/// Returns the function name.
/// </summary>
public string GetFunctionName()
{
ThrowIfObjectIsInvalid();
var nResult = cef_v8value_t.invoke_get_function_name(this.ptr);
return cef_string_userfree.GetStringAndFree(nResult);
}
/// <summary>
/// Returns the function handler or NULL if not a CEF-created function.
/// </summary>
public CefV8Handler GetFunctionHandler()
{
ThrowIfObjectIsInvalid();
return CefV8Handler.FromOrDefault(
cef_v8value_t.invoke_get_function_handler(this.ptr)
);
}
/// <summary>
/// Returns the exception resulting from the last method call. This attribute
/// exists only in the scope of the current CEF value object.
/// </summary>
public CefV8Exception GetException()
{
ThrowIfObjectIsInvalid();
return CefV8Exception.FromOrDefault(
cef_v8value_t.invoke_get_exception(this.ptr)
);
}
/// <summary>
/// Clears the last exception and returns true on success.
/// </summary>
public bool ClearException()
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_clear_exception(this.ptr) != 0;
}
/// <summary>
/// Set whether this object will re-throw future exceptions. By default
/// exceptions are not re-thrown. If a exception is re-thrown the current
/// context should not be accessed again until after the exception has been
/// caught and not re-thrown. Returns true on success. This attribute exists
/// only in the scope of the current CEF value object.
/// </summary>
public bool SetRethrowExceptions(bool rethrow)
{
ThrowIfObjectIsInvalid();
return cef_v8value_t.invoke_set_rethrow_exceptions(this.ptr, rethrow ? 1 : 0) != 0;
}
/// <summary>
/// Execute the function using the current V8 context. This method should only
/// be called from within the scope of a CefV8Handler or CefV8Accessor
/// callback, or in combination with calling Enter() and Exit() on a stored
/// CefV8Context reference. |object| is the receiver ('this' object) of the
/// function. If |object| is empty the current context's global object will be
/// used. |arguments| is the list of arguments that will be passed to the
/// function. Returns the function return value on success. Returns NULL if
/// this method is called incorrectly or an exception is thrown.
/// </summary>
public CefV8Value ExecuteFunction(CefV8Value obj, CefV8Value[] arguments)
{
ThrowIfObjectIsInvalid();
var n_arguments = CreateArgumentsArray(arguments);
fixed (cef_v8value_t** n_arguments_ptr = n_arguments)
{
return CefV8Value.FromOrDefault(
cef_v8value_t.invoke_execute_function(
this.ptr,
obj.GetNativePointerAndAddRef(),
n_arguments != null ? n_arguments.Length : 0,
n_arguments_ptr
)
);
}
}
/// <summary>
/// Execute the function using the specified V8 context. |object| is the
/// receiver ('this' object) of the function. If |object| is empty the
/// specified context's global object will be used. |arguments| is the list of
/// arguments that will be passed to the function. Returns the function return
/// value on success. Returns NULL if this method is called incorrectly or an
/// exception is thrown.
/// </summary>
public CefV8Value ExecuteFunctionWithContext(CefV8Context context, CefV8Value obj, CefV8Value[] arguments)
{
ThrowIfObjectIsInvalid();
var n_arguments = CreateArgumentsArray(arguments);
fixed (cef_v8value_t** n_arguments_ptr = n_arguments)
{
return CefV8Value.FromOrDefault(
cef_v8value_t.invoke_execute_function_with_context(
this.ptr,
context.GetNativePointerAndAddRef(),
obj.GetNativePointerAndAddRef(),
n_arguments != null ? n_arguments.Length : 0,
n_arguments_ptr
)
);
}
}
private static cef_v8value_t*[] CreateArgumentsArray(CefV8Value[] arguments)
{
if (arguments == null) return null;
var length = arguments.Length;
if (length == 0) return null;
var result = new cef_v8value_t*[arguments.Length];
for (var i = 0; i < length; i++)
{
result[i] = arguments[i].GetNativePointerAndAddRef();
}
return result;
}
}
}
| 34.57199 | 161 | 0.543104 | [
"BSD-3-Clause"
] | yasoonOfficial/cefglue | CefGlue/Proxy/CefV8Value.Impl.cs | 26,413 | C# |
namespace _02.KingsGambit.Models
{
using System;
public class RoyalGuard : Soldier
{
public RoyalGuard(string name)
: base(name)
{
}
public override void KingUnderAttack(object sender, EventArgs e)
{
Console.WriteLine($"Royal Guard {this.Name} is defending!");
}
}
}
| 19.888889 | 72 | 0.564246 | [
"MIT"
] | melikpehlivanov/CSharp-OOP-Advanced | Object Communication and Events - Exercise/02.KingsGambit/Models/RoyalGuard.cs | 360 | C# |
using System;
namespace PhotoMSK.Data.Models
{
public class DeleteRouteRequest
{
public Guid ID { get; set; }
public DateTime Date { get; set; }
public virtual RouteEntity Route { get; set; }
public Guid RouteID { get; set; }
public string Reason { get; set; }
}
}
| 22.785714 | 54 | 0.598746 | [
"MIT"
] | MarkusMokler/photomsmsk-by | PhotoMSK/Core/PhotoMSK.Data/Models/DeleteRouteRequest.cs | 321 | C# |
using System.Linq;
using Abp;
using Abp.Authorization;
using Abp.Authorization.Roles;
using Abp.Authorization.Users;
using Abp.MultiTenancy;
using Abp.Notifications;
using Microsoft.AspNetCore.Identity;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Options;
using Roc.CMS.Authorization;
using Roc.CMS.Authorization.Roles;
using Roc.CMS.Authorization.Users;
using Roc.CMS.EntityFrameworkCore;
using Roc.CMS.Notifications;
namespace Roc.CMS.Migrations.Seed.Tenants
{
public class TenantRoleAndUserBuilder
{
private readonly AbpZeroTemplateDbContext _context;
private readonly int _tenantId;
public TenantRoleAndUserBuilder(AbpZeroTemplateDbContext context, int tenantId)
{
_context = context;
_tenantId = tenantId;
}
public void Create()
{
CreateRolesAndUsers();
}
private void CreateRolesAndUsers()
{
//Admin role
var adminRole = _context.Roles.IgnoreQueryFilters().FirstOrDefault(r => r.TenantId == _tenantId && r.Name == StaticRoleNames.Tenants.Admin);
if (adminRole == null)
{
adminRole = _context.Roles.Add(new Role(_tenantId, StaticRoleNames.Tenants.Admin, StaticRoleNames.Tenants.Admin) { IsStatic = true }).Entity;
_context.SaveChanges();
}
//User role
var userRole = _context.Roles.IgnoreQueryFilters().FirstOrDefault(r => r.TenantId == _tenantId && r.Name == StaticRoleNames.Tenants.User);
if (userRole == null)
{
_context.Roles.Add(new Role(_tenantId, StaticRoleNames.Tenants.User, StaticRoleNames.Tenants.User) { IsStatic = true, IsDefault = true });
_context.SaveChanges();
}
//admin user
var adminUser = _context.Users.IgnoreQueryFilters().FirstOrDefault(u => u.TenantId == _tenantId && u.UserName == AbpUserBase.AdminUserName);
if (adminUser == null)
{
adminUser = User.CreateTenantAdminUser(_tenantId, "admin@defaulttenant.com");
adminUser.Password = new PasswordHasher<User>(new OptionsWrapper<PasswordHasherOptions>(new PasswordHasherOptions())).HashPassword(adminUser, "123qwe");
adminUser.IsEmailConfirmed = true;
adminUser.ShouldChangePasswordOnNextLogin = true;
adminUser.IsActive = true;
_context.Users.Add(adminUser);
_context.SaveChanges();
//Assign Admin role to admin user
_context.UserRoles.Add(new UserRole(_tenantId, adminUser.Id, adminRole.Id));
_context.SaveChanges();
//User account of admin user
if (_tenantId == 1)
{
_context.UserAccounts.Add(new UserAccount
{
TenantId = _tenantId,
UserId = adminUser.Id,
UserName = AbpUserBase.AdminUserName,
EmailAddress = adminUser.EmailAddress
});
_context.SaveChanges();
}
//Notification subscription
_context.NotificationSubscriptions.Add(new NotificationSubscriptionInfo(SequentialGuidGenerator.Instance.Create(), _tenantId, adminUser.Id, AppNotificationNames.NewUserRegistered));
_context.SaveChanges();
}
}
}
}
| 38.139785 | 197 | 0.610375 | [
"MIT"
] | RocChing/Roc.CMS | src/Roc.CMS.EntityFrameworkCore/Migrations/Seed/Tenants/TenantRoleAndUserBuilder.cs | 3,549 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace SFA.DAS.Commitments.Domain.Entities
{
public class OverlappingEmail
{
public long RowId { get; set; }
public long? Id { get; set; }
public long? CohortId { get; set; }
public string FirstName { get; set; }
public string LastName { get; set; }
public DateTime? DateOfBirth { get; set; }
public DateTime? StartDate { get; set; }
public DateTime? EndDate { get; set; }
public bool IsApproved { get; set; }
public string Email { get; set; }
public OverlapStatus OverlapStatus { get; set; }
}
public enum OverlapStatus : short
{
None = 0,
OverlappingStartDate = 1,
OverlappingEndDate = 2,
DateEmbrace = 3,
DateWithin = 4
}
}
| 27.30303 | 56 | 0.608213 | [
"MIT"
] | SkillsFundingAgency/das-commitments | src/SFA.DAS.Commitments.Domain/Entities/OverlappingEmail.cs | 903 | C# |
namespace FlockingBirds.Game.DrawableParts.Defaults
{
using Textures;
using SharpDX;
using SharpDX.Toolkit;
using SharpDX.Toolkit.Content;
using SharpDX.Toolkit.Graphics;
using Extensions;
using FlockingSimulation.Setup;
using SharpDX.Toolkit.Input;
public class MousePart : IMousePart
{
private readonly IFlockingBirdsGameTexturesManager textureManager;
private readonly IFlockingSetupAccessor setup;
private IMouseService mouseService;
private GraphicsDevice graphicsDevice;
private Vector2 lastPosition;
private Game game;
public MousePart(IFlockingBirdsGameTexturesManager textureManager, IFlockingSetupAccessor setup)
{
this.textureManager = textureManager;
this.setup = setup;
}
public void Draw(GameTime gameTime)
{
var sprite = new SpriteBatch(graphicsDevice);
sprite.Begin();
sprite.Draw(
this.textureManager.MouseTexture,
new Rectangle((int) this.lastPosition.X, (int) this.lastPosition.Y, 25, 25),
Color.White);
sprite.End();
}
public void Update(GameTime gameTime)
{
var state = this.mouseService.GetState();
this.lastPosition = new Vector2(state.X * this.setup.Width, state.Y * this.setup.Height);
}
public void Load(ContentManager contentManager, GraphicsDevice deviceManager, Game game)
{
textureManager.Load(contentManager);
this.graphicsDevice = deviceManager;
this.game = game;
this.mouseService = MouseServiceExtensions.Resolve(this.game);
}
}
}
| 26.893939 | 104 | 0.629296 | [
"MIT"
] | pwasiewicz/flockingbirds | FlockingBirds.Game/DrawableParts/Defaults/MousePart.cs | 1,777 | C# |
using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Linq;
using System.Threading.Tasks;
using Npgsql;
using C = Quartz.Plugins.RecentHistory.Impl.Postgres.PostgresConstants;
namespace Quartz.Plugins.RecentHistory.Impl.Postgres
{
public class PostgresExecutionHistoryStore : IExecutionHistoryStore
{
private DateTime _nextPurgeTime = DateTime.UtcNow;
public string SchedulerName { get; set; }
public string ConnectionString { get; set; }
public string TablePrefix { get; set; }
public int PurgeIntervalInMinutes { get; set; }
public int EntryTTLInMinutes { get; set; }
public async Task<ExecutionHistoryEntry> Get(string fireInstanceId)
{
if (fireInstanceId == null) throw new ArgumentNullException(nameof(fireInstanceId));
string query =
$"SELECT * FROM {GetTableName(C.TableExecutionHistoryEntries)} \n" +
$"WHERE {C.ColumnFireInstanceId} = @FireInstanceId";
var entries = await ExecuteExecutionHistoryEntryQuery(query, c => c.Parameters.AddWithValue("@FireInstanceId", fireInstanceId));
return entries.FirstOrDefault();
}
public async Task Save(ExecutionHistoryEntry entry)
{
if (entry == null) throw new ArgumentNullException(nameof(entry));
if (_nextPurgeTime < DateTime.UtcNow)
{
_nextPurgeTime = DateTime.UtcNow.AddMinutes(PurgeIntervalInMinutes);
await Purge();
}
using (var sqlConnection = new NpgsqlConnection(ConnectionString))
{
await sqlConnection.OpenAsync();
string query =
$"MERGE {GetTableName(C.TableExecutionHistoryEntries)} AS [Target] \n" +
$"USING (SELECT @FireInstanceId AS {C.ColumnFireInstanceId}) AS [Source] \n" +
$"ON [Source].{C.ColumnFireInstanceId} = [Target].{C.ColumnFireInstanceId} \n" +
$"WHEN MATCHED THEN UPDATE SET \n" +
$"{C.ColumnFireInstanceId} = @FireInstanceId, {C.ColumnSchedulerInstanceId} = @SchedulerInstanceId, {C.ColumnSchedulerName} = @SchedulerName, \n" +
$"{C.ColumnJob} = @Job, {C.ColumnTrigger} = @Trigger, {C.ColumnScheduledFireTimeUtc} = @ScheduledFireTimeUtc, {C.ColumnActualFireTimeUtc} = @ActualFireTimeUtc, \n" +
$"{C.ColumnRecovering} = @Recovering, {C.ColumnVetoed} = @Vetoed, {C.ColumnFinishedTimeUtc} = @FinishedTimeUtc, {C.ColumnExceptionMessage} = @ExceptionMessage \n" +
$"WHEN NOT MATCHED THEN INSERT \n" +
$"({C.ColumnFireInstanceId}, {C.ColumnSchedulerInstanceId}, {C.ColumnSchedulerName}, \n" +
$"{C.ColumnJob}, {C.ColumnTrigger}, {C.ColumnScheduledFireTimeUtc}, {C.ColumnActualFireTimeUtc}, \n" +
$"{C.ColumnRecovering}, {C.ColumnVetoed}, {C.ColumnFinishedTimeUtc}, {C.ColumnExceptionMessage}) \n" +
$"VALUES (@FireInstanceId, @SchedulerInstanceId, @SchedulerName, @Job, @Trigger, @ScheduledFireTimeUtc, \n" +
$"@ActualFireTimeUtc, @Recovering, @Vetoed, @FinishedTimeUtc, @ExceptionMessage);";
using (var sqlCommand = new NpgsqlCommand(query, sqlConnection))
{
sqlCommand.Parameters.AddWithValue("@FireInstanceId", entry.FireInstanceId);
sqlCommand.Parameters.AddWithValue("@SchedulerInstanceId", entry.SchedulerInstanceId);
sqlCommand.Parameters.AddWithValue("@SchedulerName", entry.SchedulerName);
sqlCommand.Parameters.AddWithValue("@Job", entry.Job);
sqlCommand.Parameters.AddWithValue("@Trigger", entry.Trigger);
sqlCommand.Parameters.AddWithValue("@ScheduledFireTimeUtc", entry.ScheduledFireTimeUtc != null ? (object)entry.ScheduledFireTimeUtc : DBNull.Value);
sqlCommand.Parameters.AddWithValue("@ActualFireTimeUtc", entry.ActualFireTimeUtc);
sqlCommand.Parameters.AddWithValue("@Recovering", entry.Recovering);
sqlCommand.Parameters.AddWithValue("@Vetoed", entry.Vetoed);
sqlCommand.Parameters.AddWithValue("@FinishedTimeUtc", entry.FinishedTimeUtc != null ? (object)entry.FinishedTimeUtc : DBNull.Value);
sqlCommand.Parameters.AddWithValue("@ExceptionMessage", entry.ExceptionMessage != null ? (object)entry.ExceptionMessage : DBNull.Value);
await sqlCommand.ExecuteNonQueryAsync();
}
}
}
public async Task Purge()
{
using (var sqlConnection = new NpgsqlConnection(ConnectionString))
{
await sqlConnection.OpenAsync();
string commandText = $"DELETE FROM {GetTableName(C.TableExecutionHistoryEntries)} WHERE {C.ColumnActualFireTimeUtc} < @PurgeThreshold";
using (var sqlCommand = new NpgsqlCommand(commandText, sqlConnection))
{
sqlCommand.Parameters.AddWithValue("@PurgeThreshold", DateTime.UtcNow.Subtract(TimeSpan.FromMinutes(EntryTTLInMinutes)));
await sqlCommand.ExecuteNonQueryAsync();
}
}
}
public async Task<IEnumerable<ExecutionHistoryEntry>> FilterLastOfEveryJob(int limitPerJob)
{
return await FilterLastOf(C.ColumnJob, limitPerJob);
}
public async Task<IEnumerable<ExecutionHistoryEntry>> FilterLastOfEveryTrigger(int limitPerTrigger)
{
return await FilterLastOf(C.ColumnTrigger, limitPerTrigger);
}
protected async Task<IEnumerable<ExecutionHistoryEntry>> FilterLastOf(string columnName, int limit)
{
string query =
$"WITH SELECTION AS ( \n" +
$" SELECT *, \n" +
$" ROW_NUMBER() OVER(PARTITION BY {columnName} ORDER BY {C.ColumnActualFireTimeUtc} DESC) AS ROW_KEY \n" +
$" FROM {GetTableName(C.TableExecutionHistoryEntries)} \n" +
$" WHERE {C.ColumnSchedulerName} = @SchedulerName \n" +
$") \n" +
$"SELECT * \n" +
$"FROM SELECTION \n" +
$"WHERE ROW_KEY <= {limit}";
return await ExecuteExecutionHistoryEntryQuery(query, c => c.Parameters.AddWithValue("@SchedulerName", SchedulerName));
}
public async Task<IEnumerable<ExecutionHistoryEntry>> FilterLast(int limit)
{
string query =
$"SELECT TOP {limit} * FROM {GetTableName(C.TableExecutionHistoryEntries)} \n" +
$"WHERE {C.ColumnSchedulerName} = @SchedulerName \n" +
$"ORDER BY {C.ColumnActualFireTimeUtc} DESC";
return await ExecuteExecutionHistoryEntryQuery(query, c => c.Parameters.AddWithValue("@SchedulerName", SchedulerName));
}
public async Task<int> GetTotalJobsExecuted()
{
try
{
return (int)await GetStatValue(C.StatTotalJobsExecuted);
}
catch (OverflowException)
{
/* should actually log here, but Quartz does not expose its
logging facilities to external plugins */
return -1;
}
}
public async Task<int> GetTotalJobsFailed()
{
try
{
return (int)await GetStatValue(C.StatTotalJobsFailed);
}
catch (OverflowException)
{
/* should actually log here, but Quartz does not expose its
logging facilities to external plugins */
return -1;
}
}
public async Task IncrementTotalJobsExecuted()
{
await IncrementStatValue(C.StatTotalJobsExecuted);
}
public async Task IncrementTotalJobsFailed()
{
await IncrementStatValue(C.StatTotalJobsFailed);
}
public async Task ClearSchedulerData()
{
using (var sqlConnection = new NpgsqlConnection(ConnectionString))
{
await sqlConnection.OpenAsync();
string commandText =
$"DELETE FROM {GetTableName(C.TableExecutionHistoryEntries)} WHERE {C.ColumnSchedulerName} = @SchedulerName;\n" +
$"DELETE FROM {GetTableName(C.TableExecutionHistoryStats)} WHERE {C.ColumnSchedulerName} = @SchedulerName;";
using (var sqlCommand = new NpgsqlCommand(commandText, sqlConnection))
{
sqlCommand.Parameters.AddWithValue("@SchedulerName", SchedulerName);
await sqlCommand.ExecuteNonQueryAsync();
}
}
}
protected string GetTableName(string tableNameWithoutPrefix)
{
if (tableNameWithoutPrefix == null) throw new ArgumentNullException(nameof(tableNameWithoutPrefix));
return $"{TablePrefix}{tableNameWithoutPrefix}";
}
protected async Task<List<ExecutionHistoryEntry>> ExecuteExecutionHistoryEntryQuery(string query, Action<NpgsqlCommand> sqlCommandModifier = null)
{
if (query == null) throw new ArgumentNullException(nameof(query));
using (var sqlConnection = new NpgsqlConnection(ConnectionString))
{
await sqlConnection.OpenAsync();
using (var sqlCommand = new NpgsqlCommand(query, sqlConnection))
{
sqlCommandModifier?.Invoke(sqlCommand);
using (var sqlDataReader = await sqlCommand.ExecuteReaderAsync())
{
var entries = new List<ExecutionHistoryEntry>();
while (await sqlDataReader.ReadAsync())
{
var entry = new ExecutionHistoryEntry();
await HydrateExecutionHistoryEntry(sqlDataReader, entry);
entries.Add(entry);
}
return entries;
}
}
}
}
protected async Task<long> GetStatValue(string statName)
{
if (statName == null) throw new ArgumentNullException(nameof(statName));
using (var sqlConnection = new NpgsqlConnection(ConnectionString))
{
await sqlConnection.OpenAsync();
string query =
$"SELECT {C.ColumnStatValue} FROM {GetTableName(C.TableExecutionHistoryStats)} \n" +
$"WHERE {C.ColumnStatName} = @StatName AND {C.ColumnSchedulerName} = @SchedulerName";
using (var sqlCommand = new NpgsqlCommand(query, sqlConnection))
{
sqlCommand.Parameters.AddWithValue("@SchedulerName", SchedulerName);
sqlCommand.Parameters.AddWithValue("@StatName", statName);
var scalar = await sqlCommand.ExecuteScalarAsync();
if (scalar != null)
{
return (long)scalar;
}
return 0;
}
}
}
protected async Task IncrementStatValue(string statName)
{
if (statName == null) throw new ArgumentNullException(nameof(statName));
using (var sqlConnection = new NpgsqlConnection(ConnectionString))
{
await sqlConnection.OpenAsync();
string query =
$"MERGE {GetTableName(C.TableExecutionHistoryStats)} AS [Target] \n" +
$"USING (SELECT @StatName AS {C.ColumnStatName}, @SchedulerName AS {C.ColumnSchedulerName}) AS [Source] \n" +
$"ON [Source].{C.ColumnStatName} = [Target].{C.ColumnStatName} AND [Source].{C.ColumnSchedulerName} = [Target].{C.ColumnSchedulerName} \n" +
$"WHEN MATCHED THEN UPDATE SET \n" +
$"{C.ColumnStatValue} = {C.ColumnStatValue} + 1 \n" +
$"WHEN NOT MATCHED THEN INSERT \n" +
$"({C.ColumnSchedulerName}, {C.ColumnStatName}, {C.ColumnStatValue}) \n" +
$"VALUES (@SchedulerName, @StatName, 1);";
using (var sqlCommand = new NpgsqlCommand(query, sqlConnection))
{
sqlCommand.Parameters.AddWithValue("@SchedulerName", SchedulerName);
sqlCommand.Parameters.AddWithValue("@StatName", statName);
try
{
await sqlCommand.ExecuteNonQueryAsync();
}
catch (SqlException e) when (e.Number == 8115) // SQL overflow exception
{
/* should actually log here, but Quartz does not expose its
logging facilities to external plugins */
}
}
}
}
private async Task HydrateExecutionHistoryEntry(NpgsqlDataReader sqlDataReader, ExecutionHistoryEntry entry)
{
var r = sqlDataReader;
entry.ActualFireTimeUtc = r.GetDateTime(r.GetOrdinal(C.ColumnActualFireTimeUtc));
entry.ExceptionMessage = await r.IsDBNullAsync(r.GetOrdinal(C.ColumnExceptionMessage)) ?
null : r.GetString(r.GetOrdinal(C.ColumnExceptionMessage));
entry.FinishedTimeUtc = await r.IsDBNullAsync(r.GetOrdinal(C.ColumnFinishedTimeUtc)) ?
(DateTime?)null : r.GetDateTime(r.GetOrdinal(C.ColumnFinishedTimeUtc));
entry.FireInstanceId = r.GetString(r.GetOrdinal(C.ColumnFireInstanceId));
entry.Job = r.GetString(r.GetOrdinal(C.ColumnJob));
entry.Recovering = r.GetBoolean(r.GetOrdinal(C.ColumnRecovering));
entry.ScheduledFireTimeUtc = await r.IsDBNullAsync(r.GetOrdinal(C.ColumnScheduledFireTimeUtc)) ?
(DateTime?)null : r.GetDateTime(r.GetOrdinal(C.ColumnScheduledFireTimeUtc));
entry.SchedulerInstanceId = r.GetString(r.GetOrdinal(C.ColumnSchedulerInstanceId));
entry.SchedulerName = r.GetString(r.GetOrdinal(C.ColumnSchedulerName));
entry.Trigger = r.GetString(r.GetOrdinal(C.ColumnTrigger));
entry.Vetoed = r.GetBoolean(r.GetOrdinal(C.ColumnVetoed));
}
}
}
| 47.374194 | 185 | 0.587839 | [
"MIT"
] | zdomokos/Quartzmin | Source/Quartz.Plugins.RecentHistory/Impl/Postgres/PostgresExecutionHistoryStore.cs | 14,688 | C# |
//
// Copyright 2021 Dynatrace LLC
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
namespace Dynatrace.OneAgent.Sdk.Api
{
/// <summary>
/// Tracer used for tracing an incoming web request.
/// See <see cref="IOneAgentSdk.TraceIncomingWebRequest"/>.
/// </summary>
public interface IIncomingWebRequestTracer : ITracer, IIncomingTaggable
{
/// <summary>
/// Sets the remote IP address of the incoming web request.
/// The remote address can only be set before the tracer is started.
///
/// This information is very useful to gain information about load balancers, proxies and
/// ultimately the end user that is sending the request.
///
/// The remote address is the peer address of the socket connection via which the request was received.
/// In case one or more proxies are used, this will be the address of the last proxy in the proxy chain.
/// To enable OneAgent to determine the client IP address (i.e., the address where the request originated),
/// an application should also call <see cref="AddRequestHeader"/> to add HTTP request headers.
/// </summary>
/// <param name="remoteAddress">remote IP address</param>
void SetRemoteAddress(string remoteAddress);
/// <summary>
/// All HTTP POST parameters should be provided to this method.
/// Selective capturing will be done based on sensor configuration.
/// </summary>
/// <param name="name">HTTP parameter name</param>
/// <param name="value">HTTP parameter value</param>
void AddParameter(string name, string value);
/// <summary>
/// All HTTP request headers should be provided to this method.
/// Selective capturing will be done based on sensor configuration.
/// Request headers can only be set *before* starting the tracer.
///
/// This method can be called multiple times with the same header name to provide multiple values.
/// </summary>
/// <param name="name">HTTP request header field name</param>
/// <param name="value">HTTP request header field value</param>
void AddRequestHeader(string name, string value);
/// <summary>
/// All HTTP response headers returned by the server should be provided to this method.
/// Selective capturing will be done based on sensor configuration.
/// Response headers can only be set *before* ending the tracer.
///
/// This method can be called multiple times with the same header name to provide multiple values.
/// </summary>
/// <param name="name">HTTP response header field name</param>
/// <param name="value">HTTP response header field value</param>
void AddResponseHeader(string name, string value);
/// <summary>
/// Sets the HTTP response status code.
/// </summary>
/// <param name="statusCode">HTTP status code of the response sent to the client</param>
void SetStatusCode(int statusCode);
}
}
| 47.142857 | 115 | 0.65978 | [
"Apache-2.0"
] | Dynatrace/OneAgent-SDK-for-dotnet | src/Api/IIncomingWebRequestTracer.cs | 3,630 | C# |
namespace MPT.CSI.API.Core.Program.ModelBehavior.Definition.LoadPattern
{
#if !BUILD_ETABS2015 && !BUILD_ETABS2016 && !BUILD_ETABS2017
/// <summary>
/// Seismic intensity for Chinese 2010 response spectrum function.
/// </summary>
public enum eSeismicIntensity_Chinese_2010
{
/// <summary>
/// Intensity 6 (0.05g).
/// </summary>
Intensity6_0_05g = 1,
/// <summary>
/// Intensity 7 (0.10g).
/// </summary>
Intensity7_0_10g = 2,
/// <summary>
/// Intensity 7 (0.15g).
/// </summary>
Intensity7_0_15g = 3,
/// <summary>
/// Intensity 8 (0.20g).
/// </summary>
Intensity8_0_20g = 4,
/// <summary>
/// Intensity 8 (0.30g).
/// </summary>
Intensity8_0_30g = 5,
/// <summary>
/// Intensity 9 (0.40g).
/// </summary>
Intensity9_0_40g = 6,
}
#endif
} | 24.1 | 72 | 0.511411 | [
"MIT"
] | MarkPThomas/MPT.Net | MPT/CSI/API/MPT.CSI.API/Core/Program/ModelBehavior/Definition/LoadPattern/eSeismicIntensity_Chinese_2010.cs | 966 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
namespace Microsoft.Bot.Schema
{
using System;
using System.Collections.Generic;
using Newtonsoft.Json;
/// <summary>
/// Provides information about the requested transaction.
/// </summary>
[Obsolete("Bot Framework no longer supports payments.")]
public partial class PaymentDetails
{
/// <summary>
/// Initializes a new instance of the <see cref="PaymentDetails"/> class.
/// </summary>
public PaymentDetails()
{
CustomInit();
}
/// <summary>
/// Initializes a new instance of the <see cref="PaymentDetails"/> class.
/// </summary>
/// <param name="total">Contains the total amount of the payment
/// request.</param>
/// <param name="displayItems">Contains line items for the payment
/// request that the user agent may display.</param>
/// <param name="shippingOptions">A sequence containing the different
/// shipping options for the user to choose from.</param>
/// <param name="modifiers">Contains modifiers for particular payment
/// method identifiers.</param>
/// <param name="error">Error description.</param>
public PaymentDetails(PaymentItem total = default(PaymentItem), IList<PaymentItem> displayItems = default(IList<PaymentItem>), IList<PaymentShippingOption> shippingOptions = default(IList<PaymentShippingOption>), IList<PaymentDetailsModifier> modifiers = default(IList<PaymentDetailsModifier>), string error = default(string))
{
Total = total;
DisplayItems = displayItems;
ShippingOptions = shippingOptions;
Modifiers = modifiers;
Error = error;
CustomInit();
}
/// <summary>
/// Gets or sets contains the total amount of the payment request.
/// </summary>
/// <value>The total amount of the payment request.</value>
[JsonProperty(PropertyName = "total")]
public PaymentItem Total { get; set; }
/// <summary>
/// Gets or sets contains line items for the payment request that the
/// user agent may display.
/// </summary>
/// <value>The items for the payment request.</value>
[JsonProperty(PropertyName = "displayItems")]
#pragma warning disable CA2227 // Collection properties should be read only (we can't change this without breaking compat).
public IList<PaymentItem> DisplayItems { get; set; }
#pragma warning restore CA2227 // Collection properties should be read only
/// <summary>
/// Gets or sets a sequence containing the different shipping options
/// for the user to choose from.
/// </summary>
/// <value>The the different shipping options for the user to choose from.</value>
[JsonProperty(PropertyName = "shippingOptions")]
#pragma warning disable CA2227 // Collection properties should be read only (we can't change this without breaking compat).
public IList<PaymentShippingOption> ShippingOptions { get; set; }
#pragma warning restore CA2227 // Collection properties should be read only
/// <summary>
/// Gets or sets contains modifiers for particular payment method
/// identifiers.
/// </summary>
/// <value>The modifiers for a particular payment method.</value>
[JsonProperty(PropertyName = "modifiers")]
#pragma warning disable CA2227 // Collection properties should be read only (we can't change this without breaking compat).
public IList<PaymentDetailsModifier> Modifiers { get; set; }
#pragma warning restore CA2227 // Collection properties should be read only
/// <summary>
/// Gets or sets error description.
/// </summary>
/// <value>The error description.</value>
[JsonProperty(PropertyName = "error")]
public string Error { get; set; }
/// <summary>
/// An initialization method that performs custom operations like setting defaults.
/// </summary>
partial void CustomInit();
}
}
| 44.03125 | 334 | 0.644192 | [
"MIT"
] | Alpharceus/botbuilder-dotnet | libraries/Microsoft.Bot.Schema/PaymentDetails.cs | 4,229 | C# |
//--------------------------------------
// Brotli Decompressor
//
// For documentation or
// if you have any issues, visit
// powerUI.kulestar.com
//
// Copyright © 2016 Kulestar Ltd
// www.kulestar.com
//--------------------------------------
using System;
using System.IO;
using PowerUI;
namespace Brotli{
/// <summary>An event that triggers when the dictionary is ready.</summary>
public delegate void DictionaryReadyEvent();
/// <summary>
/// Brotli static dictionary.
/// </summary>
public static class Dictionary{
/// <summary>Location of the dictionary.</summary>
public static string Location="resources://brotli-static";
/// <summary>The dictionary data.</summary>
internal static byte[] Data;
internal readonly static uint[] OffsetsByLength = new uint[]{
0, 0, 0, 0, 0, 4096, 9216, 21504, 35840, 44032,
53248, 63488, 74752, 87040, 93696, 100864, 104704, 106752, 108928, 113536,
115968, 118528, 119872, 121280, 122016,
};
internal readonly static byte[] SizeBitsByLength = new byte[]{
0, 0, 0, 0, 10, 10, 11, 11, 10, 10,
10, 10, 10, 9, 9, 8, 7, 7, 8, 7,
7, 6, 6, 5, 5,
};
internal const int MinDictionaryWordLength = 4;
internal const int MaxDictionaryWordLength = 24;
/// <summary>Loads the dictionary.</summary>
public static void Load(DictionaryReadyEvent onLoaded){
// Get it:
DataPackage package=new DataPackage(Location);
package.onload=delegate(UIEvent e){
Data=package.responseBytes;
onLoaded();
};
// Go!
package.send();
}
}
} | 23.884058 | 77 | 0.597694 | [
"MIT"
] | HeasHeartfire/Mega-Test | Assets/PowerUI/Source/Decompressors/Brotli/Source/dictionary.cs | 1,649 | C# |
using NHapi.Base.Parser;
using NHapi.Base;
using NHapi.Base.Log;
using System;
using System.Collections.Generic;
using NHapi.Model.V231.Segment;
using NHapi.Model.V231.Datatype;
using NHapi.Base.Model;
namespace NHapi.Model.V231.Group
{
///<summary>
///Represents the ORM_O01_INSURANCE Group. A Group is an ordered collection of message
/// segments that can repeat together or be optionally in/excluded together.
/// This Group contains the following elements:
///<ol>
///<li>0: IN1 (IN1 - insurance segment) </li>
///<li>1: IN2 (IN2 - insurance additional information segment) optional </li>
///<li>2: IN3 (IN3 - insurance additional information, certification segment) optional repeating</li>
///</ol>
///</summary>
[Serializable]
public class ORM_O01_INSURANCE : AbstractGroup {
///<summary>
/// Creates a new ORM_O01_INSURANCE Group.
///</summary>
public ORM_O01_INSURANCE(IGroup parent, IModelClassFactory factory) : base(parent, factory){
try {
this.add(typeof(IN1), true, false);
this.add(typeof(IN2), false, false);
this.add(typeof(IN3), false, true);
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating ORM_O01_INSURANCE - this is probably a bug in the source code generator.", e);
}
}
///<summary>
/// Returns IN1 (IN1 - insurance segment) - creates it if necessary
///</summary>
public IN1 IN1 {
get{
IN1 ret = null;
try {
ret = (IN1)this.GetStructure("IN1");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns IN2 (IN2 - insurance additional information segment) - creates it if necessary
///</summary>
public IN2 IN2 {
get{
IN2 ret = null;
try {
ret = (IN2)this.GetStructure("IN2");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
}
///<summary>
/// Returns first repetition of IN3 (IN3 - insurance additional information, certification segment) - creates it if necessary
///</summary>
public IN3 GetIN3() {
IN3 ret = null;
try {
ret = (IN3)this.GetStructure("IN3");
} catch(HL7Exception e) {
HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e);
throw new System.Exception("An unexpected error ocurred",e);
}
return ret;
}
///<summary>
///Returns a specific repetition of IN3
/// * (IN3 - insurance additional information, certification segment) - creates it if necessary
/// throws HL7Exception if the repetition requested is more than one
/// greater than the number of existing repetitions.
///</summary>
public IN3 GetIN3(int rep) {
return (IN3)this.GetStructure("IN3", rep);
}
/**
* Returns the number of existing repetitions of IN3
*/
public int IN3RepetitionsUsed {
get{
int reps = -1;
try {
reps = this.GetAll("IN3").Length;
} catch (HL7Exception e) {
string message = "Unexpected error accessing data - this is probably a bug in the source code generator.";
HapiLogFactory.GetHapiLog(GetType()).Error(message, e);
throw new System.Exception(message);
}
return reps;
}
}
/**
* Enumerate over the IN3 results
*/
public IEnumerable<IN3> IN3s
{
get
{
for (int rep = 0; rep < IN3RepetitionsUsed; rep++)
{
yield return (IN3)this.GetStructure("IN3", rep);
}
}
}
///<summary>
///Adds a new IN3
///</summary>
public IN3 AddIN3()
{
return this.AddStructure("IN3") as IN3;
}
///<summary>
///Removes the given IN3
///</summary>
public void RemoveIN3(IN3 toRemove)
{
this.RemoveStructure("IN3", toRemove);
}
///<summary>
///Removes the IN3 at the given index
///</summary>
public void RemoveIN3At(int index)
{
this.RemoveRepetition("IN3", index);
}
}
}
| 28.205298 | 155 | 0.666588 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | AMCN41R/nHapi | src/NHapi.Model.V231/Group/ORM_O01_INSURANCE.cs | 4,259 | C# |
using FluentAssertions;
using NSubstitute;
using Xunit;
namespace Sfa.Tl.ResultsAndCertification.Web.UnitTests.Loader.ResultLoaderTests.FindUlnResults
{
public class When_Called_With_Invalid_Data : TestSetup
{
public override void Given()
{
expectedApiResult = null;
InternalApiClient.FindUlnAsync(Ukprn, Uln).Returns(expectedApiResult);
}
[Fact]
public void Then_Returns_Expected_Results()
{
ActualResult.Should().BeNull();
}
}
} | 25.571429 | 94 | 0.659218 | [
"MIT"
] | SkillsFundingAgency/tl-result-and-certification | src/Tests/Sfa.Tl.ResultsAndCertification.Web.UnitTests/Loader/ResultLoaderTests/FindUlnResults/When_Called_With_Invalid_Data.cs | 539 | C# |
namespace Multiple_Video_Streams_Demo
{
using System;
using System.Windows.Forms;
using VisioForge.Controls.UI.WinForms;
using VisioForge.Tools.MediaInfo;
using VisioForge.Types;
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
private void btSelectFile_Click(object sender, EventArgs e)
{
if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
edFilenameOrURL.Text = openFileDialog1.FileName;
}
}
private async void btStart_Click(object sender, EventArgs e)
{
MediaPlayer1.Debug_Mode = cbDebugMode.Checked;
mmLog.Clear();
MediaPlayer1.Video_Renderer.Zoom_Ratio = 0;
MediaPlayer1.Video_Renderer.Zoom_ShiftX = 0;
MediaPlayer1.Video_Renderer.Zoom_ShiftY = 0;
var info = new MediaInfoReader
{
Filename = edFilenameOrURL.Text
};
info.ReadFileInfo(true);
MediaPlayer1.Multiple_Video_Streams_Mappings_Clear();
if (info.Video_Streams_Count() > 1)
{
for (int i = 0; i < info.Video_Streams_Count() - 1; i++)
{
if (i > 3)
{
break;
}
Panel panel = null;
switch (i)
{
case 0:
panel = pnScreen1;
break;
case 1:
panel = pnScreen2;
break;
case 2:
panel = pnScreen3;
break;
case 3:
panel = pnScreen4;
break;
}
if (panel != null)
{
MediaPlayer1.Multiple_Video_Streams_Mappings_Add(i, panel.Handle, panel.Width, panel.Height);
}
}
}
MediaPlayer1.FilenamesOrURL.Clear();
MediaPlayer1.FilenamesOrURL.Add(edFilenameOrURL.Text);
MediaPlayer1.Audio_PlayAudio = true;
MediaPlayer1.Info_UseLibMediaInfo = true;
MediaPlayer1.Source_Mode = VFMediaPlayerSource.File_DS;
if (MediaPlayer1.Filter_Supported_EVR())
{
MediaPlayer1.Video_Renderer.Video_Renderer = VFVideoRenderer.EVR;
}
else if (MediaPlayer1.Filter_Supported_VMR9())
{
MediaPlayer1.Video_Renderer.Video_Renderer = VFVideoRenderer.VMR9;
}
else
{
MediaPlayer1.Video_Renderer.Video_Renderer = VFVideoRenderer.VideoRenderer;
}
MediaPlayer1.Video_Sample_Grabber_UseForVideoEffects = false;
await MediaPlayer1.PlayAsync();
timer1.Enabled = true;
}
private void MediaPlayer1_OnError(object sender, ErrorsEventArgs e)
{
Invoke((Action)(() =>
{
mmLog.Text = mmLog.Text + e.Message + Environment.NewLine;
}));
}
private async void btResume_Click(object sender, EventArgs e)
{
await MediaPlayer1.ResumeAsync();
}
private async void btPause_Click(object sender, EventArgs e)
{
await MediaPlayer1.PauseAsync();
}
private async void btStop_Click(object sender, EventArgs e)
{
await MediaPlayer1.StopAsync();
timer1.Enabled = false;
tbTimeline.Value = 0;
}
private void btNextFrame_Click(object sender, EventArgs e)
{
MediaPlayer1.NextFrame();
}
private void tbTimeline_Scroll(object sender, EventArgs e)
{
if (Convert.ToInt32(timer1.Tag) == 0)
{
MediaPlayer1.Position_Set_Time(TimeSpan.FromSeconds(tbTimeline.Value));
}
}
private void timer1_Tick(object sender, EventArgs e)
{
timer1.Tag = 1;
tbTimeline.Maximum = (int)MediaPlayer1.Duration_Time().TotalSeconds;
int value = (int)MediaPlayer1.Position_Get_Time().TotalSeconds;
if ((value > 0) && (value < tbTimeline.Maximum))
{
tbTimeline.Value = value;
}
lbTime.Text = MediaPlayer.Helpful_SecondsToTimeFormatted(tbTimeline.Value) + "/" + MediaPlayer.Helpful_SecondsToTimeFormatted(tbTimeline.Maximum);
timer1.Tag = 0;
}
private void Form1_Load(object sender, EventArgs e)
{
}
private void MediaPlayer1_OnStop(object sender, MediaPlayerStopEventArgs e)
{
BeginInvoke(new StopDelegate(StopDelegateMethod), null);
}
private delegate void StopDelegate();
private void StopDelegateMethod()
{
tbTimeline.Value = 0;
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
btStop_Click(null, null);
}
}
}
| 30.111111 | 158 | 0.510332 | [
"MIT"
] | visioforge/.Net-SDK-s-samples-before-v12 | Media Player SDK/WinForms/CSharp/Multiple Video Streams/Form1.cs | 5,422 | C# |
using System;
using WebKit;
using AppKit;
using Foundation;
using System.Threading.Tasks;
using System.Net;
using System.Linq;
namespace SimpleAuth.Mac
{
public class WebAuthenticatorWebView : WebKit.WebView, IWebFrameLoadDelegate
{
public readonly WebAuthenticator Authenticator;
public WebAuthenticatorWebView(WebAuthenticator authenticator)
{
this.Authenticator = authenticator;
MonitorAuthenticator ();
this.FrameLoadDelegate = this;
}
async Task MonitorAuthenticator ()
{
try {
await Authenticator.GetAuthCode ();
if (!Authenticator.HasCompleted)
return;
BeginInvokeOnMainThread (() => {
try {
var app = NSApplication.SharedApplication;
app.EndSheet (shownInWindow);
window.OrderOut (this);
} catch (Exception ex) {
Console.WriteLine (ex);
}
});
} catch (Exception ex) {
Console.WriteLine (ex);
}
}
Task loadingTask;
public async void BeginLoadingInitialUrl ()
{
if (this.Authenticator.ClearCookiesBeforeLogin)
ClearCookies ();
if (loadingTask == null || loadingTask.IsCompleted) {
loadingTask = RealLoading ();
}
await loadingTask;
}
async Task RealLoading ()
{
//activity.StartAnimating ();
if (this.Authenticator.ClearCookiesBeforeLogin)
ClearCookies ();
//
// Begin displaying the page
//
try {
var url = await Authenticator.GetInitialUrl ();
if (url == null)
return;
var request = new NSUrlRequest (new NSUrl (url.AbsoluteUri));
NSUrlCache.SharedCache.RemoveCachedResponse (request);
this.MainFrame.LoadRequest (request);
} catch (Exception ex) {
Console.WriteLine (ex);
return;
} finally {
//activity.StopAnimating ();
}
}
void ClearCookies ()
{
}
private Cookie[] GetCookies (string url)
{
var store = NSHttpCookieStorage.SharedStorage;
var cookies = store.CookiesForUrl (new NSUrl (url)).Select (x => new Cookie (x.Name, x.Value, x.Path, x.Domain)).ToArray ();
return cookies;
}
[Export ("webView:didStartProvisionalLoadForFrame:")]
public void StartedProvisionalLoad (WebKit.WebView sender, WebKit.WebFrame forFrame)
{
var url = sender.MainFrameUrl;
if (!Authenticator.HasCompleted) {
Uri uri;
if (Uri.TryCreate (url, UriKind.Absolute, out uri)) {
if (Authenticator.CheckUrl (uri, GetCookies (url)))
return;
}
}
}
[Foundation.Export ("webView:didFinishLoadForFrame:")]
public void FinishedLoad (WebView sender, WebFrame forFrame)
{
var url = sender.MainFrameUrl;
if (!Authenticator.HasCompleted) {
Uri uri;
if (Uri.TryCreate (url, UriKind.Absolute, out uri)) {
if (Authenticator.CheckUrl (uri, GetCookies (url)))
return;
}
}
}
[Foundation.Export ("webView:didFailLoadWithError:forFrame:")]
public void FailedLoadWithError (WebView sender, NSError error, WebFrame forFrame)
{
Authenticator.OnError (error.LocalizedDescription);
}
[Foundation.Export ("webView:didFailProvisionalLoadWithError:forFrame:")]
public void FailedProvisionalLoad (WebView sender, NSError error, WebFrame forFrame)
{
var url = sender.MainFrameUrl;
if (!Authenticator.HasCompleted) {
Uri uri;
if (Uri.TryCreate (url, UriKind.Absolute, out uri)) {
if (Authenticator.CheckUrl (uri, GetCookies (url))) {
forFrame.StopLoading ();
return;
}
}
}
Authenticator.OnError (error.LocalizedDescription);
}
[Export ("webView:willPerformClientRedirectToURL:delay:fireDate:forFrame:")]
public void WillPerformClientRedirect (WebKit.WebView sender, Foundation.NSUrl toUrl, double secondsDelay, Foundation.NSDate fireDate, WebKit.WebFrame forFrame)
{
var url = sender.MainFrameUrl;
if (!Authenticator.HasCompleted) {
Uri uri;
if (Uri.TryCreate (url, UriKind.Absolute, out uri)) {
if (Authenticator.CheckUrl (uri, GetCookies (url))) {
forFrame.StopLoading ();
return;
}
}
} else {
forFrame.StopLoading ();
}
}
static NSWindow window;
static NSWindow shownInWindow;
public static async void ShowWebivew(WebAuthenticatorWebView webview)
{
var app = NSApplication.SharedApplication;
var rect = new CoreGraphics.CGRect (0, 0, 400, 600);
webview.Frame = rect;
window = new NSWindow (rect, NSWindowStyle.Closable | NSWindowStyle.Titled, NSBackingStore.Buffered, false);
window.ContentView = webview;
window.IsVisible = false;
window.Title = webview.Authenticator.Title;
while (shownInWindow == null) {
shownInWindow = app.MainWindow;
if (shownInWindow == null)
await Task.Delay (1000);
}
app.BeginSheet (window, shownInWindow);
webview.BeginLoadingInitialUrl ();
}
}
}
| 26.171271 | 162 | 0.68841 | [
"Apache-2.0"
] | rhedgpeth/SimpleAuth | src/SimpleAuth.Mac/WebAuthenticator.cs | 4,739 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using UltimateRedditBot.Core.Extensions;
using UltimateRedditBot.Domain.Queue;
using UltimateRedditBot.Infra.Services;
namespace UltimateRedditBot.Core.Services
{
[Serializable]
public class QueueClient : IQueueClient
{
#region Fields
public ulong GuildId { get; private set; }
public IEnumerable<QueueItem> QueueItems { get; set; }
private readonly IQueueService _queueService;
#endregion
#region Consturctor
public QueueClient(ulong guildId, IQueueService queueService)
{
GuildId = guildId;
_queueService = queueService;
QueueItems = new List<QueueItem>();
}
#endregion
#region Methods
public async Task Start()
{
while (true)
{
await Task.Run(async () =>
{
if (!QueueItems.Any())
return;
var queueItems = QueueItems.DistinctBy(x => x.SubRedditId).ToList();
await Process(queueItems);
});
}
}
public void RemoveByChannelId(ulong channelId)
{
QueueItems = QueueItems?.Where(x => x.ChannelId != channelId).ToList();
}
public void RemoveBySubredditId(ulong channelId, int subredditId)
{
QueueItems = QueueItems.Where(x => x.ChannelId != channelId || x.SubRedditId != subredditId ).ToList();
}
#region Utils
private async Task Process(ICollection<QueueItem> queueItems)
{
if (!queueItems.Any())
return;
await _queueService.ProcessQueue(queueItems.ToAsyncEnumerable());
lock (QueueItems)
{
var queue = QueueItems.ToList();
queue.RemoveAll(queueItems.Contains);
QueueItems = queue;
}
}
#endregion
#endregion
}
}
| 25.597561 | 115 | 0.557408 | [
"MIT"
] | bartb56/UltimateRedditBot | UltimateRedditBot.Core/Services/QueueClient.cs | 2,101 | C# |
namespace ClinicArrivals.Models
{
public interface ILoggingService
{
void Log(int level, string msg);
}
} | 18.857143 | 41 | 0.628788 | [
"BSD-2-Clause"
] | eugenekogan-spb/ClinicArrivals | ClinicArrivals.Models/ILoggingService.cs | 134 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
namespace TraceYourLife.Domain.Services
{
public interface IDataStore<T>
{
Task<bool> AddItemAsync(T item);
Task<bool> UpdateItemAsync(T item);
Task<bool> DeleteItemAsync(string id);
Task<T> GetItemAsync(string id);
Task<IEnumerable<T>> GetItemsAsync(bool forceRefresh = false);
}
}
| 26.733333 | 70 | 0.685786 | [
"Apache-2.0"
] | herbstsonne/TraceYourLife | TraceYourLife/TraceYourLife/Domain/Services/IDataStore.cs | 403 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Globalization;
namespace Microsoft.EntityFrameworkCore.Storage.ValueConversion.Internal;
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public class StringNumberConverter<TModel, TProvider, TNumber> : ValueConverter<TModel, TProvider>
{
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
// ReSharper disable once StaticMemberInGenericType
protected static readonly ConverterMappingHints _defaultHints = new(size: 64);
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
public StringNumberConverter(
Expression<Func<TModel, TProvider>> convertToProviderExpression,
Expression<Func<TProvider, TModel>> convertFromProviderExpression,
ConverterMappingHints? mappingHints = null)
: base(convertToProviderExpression, convertFromProviderExpression, mappingHints)
{
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected static Expression<Func<string, TNumber>> ToNumber()
{
var type = typeof(TNumber).UnwrapNullableType();
CheckTypeSupported(
type,
typeof(StringNumberConverter<TModel, TProvider, TNumber>),
typeof(int), typeof(long), typeof(short), typeof(byte),
typeof(uint), typeof(ulong), typeof(ushort), typeof(sbyte),
typeof(decimal), typeof(float), typeof(double));
var parseMethod = type.GetMethod(
nameof(double.Parse),
new[] { typeof(string), typeof(NumberStyles), typeof(IFormatProvider) })!;
var param = Expression.Parameter(typeof(string), "v");
Expression expression = Expression.Call(
parseMethod,
param,
Expression.Constant(NumberStyles.Any),
Expression.Constant(CultureInfo.InvariantCulture, typeof(IFormatProvider)));
if (typeof(TNumber).IsNullableType())
{
expression = Expression.Condition(
Expression.ReferenceEqual(param, Expression.Constant(null, typeof(string))),
Expression.Constant(null, typeof(TNumber)),
Expression.Convert(expression, typeof(TNumber)));
}
return Expression.Lambda<Func<string, TNumber>>(expression, param);
}
/// <summary>
/// This is an internal API that supports the Entity Framework Core infrastructure and not subject to
/// the same compatibility standards as public APIs. It may be changed or removed without notice in
/// any release. You should only use it directly in your code with extreme caution and knowing that
/// doing so can result in application failures when updating to a new Entity Framework Core release.
/// </summary>
protected static new Expression<Func<TNumber, string>> ToString()
{
var type = typeof(TNumber).UnwrapNullableType();
CheckTypeSupported(
type,
typeof(StringNumberConverter<TModel, TProvider, TNumber>),
typeof(int), typeof(long), typeof(short), typeof(byte),
typeof(uint), typeof(ulong), typeof(ushort), typeof(sbyte),
typeof(decimal), typeof(float), typeof(double));
var formatMethod = typeof(string).GetMethod(
nameof(string.Format),
new[] { typeof(IFormatProvider), typeof(string), typeof(object) })!;
var param = Expression.Parameter(typeof(TNumber), "v");
Expression expression = Expression.Call(
formatMethod,
Expression.Constant(CultureInfo.InvariantCulture),
Expression.Constant(type == typeof(float) || type == typeof(double) ? "{0:R}" : "{0}"),
Expression.Convert(param, typeof(object)));
if (typeof(TNumber).IsNullableType())
{
expression = Expression.Condition(
Expression.Call(param, typeof(TNumber).GetMethod("get_HasValue")!),
expression,
Expression.Constant(null, typeof(string)));
}
return Expression.Lambda<Func<TNumber, string>>(expression, param);
}
}
| 49.07563 | 109 | 0.674144 | [
"MIT"
] | Applesauce314/efcore | src/EFCore/Storage/ValueConversion/Internal/StringNumberConverter.cs | 5,840 | C# |
namespace AquaShop.Core.Contracts
{
using System;
public interface IEngine
{
void Run();
}
}
| 11.9 | 34 | 0.588235 | [
"MIT"
] | AntoniyaIvanova/SoftUni | C#/C# Advanced/C# OOP/10. EXAMS/15 Dec 2019/01. Structure/Core/Contracts/IEngine.cs | 121 | C# |
using Avalonia;
using Avalonia.Controls;
using Avalonia.Markup.Xaml;
namespace FluentAvaloniaSamples.Pages
{
public partial class PathIconPage : UserControl
{
public PathIconPage()
{
InitializeComponent();
}
private void InitializeComponent()
{
AvaloniaXamlLoader.Load(this);
}
}
}
| 15.25 | 48 | 0.740984 | [
"MIT"
] | DrewNaylor/FluentAvalonia | FluentAvaloniaSamples/Pages/IconPages/PathIconPage.axaml.cs | 305 | C# |
namespace Utility
{
public interface ICloneable<TYPE_T>
{
TYPE_T Clone();
}
}
| 12.375 | 39 | 0.585859 | [
"MIT"
] | rougemeilland/ZipArchiveNormalizer | Utility/ICloneable.cs | 101 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Input;
using GalaSoft.MvvmLight;
using SIL.Machine.Utils;
namespace SIL.Machine.Translation.TestApp
{
public class TaskViewModel : ViewModelBase
{
private readonly Func<IProgress<ProgressStatus>, CancellationToken, Task> _execute;
private readonly AsyncRelayCommand _startTaskCommand;
private readonly RelayCommand _cancelCommand;
private CancellationTokenSource _cts;
private bool _isExecuting;
private int _percentCompleted;
private string _message;
public TaskViewModel(Func<IProgress<ProgressStatus>, CancellationToken, Task> execute, Func<bool> canExecute)
{
_execute = execute;
_startTaskCommand = new AsyncRelayCommand(ExecuteAsync, canExecute);
_cancelCommand = new RelayCommand(Cancel, CanCancel);
}
private async Task ExecuteAsync()
{
using (_cts = new CancellationTokenSource())
{
IsExecuting = true;
_cancelCommand.UpdateCanExecute();
var progress = new Progress<ProgressStatus>(p =>
{
PercentCompleted = (int) Math.Round(p.PercentCompleted * 100, MidpointRounding.AwayFromZero);
Message = p.Message;
});
CancellationToken token = _cts.Token;
Task task = null;
try
{
task = _execute(progress, token);
await task;
}
catch
{
}
if (task != null && task.IsFaulted && task.Exception != null)
throw task.Exception;
IsExecuting = false;
_cancelCommand.UpdateCanExecute();
}
}
private bool CanCancel()
{
return IsExecuting && !_cts.IsCancellationRequested;
}
private void Cancel()
{
_cts.Cancel();
_cancelCommand.UpdateCanExecute();
Message = "Canceling";
}
public int PercentCompleted
{
get => _percentCompleted;
private set => Set(nameof(PercentCompleted), ref _percentCompleted, value);
}
public string Message
{
get => _message;
private set => Set(nameof(Message), ref _message, value);
}
public bool IsExecuting
{
get => _isExecuting;
private set
{
if (Set(nameof(IsExecuting), ref _isExecuting, value))
RaisePropertyChanged(nameof(IsNotExecuting));
}
}
public bool IsNotExecuting => !_isExecuting;
public ICommand StartTaskCommand => _startTaskCommand;
public ICommand CancelCommand => _cancelCommand;
public void UpdateCanExecute()
{
_startTaskCommand.UpdateCanExecute();
}
}
}
| 23.524272 | 111 | 0.710277 | [
"MIT"
] | russellmorley/machine | samples/SIL.Machine.Translation.TestApp/TaskViewModel.cs | 2,425 | C# |
//Author Maxim Kuzmin//makc//
using Makc2020.Core.Base.Auth.Enums;
using Makc2020.Mods.Auth.Base.Config.Settings;
namespace Makc2020.Mods.Auth.Base.Config
{
/// <summary>
/// Мод "Auth". Основа. Конфигурация. Настройки. Интерфейс.
/// </summary>
public interface IModAuthBaseConfigSettings
{
#region Properties
/// <summary>
/// Тип.
/// </summary>
CoreBaseAuthEnumTypes Type { get; }
/// <summary>
/// Типы.
/// </summary>
IModAuthBaseConfigSettingTypes Types { get; }
#endregion Properties
}
} | 22.407407 | 63 | 0.593388 | [
"MIT"
] | balkar20/SibTrain | net-core/Makc2020.Mods.Auth.Base/Config/IModAuthBaseConfigSettings.cs | 653 | C# |
// UI controller.
// Created on Thu Jul 5 22:00:00 2018
// Author: Prasun Roy (https://github.com/prasunroy)
// GitHub: https://github.com/prasunroy/galaxy-shooter
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class UIController : MonoBehaviour
{
[SerializeField]
private bool _debug = false;
[SerializeField]
private Image _mainMenuImage;
[SerializeField]
private Sprite[] _playerLivesSprites;
[SerializeField]
private Image _playerLivesImage;
[SerializeField]
private Text _playerScoreText;
[SerializeField]
private int _playerScoreTotal;
// Initialize
void Start ()
{
// Debug message
if (_debug)
{
Debug.Log("[INFO] UIController initialized");
}
}
// Display main menu
public void DisplayMainMenu(bool visible = true)
{
_mainMenuImage.enabled = visible;
}
// Update player lives
public void UpdatePlayerLives(int lives)
{
_playerLivesImage.sprite = _playerLivesSprites[lives];
}
// Update player score
public void UpdatePlayerScore(int score)
{
_playerScoreTotal += score;
_playerScoreText.text = "SCORE = " + _playerScoreTotal;
}
// Reset player score
public void ResetPlayerScore(int score = 0)
{
_playerScoreTotal = score;
_playerScoreText.text = "SCORE = " + _playerScoreTotal;
}
}
| 23.887097 | 63 | 0.656989 | [
"MIT"
] | prasunroy/galaxy-shooter | Galaxy_Shooter/Assets/Scripts/UIController.cs | 1,483 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("_01.DecimalToBinary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("_01.DecimalToBinary")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("980a3b61-b219-4932-904d-6c07e636d7c1")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.135135 | 84 | 0.746279 | [
"MIT"
] | ivailo-kolarov/TelerikAcademy | 04.NumeralSystems/01.DecimalToBinary/Properties/AssemblyInfo.cs | 1,414 | C# |
/*
* Copyright(c) 2021 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
namespace Tizen.NUI
{
internal static partial class Interop
{
internal static partial class PageTurnView
{
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_PageTurnView_SWIGUpcast")]
public static extern global::System.IntPtr Upcast(global::System.IntPtr jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_PageTurnView_Property_VIEW_PAGE_SIZE_get")]
public static extern int ViewPageSizeGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_PageTurnView_Property_CURRENT_PAGE_ID_get")]
public static extern int CurrentPageIdGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_PageTurnView_Property_SPINE_SHADOW_get")]
public static extern int SpineShadowGet();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_new_PageTurnView_Property")]
public static extern global::System.IntPtr NewPageTurnViewProperty();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_delete_PageTurnView_Property")]
public static extern void DeletePageTurnViewProperty(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_new_PageTurnView__SWIG_0")]
public static extern global::System.IntPtr NewPageTurnView();
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_new_PageTurnView__SWIG_1")]
public static extern global::System.IntPtr NewPageTurnView(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_PageTurnView_Assign")]
public static extern global::System.IntPtr Assign(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_delete_PageTurnView")]
public static extern void DeletePageTurnView(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_PageTurnView_DownCast")]
public static extern global::System.IntPtr DownCast(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_PageTurnView_PageTurnStartedSignal")]
public static extern global::System.IntPtr PageTurnStartedSignal(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_PageTurnView_PageTurnFinishedSignal")]
public static extern global::System.IntPtr PageTurnFinishedSignal(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_PageTurnView_PagePanStartedSignal")]
public static extern global::System.IntPtr PagePanStartedSignal(global::System.Runtime.InteropServices.HandleRef jarg1);
[global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_PageTurnView_PagePanFinishedSignal")]
public static extern global::System.IntPtr PagePanFinishedSignal(global::System.Runtime.InteropServices.HandleRef jarg1);
}
}
}
| 63.309859 | 174 | 0.758621 | [
"Apache-2.0",
"MIT"
] | AchoWang/TizenFX | src/Tizen.NUI/src/internal/Interop/Interop.PageTurnView.cs | 4,497 | C# |
using System.Collections.Generic;
using System.Threading.Tasks;
using Unearth.Core;
using Unearth.Dns;
namespace Unearth.Smtp
{
public class SmtpLocator : ServiceLocator<SmtpService>
{
public Task<SmtpService> Locate()
{
return Locate( null );
}
public override Task<SmtpService> Locate(string serviceName)
{
string longName;
if (string.IsNullOrWhiteSpace(serviceName))
longName = serviceName = "_smtp";
else
longName = $"{serviceName.ToLowerInvariant()}._smtp";
// get name of service to resolve
ServiceDnsName name = new ServiceDnsName
{
Domain = ServiceDomain,
ServiceName = serviceName,
Protocol = "smtp",
DnsName = string.IsNullOrEmpty(ServiceDomain)
? serviceName.ToLowerInvariant()
: $"{longName}._tcp.{ServiceDomain}"
};
return Locate(name, _ => ServiceLookup.SrvTxt(name, SmtpServiceFactory));
}
private SmtpService SmtpServiceFactory(ServiceDnsName name, IEnumerable<DnsEntry> dnsEntries)
{
ApplyDnsRandomizer(ref dnsEntries);
return new SmtpService(dnsEntries)
{
Name = name.ServiceName,
Protocol = name.Protocol,
Decryptor = { ServiceDomain = name.Domain }
};
}
}
}
| 30.18 | 101 | 0.558648 | [
"MIT"
] | kellybirr/unearth | src/Unearth.Common/Smtp/SmtpLocator.cs | 1,511 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System.Threading.Tasks;
namespace Microsoft.AspNetCore.Mvc.Filters
{
/// <summary>
/// A delegate that asynchronously returns an <see cref="ResultExecutedContext"/> indicating the action result or
/// the next result filter has executed.
/// </summary>
/// <returns>A <see cref="Task"/> that on completion returns an <see cref="ResultExecutedContext"/>.</returns>
public delegate Task<ResultExecutedContext> ResultExecutionDelegate();
}
| 40.4 | 117 | 0.732673 | [
"MIT"
] | 48355746/AspNetCore | src/Mvc/Mvc.Abstractions/src/Filters/ResultExecutionDelegate.cs | 606 | C# |
// ==========================================================================
// Squidex Headless CMS
// ==========================================================================
// Copyright (c) Squidex UG (haftungsbeschraenkt)
// All rights reserved. Licensed under the MIT license.
// ==========================================================================
namespace Squidex.Infrastructure.MongoDb
{
public static class BsonHelper
{
private const string Empty = "§empty";
private const string TypeBson = "§type";
private const string TypeJson = "$type";
private const string DotSource = ".";
private const string DotReplacement = "_§§_";
public static string UnescapeBson(this string value)
{
if (value == Empty)
{
return string.Empty;
}
if (value == TypeBson)
{
return TypeJson;
}
var result = value.ReplaceFirst('§', '$').Replace(DotReplacement, DotSource, StringComparison.Ordinal);
return result;
}
public static string EscapeJson(this string value)
{
if (value.Length == 0)
{
return Empty;
}
if (value == TypeJson)
{
return TypeBson;
}
var result = value.ReplaceFirst('$', '§').Replace(DotSource, DotReplacement, StringComparison.Ordinal);
return result;
}
private static string ReplaceFirst(this string value, char toReplace, char replacement)
{
if (value.Length == 0 || value[0] != toReplace)
{
return value;
}
if (value.Length == 1)
{
return toReplace.ToString();
}
return replacement + value[1..];
}
}
}
| 28.411765 | 115 | 0.449275 | [
"MIT"
] | Appleseed/squidex | backend/src/Squidex.Infrastructure.MongoDb/MongoDb/BsonHelper.cs | 1,940 | C# |
// <auto-generated />
using Gooios.GoodsService.Domains.Aggregates;
using Gooios.GoodsService.Repositories;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage;
using Microsoft.EntityFrameworkCore.Storage.Internal;
using System;
namespace Gooios.GoodsService.Migrations
{
[DbContext(typeof(DatabaseContext))]
[Migration("20180523135326_AddDistributionScopeForGoods")]
partial class AddDistributionScopeForGoods
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("MySql:ValueGenerationStrategy", MySqlValueGenerationStrategy.IdentityColumn)
.HasAnnotation("ProductVersion", "2.0.1-rtm-125");
modelBuilder.Entity("Gooios.GoodsService.Domains.Aggregates.Comment", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("Content")
.IsRequired()
.HasColumnName("content")
.HasMaxLength(80);
b.Property<string>("CreatedBy")
.IsRequired()
.HasColumnName("created_by")
.HasMaxLength(80);
b.Property<DateTime>("CreatedOn")
.HasColumnName("created_on");
b.Property<string>("GoodsId")
.IsRequired()
.HasColumnName("goods_id")
.HasMaxLength(80);
b.Property<string>("OrderId")
.IsRequired()
.HasColumnName("order_id")
.HasMaxLength(80);
b.HasKey("Id");
b.ToTable("comments");
});
modelBuilder.Entity("Gooios.GoodsService.Domains.Aggregates.CommentImage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("CommentId")
.IsRequired()
.HasColumnName("comment_id")
.HasMaxLength(80);
b.Property<string>("ImageId")
.IsRequired()
.HasColumnName("image_id")
.HasMaxLength(80);
b.HasKey("Id");
b.ToTable("comment_images");
});
modelBuilder.Entity("Gooios.GoodsService.Domains.Aggregates.CommentTag", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("CommentId")
.IsRequired()
.HasColumnName("comment_id")
.HasMaxLength(80);
b.Property<string>("GoodsId")
.IsRequired()
.HasColumnName("goods_id")
.HasMaxLength(80);
b.Property<string>("TagId")
.IsRequired()
.HasColumnName("tag_id")
.HasMaxLength(80);
b.Property<string>("UserId")
.IsRequired()
.HasColumnName("user_id")
.HasMaxLength(80);
b.HasKey("Id");
b.ToTable("comment_tags");
});
modelBuilder.Entity("Gooios.GoodsService.Domains.Aggregates.Goods", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("ApplicationId")
.IsRequired()
.HasColumnName("application_id")
.HasMaxLength(80);
b.Property<string>("Area")
.IsRequired()
.HasColumnName("area")
.HasMaxLength(80);
b.Property<string>("Category")
.IsRequired()
.HasColumnName("category")
.HasMaxLength(80);
b.Property<string>("City")
.IsRequired()
.HasColumnName("city")
.HasMaxLength(80);
b.Property<string>("CreatedBy")
.IsRequired()
.HasColumnName("created_by")
.HasMaxLength(80);
b.Property<DateTime>("CreatedOn")
.HasColumnName("created_on");
b.Property<string>("Description")
.HasColumnName("description")
.HasMaxLength(4000);
b.Property<string>("Detail")
.HasColumnName("detail");
b.Property<int>("DistributionScope")
.HasColumnName("distribution_scope")
.HasMaxLength(80);
b.Property<string>("ItemNumber")
.IsRequired()
.HasColumnName("item_number")
.HasMaxLength(80);
b.Property<string>("LastUpdBy")
.IsRequired()
.HasColumnName("updated_by")
.HasMaxLength(80);
b.Property<DateTime?>("LastUpdOn")
.IsRequired()
.HasColumnName("updated_on");
b.Property<double>("Latitude")
.HasColumnName("latitude");
b.Property<double>("Longitude")
.HasColumnName("longitude");
b.Property<decimal>("MarketPrice")
.HasColumnName("market_price");
b.Property<string>("OptionalPropertyJsonObject")
.HasColumnName("optional_property_json_object");
b.Property<string>("Postcode")
.IsRequired()
.HasColumnName("post_code")
.HasMaxLength(80);
b.Property<string>("Province")
.IsRequired()
.HasColumnName("province")
.HasMaxLength(80);
b.Property<int>("Status")
.HasColumnName("status");
b.Property<int>("Stock")
.HasColumnName("stock");
b.Property<string>("StoreId")
.IsRequired()
.HasColumnName("store_id")
.HasMaxLength(80);
b.Property<string>("StreetAddress")
.IsRequired()
.HasColumnName("street_address")
.HasMaxLength(80);
b.Property<string>("SubCategory")
.IsRequired()
.HasColumnName("sub_category")
.HasMaxLength(80);
b.Property<string>("Title")
.IsRequired()
.HasColumnName("title")
.HasMaxLength(200);
b.Property<string>("Unit")
.IsRequired()
.HasColumnName("unit");
b.Property<decimal>("UnitPrice")
.HasColumnName("unit_price");
b.HasKey("Id");
b.ToTable("goods");
});
modelBuilder.Entity("Gooios.GoodsService.Domains.Aggregates.GoodsCategory", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("ApplicationId")
.IsRequired()
.HasColumnName("application_id")
.HasMaxLength(80);
b.Property<string>("Name")
.IsRequired()
.HasColumnName("name")
.HasMaxLength(80);
b.Property<string>("ParentId")
.HasColumnName("parent_id")
.HasMaxLength(80);
b.HasKey("Id");
b.ToTable("goods_categories");
});
modelBuilder.Entity("Gooios.GoodsService.Domains.Aggregates.GoodsImage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<DateTime>("CreatedOn")
.HasColumnName("created_on");
b.Property<string>("GoodsId")
.IsRequired()
.HasColumnName("goods_id")
.HasMaxLength(80);
b.Property<string>("ImageId")
.IsRequired()
.HasColumnName("image_id")
.HasMaxLength(80);
b.HasKey("Id");
b.ToTable("goods_images");
});
modelBuilder.Entity("Gooios.GoodsService.Domains.Aggregates.GrouponCondition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("GoodsId")
.IsRequired()
.HasColumnName("goods_id")
.HasMaxLength(80);
b.Property<int>("MoreThanNumber")
.HasColumnName("more_than_number");
b.Property<decimal>("Price")
.HasColumnName("price");
b.HasKey("Id");
b.ToTable("groupon_conditions");
});
modelBuilder.Entity("Gooios.GoodsService.Domains.Aggregates.OnlineGoods", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("ApplicationId")
.IsRequired()
.HasColumnName("application_id")
.HasMaxLength(80);
b.Property<string>("Area")
.IsRequired()
.HasColumnName("area")
.HasMaxLength(80);
b.Property<string>("Category");
b.Property<string>("City")
.IsRequired()
.HasColumnName("city")
.HasMaxLength(80);
b.Property<string>("CreatedBy")
.IsRequired()
.HasColumnName("created_by")
.HasMaxLength(80);
b.Property<DateTime>("CreatedOn")
.HasColumnName("created_on");
b.Property<string>("Description")
.HasColumnName("description")
.HasMaxLength(4000);
b.Property<string>("Detail")
.HasColumnName("detail");
b.Property<int>("DistributionScope")
.HasColumnName("distribution_scope")
.HasMaxLength(80);
b.Property<string>("ItemNumber")
.IsRequired()
.HasColumnName("item_number")
.HasMaxLength(80);
b.Property<string>("LastUpdBy")
.IsRequired()
.HasColumnName("updated_by")
.HasMaxLength(80);
b.Property<DateTime?>("LastUpdOn")
.IsRequired()
.HasColumnName("updated_on");
b.Property<double>("Latitude")
.HasColumnName("latitude");
b.Property<double>("Longitude")
.HasColumnName("longitude");
b.Property<decimal>("MarketPrice")
.HasColumnName("market_price");
b.Property<string>("OptionalPropertyJsonObject")
.HasColumnName("optional_property_json_object");
b.Property<string>("Postcode")
.IsRequired()
.HasColumnName("post_code")
.HasMaxLength(80);
b.Property<string>("Province")
.IsRequired()
.HasColumnName("province")
.HasMaxLength(80);
b.Property<int>("Status")
.HasColumnName("status");
b.Property<int>("Stock")
.HasColumnName("stock");
b.Property<string>("StoreId")
.IsRequired()
.HasColumnName("store_id")
.HasMaxLength(80);
b.Property<string>("StreetAddress")
.IsRequired()
.HasColumnName("street_address")
.HasMaxLength(80);
b.Property<string>("SubCategory");
b.Property<string>("Title")
.IsRequired()
.HasColumnName("title")
.HasMaxLength(200);
b.Property<string>("Unit")
.IsRequired()
.HasColumnName("unit");
b.Property<decimal>("UnitPrice")
.HasColumnName("unit_price");
b.HasKey("Id");
b.ToTable("online_goods");
});
modelBuilder.Entity("Gooios.GoodsService.Domains.Aggregates.OnlineGoodsImage", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<DateTime>("CreatedOn")
.HasColumnName("created_on");
b.Property<string>("GoodsId")
.IsRequired()
.HasColumnName("goods_id")
.HasMaxLength(80);
b.Property<string>("ImageId")
.IsRequired()
.HasColumnName("image_id")
.HasMaxLength(80);
b.HasKey("Id");
b.ToTable("online_goods_images");
});
modelBuilder.Entity("Gooios.GoodsService.Domains.Aggregates.OnlineGrouponCondition", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("GoodsId")
.IsRequired()
.HasColumnName("goods_id")
.HasMaxLength(80);
b.Property<int>("MoreThanNumber")
.HasColumnName("more_than_number");
b.Property<decimal>("Price")
.HasColumnName("price");
b.HasKey("Id");
b.ToTable("online_groupon_conditions");
});
modelBuilder.Entity("Gooios.GoodsService.Domains.Aggregates.Tag", b =>
{
b.Property<string>("Id")
.ValueGeneratedOnAdd()
.HasColumnName("id");
b.Property<string>("CategoryId")
.IsRequired()
.HasColumnName("category_id")
.HasMaxLength(80);
b.Property<string>("CreatedBy")
.IsRequired()
.HasColumnName("created_by")
.HasMaxLength(80);
b.Property<DateTime>("CreatedOn")
.HasColumnName("created_on");
b.Property<string>("Name")
.IsRequired()
.HasColumnName("name")
.HasMaxLength(80);
b.HasKey("Id");
b.ToTable("tags");
});
#pragma warning restore 612, 618
}
}
}
| 35.418699 | 108 | 0.417824 | [
"Apache-2.0"
] | hccoo/gooios | netcoremicroservices/Gooios.GoodsService/Migrations/20180523135326_AddDistributionScopeForGoods.Designer.cs | 17,428 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("05.HexToBinary")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("05.HexToBinary")]
[assembly: AssemblyCopyright("Copyright © 2013")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("4008905d-7004-4c8b-b83a-dd7b9ddda0ea")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.864865 | 84 | 0.744468 | [
"MIT"
] | niki-funky/Telerik_Academy | Programming/02.Csharp/05. Numeral systems/05.HexToBinary/Properties/AssemblyInfo.cs | 1,404 | C# |
// <copyright>
// Copyright 2013 by the Spark Development Network
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>
//
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data.Entity;
using System.Linq;
using System.Web.UI.WebControls;
using Rock;
using Rock.Attribute;
using Rock.Data;
using Rock.Model;
using Rock.Security;
using Rock.Web.Cache;
using Rock.Web.UI;
using Rock.Web.UI.Controls;
namespace RockWeb.Blocks.Finance
{
/// <summary>
/// Block for viewing list of financial gateways
/// </summary>
[DisplayName( "Gateway List" )]
[Category( "Finance" )]
[Description( "Block for viewing list of financial gateways." )]
[LinkedPage( "Detail Page" )]
public partial class GatewayList : RockBlock
{
#region Control Methods
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.Init" /> event.
/// </summary>
/// <param name="e">An <see cref="T:System.EventArgs" /> object that contains the event data.</param>
protected override void OnInit( EventArgs e )
{
base.OnInit( e );
bool canEdit = IsUserAuthorized( Authorization.EDIT );
rGridGateway.DataKeyNames = new string[] { "Id" };
rGridGateway.Actions.ShowAdd = canEdit;
rGridGateway.Actions.AddClick += rGridGateway_Add;
rGridGateway.GridRebind += rGridGateways_GridRebind;
rGridGateway.IsDeleteEnabled = canEdit;
}
/// <summary>
/// Raises the <see cref="E:System.Web.UI.Control.Load" /> event.
/// </summary>
/// <param name="e">The <see cref="T:System.EventArgs" /> object that contains the event data.</param>
protected override void OnLoad( EventArgs e )
{
if ( !Page.IsPostBack )
{
BindGrid();
}
base.OnLoad( e );
}
#endregion
#region Events
/// <summary>
/// Handles the Add event of the rGridGateway control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
protected void rGridGateway_Add( object sender, EventArgs e )
{
var parms = new Dictionary<string, string>();
parms.Add( "gatewayId", "0" );
NavigateToLinkedPage( "DetailPage", parms );
}
/// <summary>
/// Handles the Edit event of the rGridGateway control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
protected void rGridGateway_Edit( object sender, RowEventArgs e )
{
var parms = new Dictionary<string, string>();
parms.Add( "gatewayId", e.RowKeyValue.ToString() );
NavigateToLinkedPage( "DetailPage", parms );
}
/// <summary>
/// Handles the Delete event of the rGridGateway control.
/// </summary>
/// <param name="sender">The source of the event.</param>
/// <param name="e">The <see cref="RowEventArgs"/> instance containing the event data.</param>
protected void rGridGateway_Delete( object sender, RowEventArgs e )
{
var rockContext = new RockContext();
var gatewayService = new FinancialGatewayService( rockContext );
var gateway = gatewayService.Get( e.RowKeyId );
if ( gateway != null )
{
string errorMessage;
if ( !gatewayService.CanDelete( gateway, out errorMessage ) )
{
mdGridWarning.Show( errorMessage, ModalAlertType.Information );
return;
}
gatewayService.Delete( gateway );
rockContext.SaveChanges();
}
BindGrid();
}
/// <summary>
/// Handles the GridRebind event of the rGridGateway control.
/// </summary>
/// <param name="sendder">The source of the event.</param>
/// <param name="e">The <see cref="EventArgs"/> instance containing the event data.</param>
protected void rGridGateways_GridRebind( object sender, EventArgs e )
{
BindGrid();
}
#endregion
#region Internal Methods
/// <summary>
/// Binds the Gateway list grid.
/// </summary>
private void BindGrid()
{
using ( var rockContext = new RockContext() )
{
var qry = new FinancialGatewayService( rockContext )
.Queryable( "EntityType" ).AsNoTracking();
SortProperty sortProperty = rGridGateway.SortProperty;
if ( sortProperty != null )
{
qry = qry.Sort( sortProperty );
}
else
{
qry = qry.OrderBy( g => g.Name );
}
rGridGateway.DataSource = qry.ToList();
rGridGateway.DataBind();
}
}
protected string GetComponentName( object entityTypeObject )
{
var entityType = entityTypeObject as EntityType;
if ( entityType != null )
{
string name = Rock.Financial.GatewayContainer.GetComponentName( entityType.Name );
if ( !string.IsNullOrWhiteSpace(name))
{
return name.SplitCase();
}
}
return string.Empty;
}
#endregion
}
} | 33.850267 | 110 | 0.569036 | [
"Apache-2.0",
"Unlicense"
] | ThursdayChurch/rockweb.thursdaychurch.org | Blocks/Finance/GatewayList.ascx.cs | 6,332 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Client Application.UnitTests")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Client Application.UnitTests")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("313f5e9d-f884-4e80-b949-aa9ff5b6ce95")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.621622 | 84 | 0.748076 | [
"MIT"
] | AdamHupa/Unified-Work-Solution-.net | Client Application.UnitTests/Properties/AssemblyInfo.cs | 1,432 | C# |
using Abp.Authorization;
using Abp.Authorization.Users;
using Abp.MultiTenancy;
using Abp.Runtime.Security;
using Abp.UI;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using System;
using System.Collections.Generic;
using System.IdentityModel.Tokens.Jwt;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using WebShop.Authentication.External;
using WebShop.Authentication.JwtBearer;
using WebShop.Authorization;
using WebShop.Authorization.Users;
using WebShop.Models.TokenAuth;
using WebShop.MultiTenancy;
namespace WebShop.Controllers
{
[Route("api/[controller]/[action]")]
public class TokenAuthController : WebShopControllerBase
{
private readonly LogInManager _logInManager;
private readonly ITenantCache _tenantCache;
private readonly AbpLoginResultTypeHelper _abpLoginResultTypeHelper;
private readonly TokenAuthConfiguration _configuration;
private readonly IExternalAuthConfiguration _externalAuthConfiguration;
private readonly IExternalAuthManager _externalAuthManager;
private readonly UserRegistrationManager _userRegistrationManager;
public TokenAuthController(
LogInManager logInManager,
ITenantCache tenantCache,
AbpLoginResultTypeHelper abpLoginResultTypeHelper,
TokenAuthConfiguration configuration,
IExternalAuthConfiguration externalAuthConfiguration,
IExternalAuthManager externalAuthManager,
UserRegistrationManager userRegistrationManager)
{
_logInManager = logInManager;
_tenantCache = tenantCache;
_abpLoginResultTypeHelper = abpLoginResultTypeHelper;
_configuration = configuration;
_externalAuthConfiguration = externalAuthConfiguration;
_externalAuthManager = externalAuthManager;
_userRegistrationManager = userRegistrationManager;
}
[HttpPost]
public async Task<AuthenticateResultModel> Authenticate([FromBody] AuthenticateModel model)
{
AbpLoginResult<Tenant, User> loginResult = await GetLoginResultAsync(
model.UserNameOrEmailAddress,
model.Password,
GetTenancyNameOrNull()
);
string accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));
return new AuthenticateResultModel
{
AccessToken = accessToken,
EncryptedAccessToken = GetEncryptedAccessToken(accessToken),
ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds,
UserId = loginResult.User.Id
};
}
[HttpGet]
public List<ExternalLoginProviderInfoModel> GetExternalAuthenticationProviders()
{
return ObjectMapper.Map<List<ExternalLoginProviderInfoModel>>(_externalAuthConfiguration.Providers);
}
[HttpPost]
public async Task<ExternalAuthenticateResultModel> ExternalAuthenticate([FromBody] ExternalAuthenticateModel model)
{
ExternalAuthUserInfo externalUser = await GetExternalUserInfo(model);
AbpLoginResult<Tenant, User> loginResult = await _logInManager.LoginAsync(new UserLoginInfo(model.AuthProvider, model.ProviderKey, model.AuthProvider), GetTenancyNameOrNull());
switch (loginResult.Result)
{
case AbpLoginResultType.Success:
{
string accessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity));
return new ExternalAuthenticateResultModel
{
AccessToken = accessToken,
EncryptedAccessToken = GetEncryptedAccessToken(accessToken),
ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds
};
}
case AbpLoginResultType.UnknownExternalLogin:
{
User newUser = await RegisterExternalUserAsync(externalUser);
if (!newUser.IsActive)
{
return new ExternalAuthenticateResultModel
{
WaitingForActivation = true
};
}
// Try to login again with newly registered user!
loginResult = await _logInManager.LoginAsync(new UserLoginInfo(model.AuthProvider, model.ProviderKey, model.AuthProvider), GetTenancyNameOrNull());
if (loginResult.Result != AbpLoginResultType.Success)
{
throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(
loginResult.Result,
model.ProviderKey,
GetTenancyNameOrNull()
);
}
return new ExternalAuthenticateResultModel
{
AccessToken = CreateAccessToken(CreateJwtClaims(loginResult.Identity)),
ExpireInSeconds = (int)_configuration.Expiration.TotalSeconds
};
}
default:
{
throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(
loginResult.Result,
model.ProviderKey,
GetTenancyNameOrNull()
);
}
}
}
private async Task<User> RegisterExternalUserAsync(ExternalAuthUserInfo externalUser)
{
User user = await _userRegistrationManager.RegisterAsync(
externalUser.Name,
externalUser.Surname,
externalUser.EmailAddress,
externalUser.EmailAddress,
Authorization.Users.User.CreateRandomPassword(),
true
);
user.Logins = new List<UserLogin>
{
new UserLogin
{
LoginProvider = externalUser.Provider,
ProviderKey = externalUser.ProviderKey,
TenantId = user.TenantId
}
};
await CurrentUnitOfWork.SaveChangesAsync();
return user;
}
private async Task<ExternalAuthUserInfo> GetExternalUserInfo(ExternalAuthenticateModel model)
{
ExternalAuthUserInfo userInfo = await _externalAuthManager.GetUserInfo(model.AuthProvider, model.ProviderAccessCode);
if (userInfo.ProviderKey != model.ProviderKey)
{
throw new UserFriendlyException(L("CouldNotValidateExternalUser"));
}
return userInfo;
}
private string GetTenancyNameOrNull()
{
if (!AbpSession.TenantId.HasValue)
{
return null;
}
return _tenantCache.GetOrNull(AbpSession.TenantId.Value)?.TenancyName;
}
private async Task<AbpLoginResult<Tenant, User>> GetLoginResultAsync(string usernameOrEmailAddress, string password, string tenancyName)
{
AbpLoginResult<Tenant, User> loginResult = await _logInManager.LoginAsync(usernameOrEmailAddress, password, tenancyName);
switch (loginResult.Result)
{
case AbpLoginResultType.Success:
return loginResult;
default:
throw _abpLoginResultTypeHelper.CreateExceptionForFailedLoginAttempt(loginResult.Result, usernameOrEmailAddress, tenancyName);
}
}
private string CreateAccessToken(IEnumerable<Claim> claims, TimeSpan? expiration = null)
{
DateTime now = DateTime.UtcNow;
JwtSecurityToken jwtSecurityToken = new JwtSecurityToken(
issuer: _configuration.Issuer,
audience: _configuration.Audience,
claims: claims,
notBefore: now,
expires: now.Add(expiration ?? _configuration.Expiration),
signingCredentials: _configuration.SigningCredentials
);
return new JwtSecurityTokenHandler().WriteToken(jwtSecurityToken);
}
private static List<Claim> CreateJwtClaims(ClaimsIdentity identity)
{
List<Claim> claims = identity.Claims.ToList();
Claim nameIdClaim = claims.First(c => c.Type == ClaimTypes.NameIdentifier);
// Specifically add the jti (random nonce), iat (issued timestamp), and sub (subject/user) claims.
claims.AddRange(new[]
{
new Claim(JwtRegisteredClaimNames.Sub, nameIdClaim.Value),
new Claim(JwtRegisteredClaimNames.Jti, Guid.NewGuid().ToString()),
new Claim(JwtRegisteredClaimNames.Iat, DateTimeOffset.Now.ToUnixTimeSeconds().ToString(), ClaimValueTypes.Integer64)
});
return claims;
}
private string GetEncryptedAccessToken(string accessToken)
{
return SimpleStringCipher.Instance.Encrypt(accessToken, AppConsts.DefaultPassPhrase);
}
}
}
| 40.92735 | 188 | 0.602903 | [
"MIT"
] | dangminhbk/auction | aspnet-core/src/WebShop.Web.Core/Controllers/TokenAuthController.cs | 9,579 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using Microsoft.Win32.SafeHandles;
using System.Diagnostics;
using System.IO;
using System.Runtime.InteropServices;
internal partial class Interop
{
internal partial class Kernel32
{
[DllImport(Libraries.Kernel32, EntryPoint = "CreateFile2", SetLastError = true, CharSet = CharSet.Unicode)]
private static extern SafeFileHandle CreateFile2Private(
string lpFileName,
int dwDesiredAccess,
FileShare dwShareMode,
FileMode dwCreationDisposition,
ref Kernel32.CREATEFILE2_EXTENDED_PARAMETERS pCreateExParams);
internal static SafeFileHandle CreateFile2(
string lpFileName,
int dwDesiredAccess,
FileShare dwShareMode,
FileMode dwCreationDisposition,
ref Kernel32.CREATEFILE2_EXTENDED_PARAMETERS pCreateExParams)
{
lpFileName = PathInternal.EnsureExtendedPrefixIfNeeded(lpFileName)!; // TODO-NULLABLE: Remove ! when nullable attributes are respected
return CreateFile2Private(lpFileName, dwDesiredAccess, dwShareMode, dwCreationDisposition, ref pCreateExParams);
}
}
}
| 40.147059 | 146 | 0.713553 | [
"MIT"
] | 85331479/coreclr | src/System.Private.CoreLib/shared/Interop/Windows/Kernel32/Interop.CreateFile2.cs | 1,365 | C# |
using FluentMigrator.Builders.Create.Table;
using Nop.Core;
namespace Nop.Data.Mapping.Builders
{
/// <summary>
/// Represents base entity builder
/// </summary>
/// <typeparam name="TEntity">Entity type</typeparam>
/// <remarks>
/// "Entity type <see cref="TEntity"/>" is needed to determine the right entity builder for a specific entity type
/// </remarks>
public abstract class NopEntityBuilder<TEntity> : IEntityBuilder where TEntity : BaseEntity
{
/// <summary>
/// Apply entity configuration
/// </summary>
/// <param name="table">Create table expression builder</param>
public abstract void MapEntity(CreateTableExpressionBuilder table);
}
} | 34.809524 | 118 | 0.662107 | [
"MIT"
] | ASP-WAF/FireWall | Samples/NopeCommerce/Libraries/Nop.Data/Mapping/Builders/NopEntityBuilder.cs | 733 | C# |
using Abp.Authorization.Roles;
using Abp.Domain.Repositories;
using Abp.Domain.Uow;
using NPS.Authorization.Users;
namespace NPS.Authorization.Roles
{
public class RoleStore : AbpRoleStore<Role, User>
{
public RoleStore(
IUnitOfWorkManager unitOfWorkManager,
IRepository<Role> roleRepository,
IRepository<RolePermissionSetting, long> rolePermissionSettingRepository)
: base(
unitOfWorkManager,
roleRepository,
rolePermissionSettingRepository)
{
}
}
}
| 26.545455 | 85 | 0.645548 | [
"MIT"
] | leonardo-buta/automated-nps | aspnet-core/src/NPS.Core/Authorization/Roles/RoleStore.cs | 584 | C# |
#pragma warning disable 108 // new keyword hiding
#pragma warning disable 114 // new keyword hiding
namespace Windows.ApplicationModel.Activation
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
[global::Uno.NotImplemented]
#endif
public partial interface IPickerReturnedActivatedEventArgs : global::Windows.ApplicationModel.Activation.IActivatedEventArgs
{
#if __ANDROID__ || __IOS__ || NET461 || __WASM__ || __MACOS__
string PickerOperationId
{
get;
}
#endif
// Forced skipping of method Windows.ApplicationModel.Activation.IPickerReturnedActivatedEventArgs.PickerOperationId.get
}
}
| 32.789474 | 126 | 0.780096 | [
"Apache-2.0"
] | 06needhamt/uno | src/Uno.UWP/Generated/3.0.0.0/Windows.ApplicationModel.Activation/IPickerReturnedActivatedEventArgs.cs | 623 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Reactive;
using System.Reactive.Concurrency;
using System.Reactive.Disposables;
using System.Reactive.Linq;
using System.Reactive.Subjects;
using System.Runtime.CompilerServices;
using System.Threading;
using Splat;
namespace ReactiveUI
{
/// <summary>
/// A reactive object is a interface for ViewModels which will expose
/// logging, and notify when properties are either changing or changed.
/// The primary use of this interface is to allow external classes such as
/// the ObservableAsPropertyHelper to trigger these events inside the ViewModel.
/// </summary>
public interface IReactiveObject : INotifyPropertyChanged, INotifyPropertyChanging, IEnableLogger
{
/// <summary>
/// Raise a property is changing event.
/// </summary>
/// <param name="args">The arguments with details about the property that is changing.</param>
void RaisePropertyChanging(PropertyChangingEventArgs args);
/// <summary>
/// Raise a property has changed event.
/// </summary>
/// <param name="args">The arguments with details about the property that has changed.</param>
void RaisePropertyChanged(PropertyChangedEventArgs args);
}
}
| 38.170732 | 102 | 0.725879 | [
"MIT"
] | Nilox/ReactiveUI | src/ReactiveUI/ReactiveObject/IReactiveObject.cs | 1,567 | C# |
#if UNITY_EDITOR
using Unity.Mathematics;
using UnityEditor;
using UnityEngine;
namespace AeternumGames.ShapeEditor
{
public class ScaleTool : BoxSelectTool
{
private bool isSingleUseDone = false;
private float2 initialGridPosition;
private float initialDistance;
private ScaleWidget scaleWidget = new ScaleWidget();
public override void OnActivate()
{
base.OnActivate();
if (isSingleUse)
{
initialGridPosition = editor.ScreenPointToGrid(editor.selectedSegmentsAveragePosition);
initialDistance = math.distance(initialGridPosition, editor.mouseGridPosition);
ToolOnBeginScaling();
}
else
{
editor.AddWidget(scaleWidget);
scaleWidget.onBeginScaling = () => ToolOnBeginScaling();
scaleWidget.onMouseDrag = (pivot, scale) => ToolOnMouseDrag(pivot, scale);
}
}
public override void OnRender()
{
base.OnRender();
if (isSingleUse)
{
GLUtilities.DrawGui(() =>
{
GL.Color(Color.gray);
GLUtilities.DrawDottedLine(1.0f, editor.mousePosition, editor.GridPointToScreen(initialGridPosition));
});
editor.SetMouseCursor(MouseCursor.ScaleArrow);
}
else
{
if (editor.selectedSegmentsCount > 0)
{
scaleWidget.position = editor.selectedSegmentsAveragePosition;
scaleWidget.visible = true;
}
else
{
scaleWidget.visible = false;
}
}
}
public override void OnMouseMove(float2 screenDelta, float2 gridDelta)
{
if (isSingleUse && !isSingleUseDone)
{
float2 scale = math.distance(initialGridPosition, editor.mouseGridPosition);
if (initialDistance == 0f)
{
scale = new float2(1.0f, 1.0f);
}
else
{
scale /= initialDistance;
}
ToolOnMouseDrag(initialGridPosition, scale);
}
}
public override void OnMouseDown(int button)
{
if (isSingleUse)
{
if (button == 0)
{
isSingleUseDone = true;
}
}
}
public override void OnMouseDrag(int button, float2 screenDelta, float2 gridDelta)
{
if (isSingleUse)
{
if (button == 0)
{
// we do not want the marquee in this mode.
return;
}
}
base.OnMouseDrag(button, screenDelta, gridDelta);
}
public override void OnGlobalMouseUp(int button)
{
if (isSingleUse)
{
if (button == 0)
{
editor.SwitchTool(parent);
}
}
else
{
base.OnGlobalMouseUp(button);
}
}
public override bool IsBusy()
{
if (isSingleUse)
{
return !isSingleUseDone;
}
return false;
}
private void ToolOnBeginScaling()
{
editor.RegisterUndo("Scale Selection");
// store the initial position of all selected segments.
foreach (var segment in editor.ForEachSelectedObject())
segment.gpVector1 = segment.position;
}
private void ToolOnMouseDrag(float2 pivot, float2 scale)
{
// optionally snap the scale to grid increments.
if (editor.isSnapping)
scale = scale.Snap(editor.gridSnap);
// scale the selected segments using their initial position.
foreach (var segment in editor.ForEachSelectedObject())
segment.position = MathEx.ScaleAroundPivot(segment.gpVector1, pivot, scale);
}
}
}
#endif | 28.651316 | 122 | 0.4907 | [
"MIT"
] | Henry00IS/ShapeEditor | Scripts/ShapeEditor/Tools/ScaleTool.cs | 4,357 | C# |
// *****************************************************************************
//
// © Component Factory Pty Ltd, 2006 - 2016. All rights reserved.
// The software and associated documentation supplied hereunder are the
// proprietary information of Component Factory Pty Ltd, PO Box 1504,
// Glen Waverley, Vic 3150, Australia and are supplied subject to licence terms.
//
// Version 5.460.5000.0 www.ComponentFactory.com
// *****************************************************************************
using System;
using System.Text;
using System.Drawing;
using System.Windows.Forms;
using System.ComponentModel;
using System.Collections.Generic;
using System.Diagnostics;
using ComponentFactory.Krypton.Toolkit;
using ComponentFactory.Krypton.Navigator;
namespace OrientationPlusAlignment
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 31.567568 | 81 | 0.599315 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy/Krypton-NET-5.460 | Source/Demos/Non-NuGet/Krypton Navigator Examples/Orientation + Alignment/Program.cs | 1,171 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the MIT license. See License.txt in the project root for license information.
namespace System.Data.Entity.Core
{
using System.Data.Entity.Resources;
using System.Runtime.Serialization;
/// <summary>
/// metadata exception class
/// </summary>
[Serializable]
public sealed class MetadataException : EntityException
{
private const int HResultMetadata = -2146232007;
#region Constructors
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Data.Entity.Core.MetadataException" /> class with a default message.
/// </summary>
public MetadataException() // required ctor
: base(Strings.Metadata_General_Error)
{
HResult = HResultMetadata;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Data.Entity.Core.MetadataException" /> class with the specified message.
/// </summary>
/// <param name="message">The exception message.</param>
public MetadataException(string message) // required ctor
: base(message)
{
HResult = HResultMetadata;
}
/// <summary>
/// Initializes a new instance of the <see cref="T:System.Data.Entity.Core.MetadataException" /> class with the specified message and inner exception.
/// </summary>
/// <param name="message">The exception message.</param>
/// <param name="innerException">
/// The exception that is the cause of this <see cref="T:System.Data.Entity.Core.MetadataException" />.
/// </param>
public MetadataException(string message, Exception innerException) // required ctor
: base(message, innerException)
{
HResult = HResultMetadata;
}
// <summary>
// constructor for deserialization
// </summary>
private MetadataException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
#endregion
}
}
| 35.147541 | 158 | 0.617537 | [
"MIT"
] | dotnet/ef6tools | src/EntityFramework/Core/MetadataException.cs | 2,144 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Zone Settings
* A Zone setting changes how the Zone works in relation to caching, security, or other features of JDC StarShield
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
namespace JDCloudSDK.Starshield.Apis
{
/// <summary>
/// 星盾将把具有相同查询字符串的文件视为缓存中的同一个文件,而不管查询字符串的顺序如何。这只限于企业级域。
/// ///
/// </summary>
public class ChangeEnableQueryStringSortSettingResponse : JdcloudResponse<ChangeEnableQueryStringSortSettingResult>
{
}
} | 29.785714 | 119 | 0.729816 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Starshield/Apis/ChangeEnableQueryStringSortSettingResponse.cs | 1,353 | C# |
using System.ComponentModel;
using Template10.ViewModels;
using Windows.UI.Xaml.Controls;
namespace Template10.Views
{
public sealed partial class RandomAccessPage : Page
{
public RandomAccessPage()
{
this.InitializeComponent();
}
}
}
| 19 | 55 | 0.663158 | [
"MIT"
] | HydAu/WebDevCamp | Presentation/07. XAML Performance/Demos/Performance/Performance/Views/RandomAccessPage.xaml.cs | 287 | C# |
using UnityEngine;
using Zenject;
using ZEscape.VFX;
public class EffectInstaller : ScriptableObjectInstaller<EffectInstaller>
{
[SerializeField] private BulletImpactEffect _bulletImpactEffect;
[SerializeField] private BonusEffect _bonusEffect;
public override void InstallBindings()
{
Container.BindFactory<Vector3, BulletImpactEffect, BulletImpactEffect.Factory>().FromMonoPoolableMemoryPool(
x => x.WithInitialSize(20).FromComponentInNewPrefab(_bulletImpactEffect).UnderTransformGroup("BulletImpactEffect"));
Container.BindFactory<Vector3, BonusEffect, BonusEffect.Factory>().FromMonoPoolableMemoryPool(
x => x.WithInitialSize(20).FromComponentInNewPrefab(_bonusEffect).UnderTransformGroup("BonusEffect"));
}
}
| 42.944444 | 127 | 0.783959 | [
"Apache-2.0"
] | AndrewKharkow/ZEscape | Assets/ZEscape/SceneContext/EffectInstaller.cs | 773 | C# |
// *** WARNING: this file was generated by the Pulumi SDK Generator. ***
// *** Do not edit by hand unless you're certain you know what you are doing! ***
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Threading.Tasks;
using Pulumi.Serialization;
namespace Pulumi.AzureNextGen.BatchAI.Latest.Inputs
{
/// <summary>
/// An environment variable definition.
/// </summary>
public sealed class EnvironmentVariableArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The name of the environment variable.
/// </summary>
[Input("name", required: true)]
public Input<string> Name { get; set; } = null!;
/// <summary>
/// The value of the environment variable.
/// </summary>
[Input("value", required: true)]
public Input<string> Value { get; set; } = null!;
public EnvironmentVariableArgs()
{
}
}
}
| 27.685714 | 81 | 0.619195 | [
"Apache-2.0"
] | pulumi/pulumi-azure-nextgen | sdk/dotnet/BatchAI/Latest/Inputs/EnvironmentVariableArgs.cs | 969 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Linq;
using System.Threading.Tasks;
namespace NeoWeb.Models
{
public class ICO2
{
[Key]
public string NeoAddress { get; set; }
[Required]
public decimal GiveBackCNY { get; set; }
[NotMapped]
public Choose Choose { get; set; }
[MinLength(2)]
[MaxLength(8)]
public string Name { get; set; }
[MinLength(15)]
[MaxLength(19)]
public string BankAccount { get; set; }
[MinLength(5)]
[MaxLength(30)]
public string BankName { get; set; }
public string GivebackNeoAddress { get; set; }
[EmailAddress]
public string Email { get; set; }
public DateTime? CommitTime { get; set; }
}
}
| 22.02439 | 54 | 0.603544 | [
"MPL-2.0"
] | Woodehh/neo.org | NeoWeb/Models/ICO2Models.cs | 905 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.42000
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace Stride.Core.Assets.Editor.Resources.Strings {
using System;
/// <summary>
/// A strongly-typed resource class, for looking up localized strings, etc.
/// </summary>
// This class was auto-generated by the StronglyTypedResourceBuilder
// class via a tool like ResGen or Visual Studio.
// To add or remove a member, edit your .ResX file then rerun ResGen
// with the /str option, or rebuild your VS project.
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
public class KeyGestures {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal KeyGestures() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Stride.Core.Assets.Editor.Resources.Strings.KeyGestures", typeof(KeyGestures).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Ctrl+Enter.
/// </summary>
public static string EditAsset {
get {
return ResourceManager.GetString("EditAsset", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ctrl+A.
/// </summary>
public static string ImportAddFiles {
get {
return ResourceManager.GetString("ImportAddFiles", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ctrl+N.
/// </summary>
public static string ImportAllAsNew {
get {
return ResourceManager.GetString("ImportAllAsNew", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ctrl+M.
/// </summary>
public static string ImportAutoMerge {
get {
return ResourceManager.GetString("ImportAutoMerge", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Alt+F.
/// </summary>
public static string ImportFinish {
get {
return ResourceManager.GetString("ImportFinish", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Alt+N.
/// </summary>
public static string ImportNextStep {
get {
return ResourceManager.GetString("ImportNextStep", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Alt+P.
/// </summary>
public static string ImportPreviousStep {
get {
return ResourceManager.GetString("ImportPreviousStep", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ctrl+R.
/// </summary>
public static string UpdateAllAssetsWithModifiedSource {
get {
return ResourceManager.GetString("UpdateAllAssetsWithModifiedSource", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Ctrl+Shift+R.
/// </summary>
public static string UpdateSelectedAssetsFromSource {
get {
return ResourceManager.GetString("UpdateSelectedAssetsFromSource", resourceCulture);
}
}
}
}
| 37.889655 | 202 | 0.568074 | [
"MIT"
] | Aggror/Stride | sources/editor/Stride.Core.Assets.Editor/Resources/Strings/KeyGestures.Designer.cs | 5,496 | C# |
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved.
// Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information.
using System.Collections.Generic;
using System.Threading.Tasks;
using Dbosoft.IdentityServer.Extensions;
using Dbosoft.IdentityServer.Models.Messages;
namespace Dbosoft.IdentityServer.Stores.Default
{
// internal just for testing
internal class QueryStringAuthorizationParametersMessageStore : IAuthorizationParametersMessageStore
{
public Task<string> WriteAsync(Message<IDictionary<string, string[]>> message)
{
var queryString = message.Data.FromFullDictionary().ToQueryString();
return Task.FromResult(queryString);
}
public Task<Message<IDictionary<string, string[]>>> ReadAsync(string id)
{
var values = id.ReadQueryStringAsNameValueCollection();
var msg = new Message<IDictionary<string, string[]>>(values.ToFullDictionary());
return Task.FromResult(msg);
}
public Task DeleteAsync(string id)
{
return Task.CompletedTask;
}
}
}
| 34.588235 | 107 | 0.693027 | [
"Apache-2.0"
] | dbosoft/IdentityServer | src/IdentityServer/Stores/Default/QueryStringAuthorizationParametersMessageStore.cs | 1,176 | C# |
using FluentAssertions;
using JWT.Tests.Common;
using JWT.Tests.NETFramework.Serializers;
using System.Collections.Generic;
using Xunit;
namespace JWT.Tests.NETFramework
{
public class EncodeTests
{
[Fact]
public void Should_Encode_Type_With_WebScript_Serializer()
{
JsonWebToken.JsonSerializer = new WebScriptJsonSerializer();
var actual = JsonWebToken.Encode(TestData.Customer, "ABC", JwtHashAlgorithm.HS256);
actual.Should().Be(TestData.Token);
}
[Fact]
public void Should_Encode_Type_With_WebScript_Serializer_And_Extra_Headers()
{
JsonWebToken.JsonSerializer = new WebScriptJsonSerializer();
var extraheaders = new Dictionary<string, object> { { "foo", "bar" } };
var actual = JsonWebToken.Encode(extraheaders, TestData.Customer, "ABC", JwtHashAlgorithm.HS256);
actual.Should().Be(TestData.ExtraHeadersToken);
}
[Fact]
public void Should_Encode_Type_With_ServiceStack_Serializer()
{
JsonWebToken.JsonSerializer = new ServiceStackJsonSerializer();
var actual = JsonWebToken.Encode(TestData.Customer, "ABC", JwtHashAlgorithm.HS256);
actual.Should().Be(TestData.Token);
}
[Fact]
public void Should_Encode_Type_With_ServiceStack_Serializer_And_Extra_Headers()
{
JsonWebToken.JsonSerializer = new ServiceStackJsonSerializer();
var extraheaders = new Dictionary<string, object> { { "foo", "bar" } };
var actual = JsonWebToken.Encode(extraheaders, TestData.Customer, "ABC", JwtHashAlgorithm.HS256);
actual.Should().Be(TestData.ExtraHeadersToken);
}
}
}
| 32.236364 | 109 | 0.659898 | [
"CC0-1.0"
] | nbarbettini/jwt | tests/JWT.Tests.NETFramework/EncodeTests.cs | 1,775 | C# |
//
// The MIT License(MIT)
//
// Copyright(c) 2014 Demonsaw LLC
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
// SOFTWARE.
namespace DemonSaw.Controller
{
using DemonSaw.Wpf.TreeList;
using System.Collections.Generic;
using System.Linq;
using System.Windows.Controls;
public class TreeController<T> : DemonController where T : ITreeModel
{
#region Properties
public TreeList View { get; set; }
public bool Selected
{
get { return SelectedNode != null; }
}
public int SelectedIndex
{
get { return View.SelectedIndex; }
}
public TreeNode SelectedNode
{
get { return View.SelectedNode; }
}
public List<TreeNode> SelectedNodes
{
get { return View.SelectedNodes.Cast<TreeNode>().ToList(); }
}
public T SelectedItem
{
get { return (SelectedNode != null) ? (T) SelectedNode.Tag : default(T); }
}
public List<T> SelectedItems
{
get
{
List<T> items = new List<T>();
foreach (TreeNode node in SelectedNodes)
items.Add((T) node.Tag);
return items;
}
}
#endregion
#region Constructors
public TreeController(TreeList view)
{
View = view;
}
public TreeController(TreeList view, TextBlock title) : base(title)
{
View = view;
}
#endregion
#region Interface
public override void Clear()
{
base.Clear();
Update();
}
#endregion
#region Utility
public void Add(List<T> items)
{
foreach (T item in items)
Add(item);
}
public virtual void Add(T item) { }
public bool Remove()
{
return Remove(SelectedItems);
}
public bool Remove(List<T> items)
{
bool removed = true;
foreach (T item in items)
removed &= Remove(item);
return removed;
}
public virtual bool Remove(T item)
{
return true;
}
public virtual void Select()
{
Select(SelectedItem);
}
public virtual void Select(T item)
{
if (item != null)
{
ITreeModel model = (ITreeModel) item;
if (model.Node == null)
{
model.Node = new TreeNode(View, null) { IsExpanded = true };
View.Model = model;
View.Clear();
}
else
{
View.Model = model;
View.Update();
}
}
else
{
View.Model = null;
View.Clear();
}
Update();
}
#endregion
}
}
| 21.076433 | 81 | 0.661831 | [
"MIT"
] | demonsaw/Code | ds1/Library/Controller/TreeController.cs | 3,311 | C# |
using System;
using HyprWinUI3.Services;
using Windows.ApplicationModel.Activation;
using Windows.UI.Xaml;
namespace HyprWinUI3
{
public sealed partial class App : Application
{
private Lazy<ActivationService> _activationService;
private ActivationService ActivationService => _activationService.Value;
public App()
{
InitializeComponent();
UnhandledException += OnAppUnhandledException;
// Deferred execution until used. Check https://docs.microsoft.com/dotnet/api/system.lazy-1 for further info on Lazy<T> class.
_activationService = new Lazy<ActivationService>(CreateActivationService);
}
protected override async void OnLaunched(LaunchActivatedEventArgs args)
{
DebugSettings.EnableFrameRateCounter = true;
if (!args.PrelaunchActivated)
{
await ActivationService.ActivateAsync(args);
}
}
protected override async void OnActivated(IActivatedEventArgs args)
{
await ActivationService.ActivateAsync(args);
}
private void OnAppUnhandledException(object sender, Windows.UI.Xaml.UnhandledExceptionEventArgs e)
{
// TODO WTS: Please log and handle the exception as appropriate to your scenario
// For more info see https://docs.microsoft.com/uwp/api/windows.ui.xaml.application.unhandledexception
}
private ActivationService CreateActivationService()
{
return new ActivationService(this, typeof(Views.TabViewPage), new Lazy<UIElement>(CreateShell));
}
private UIElement CreateShell()
{
return new Views.ShellPage();
}
}
}
| 27.303571 | 129 | 0.761282 | [
"MIT"
] | HLCaptain/Hypr | App.xaml.cs | 1,531 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using DefaultDocumentation.Markdown.Extensions;
using DefaultDocumentation.Model.Type;
using DefaultDocumentation.Writers;
namespace DefaultDocumentation.Markdown.Sections
{
public sealed class DerivedSection : ISectionWriter
{
public string Name => "Derived";
public void Write(IWriter writer)
{
if (writer.GetCurrentItem() is TypeDocItem typeItem)
{
List<TypeDocItem> derived = writer.Context.Items.OfType<TypeDocItem>().Where(i => i.Type.DirectBaseTypes.Select(t => t.GetDefinition() ?? t).Contains(typeItem.Type)).OrderBy(i => i.FullName).ToList();
if (derived.Count > 0)
{
writer
.EnsureLineStart()
.AppendLine()
.Append("Derived");
foreach (TypeDocItem t in derived)
{
writer
.AppendLine(" ")
.Append("↳ ")
.AppendLink(t);
}
}
}
}
}
}
| 32.184211 | 216 | 0.50695 | [
"MIT-0"
] | Doraku/DefaultDocumentation | source/DefaultDocumentation.Markdown/Sections/DerivedSection.cs | 1,225 | C# |
// <auto-generated />
using System;
using blazor_auth_individual_experiment.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace blazor_auth_individual_experiment.Data.Migrations
{
[DbContext(typeof(ApplicationDbContext))]
partial class ApplicationDbContextModelSnapshot : ModelSnapshot
{
protected override void BuildModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.0.0");
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("TEXT");
b.Property<string>("Name")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUser", b =>
{
b.Property<string>("Id")
.HasColumnType("TEXT");
b.Property<int>("AccessFailedCount")
.HasColumnType("INTEGER");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("TEXT");
b.Property<string>("Email")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("INTEGER");
b.Property<bool>("LockoutEnabled")
.HasColumnType("INTEGER");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("TEXT");
b.Property<string>("NormalizedEmail")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("TEXT");
b.Property<string>("PhoneNumber")
.HasColumnType("TEXT");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("INTEGER");
b.Property<string>("SecurityStamp")
.HasColumnType("TEXT");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("INTEGER");
b.Property<string>("UserName")
.HasColumnType("TEXT")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("INTEGER");
b.Property<string>("ClaimType")
.HasColumnType("TEXT");
b.Property<string>("ClaimValue")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("TEXT")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.HasColumnType("TEXT")
.HasMaxLength(128);
b.Property<string>("ProviderDisplayName")
.HasColumnType("TEXT");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("TEXT");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("TEXT");
b.Property<string>("RoleId")
.HasColumnType("TEXT");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("TEXT");
b.Property<string>("LoginProvider")
.HasColumnType("TEXT")
.HasMaxLength(128);
b.Property<string>("Name")
.HasColumnType("TEXT")
.HasMaxLength(128);
b.Property<string>("Value")
.HasColumnType("TEXT");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityRole", null)
.WithMany()
.HasForeignKey("RoleId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("Microsoft.AspNetCore.Identity.IdentityUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 36.587361 | 96 | 0.436801 | [
"Apache-2.0"
] | jraygauthier/jrg-blazor-auth-experiment | Data/Migrations/ApplicationDbContextModelSnapshot.cs | 9,842 | C# |
/*****************************************************************************
* Copyright 2016 Aurora Solutions
*
* http://www.aurorasolutions.io
*
* Aurora Solutions is an innovative services and product company at
* the forefront of the software industry, with processes and practices
* involving Domain Driven Design(DDD), Agile methodologies to build
* scalable, secure, reliable and high performance products.
*
* Coin Exchange is a high performance exchange system specialized for
* Crypto currency trading. It has different general purpose uses such as
* independent deposit and withdrawal channels for Bitcoin and Litecoin,
* but can also act as a standalone exchange that can be used with
* different asset classes.
* Coin Exchange uses state of the art technologies such as ASP.NET REST API,
* AngularJS and NUnit. It also uses design patterns for complex event
* processing and handling of thousands of transactions per second, such as
* Domain Driven Designing, Disruptor Pattern and CQRS With Event Sourcing.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*****************************************************************************/
using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
using System.Web.Http.Results;
using CoinExchange.Common.Domain.Model;
using CoinExchange.Common.Tests;
using CoinExchange.Trades.Application.OrderServices.Representation;
using CoinExchange.Trades.Domain.Model.CurrencyPairAggregate;
using CoinExchange.Trades.Domain.Model.OrderAggregate;
using CoinExchange.Trades.Domain.Model.OrderMatchingEngine;
using CoinExchange.Trades.Domain.Model.Services;
using CoinExchange.Trades.Infrastructure.Persistence.RavenDb;
using CoinExchange.Trades.Port.Adapter.Rest.DTOs.Order;
using CoinExchange.Trades.Port.Adapter.Rest.DTOs.Trade;
using CoinExchange.Trades.Port.Adapter.Rest.Resources;
using CoinExchange.Trades.ReadModel.DTO;
using CoinExchange.Trades.ReadModel.MemoryImages;
using Disruptor;
using NUnit.Framework;
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using Spring.Context;
using Spring.Context.Support;
namespace CoinExchange.Trades.Port.Adapter.Rest.IntegrationTests
{
[TestFixture]
public class EndToEndTests
{
private DatabaseUtility _databaseUtility;
private IEventStore inputEventStore;
private IEventStore outputEventStore;
private Journaler inputJournaler;
private Journaler outputJournaler;
[SetUp]
public new void SetUp()
{
var connection = ConfigurationManager.ConnectionStrings["MySql"].ToString();
_databaseUtility = new DatabaseUtility(connection);
_databaseUtility.Create();
_databaseUtility.Populate();
inputEventStore = new RavenNEventStore(Constants.INPUT_EVENT_STORE);
outputEventStore = new RavenNEventStore(Constants.OUTPUT_EVENT_STORE);
inputJournaler = new Journaler(inputEventStore);
outputJournaler = new Journaler(outputEventStore);
IList<CurrencyPair> currencyPairs = new List<CurrencyPair>();
currencyPairs.Add(new CurrencyPair("BTCUSD", "USD", "BTC"));
currencyPairs.Add(new CurrencyPair("BTCLTC", "LTC", "BTC"));
currencyPairs.Add(new CurrencyPair("BTCDOGE", "DOGE", "BTC"));
Exchange exchange = new Exchange(currencyPairs);
InputDisruptorPublisher.InitializeDisruptor(new IEventHandler<InputPayload>[] { exchange, inputJournaler });
OutputDisruptor.InitializeDisruptor(new IEventHandler<byte[]>[] { outputJournaler });
}
[TearDown]
public new void TearDown()
{
_databaseUtility.Create();
InputDisruptorPublisher.Shutdown();
OutputDisruptor.ShutDown();
inputEventStore.RemoveAllEvents();
outputEventStore.RemoveAllEvents();
}
[Test]
[Category("Integration")]
public void Scenario1Test_TestsScenario1AndItsOutcome_VerifiesThroughMarketDataOrderAndTradesResults()
{
// Get the context
IApplicationContext applicationContext = ContextRegistry.GetContext();
// Get the instance through Spring configuration
OrderController orderController = (OrderController)applicationContext["OrderController"];
TradeController tradeController = (TradeController)applicationContext["TradeController"];
MarketController marketController = (MarketController)applicationContext["MarketController"];
orderController.Request = new HttpRequestMessage(HttpMethod.Post, "");
orderController.Request.Headers.Add("Auth", "123456789");
tradeController.Request = new HttpRequestMessage(HttpMethod.Post, "");
tradeController.Request.Headers.Add("Auth", "123456789");
marketController.Request = new HttpRequestMessage(HttpMethod.Post, "");
marketController.Request.Headers.Add("Auth", "123456789");
Scenario1OrderCreation(orderController);
// ------------------------------- Order Book ------------------------------
IHttpActionResult orderBookResponse = marketController.GetOrderBook("BTCLTC");
OkNegotiatedContentResult<object> okOrderBookResponse =
(OkNegotiatedContentResult<object>) orderBookResponse;
OrderBookRepresentation representation = okOrderBookResponse.Content as OrderBookRepresentation;
Tuple<OrderRepresentationList, OrderRepresentationList> orderBook =new Tuple<OrderRepresentationList, OrderRepresentationList>(representation.Bids,representation.Asks);
// Item1 = Bid Book, Item1[i].Item1 = Volume of 'i' Bid, Item1[i].Item2 = Price of 'i' Bid
Assert.AreEqual(5, orderBook.Item1.ToList()[0].Volume);
Assert.AreEqual(250, orderBook.Item1.ToList()[0].Price);
Assert.AreEqual(2, orderBook.Item1.ToList()[1].Volume);
Assert.AreEqual(250, orderBook.Item1.ToList()[1].Price);
// Item2 = Ask Book, Item2[i].Item1 = Volume of Ask at index 'i', Item2[i].Item2 = Price of Ask at index 'i'
Assert.AreEqual(0, orderBook.Item2.Count());
// ------------------------------- Order Book ------------------------------
IHttpActionResult depthResponse = marketController.GetDepth("BTCLTC");
OkNegotiatedContentResult<object> okDepth
= (OkNegotiatedContentResult<object>)depthResponse;
DepthTupleRepresentation depth = okDepth.Content as DepthTupleRepresentation;
// Item1 = Bid Book, Item1.Item1 = Aggregated Volume, Item1.Item2 = Price, Item1.Item3 = Number of Orders
Assert.AreEqual(7, depth.BidDepth[0].Volume);
Assert.AreEqual(250, depth.BidDepth[0].Price);
Assert.AreEqual(2, depth.BidDepth[0].OrderCount);
Assert.IsNull(depth.BidDepth[1]);
Assert.IsNull(depth.BidDepth[2]);
Assert.IsNull(depth.BidDepth[3]);
Assert.IsNull(depth.BidDepth[4]);
// Item2 = Ask Book, Item2.Item1 = Aggregated Volume, Item2.Item2 = Price, Item2.Item3 = Number of Orders
Assert.IsNull(depth.AskDepth[0]);
Assert.IsNull(depth.AskDepth[1]);
Assert.IsNull(depth.AskDepth[2]);
Assert.IsNull(depth.AskDepth[3]);
Assert.IsNull(depth.AskDepth[4]);
//------------------- Open Orders -------------------------
IHttpActionResult openOrdersResponse = GetOpenOrders(orderController);
OkNegotiatedContentResult<List<OrderReadModel>> okOpenOrdersResponse = (OkNegotiatedContentResult<List<OrderReadModel>>)openOrdersResponse;
List<OrderReadModel> openOrders = okOpenOrdersResponse.Content;
Assert.AreEqual(2, openOrders.Count);
// First Open Order
Assert.AreEqual(250, openOrders[1].Price);
Assert.AreEqual(10, openOrders[1].Volume);
Assert.AreEqual(5, openOrders[1].VolumeExecuted);
Assert.AreEqual(5, openOrders[1].OpenQuantity);
Assert.AreEqual("Limit", openOrders[1].Type);
Assert.AreEqual("Buy", openOrders[1].Side);
Assert.AreEqual("PartiallyFilled", openOrders[1].Status);
// Second Open Order
Assert.AreEqual(250, openOrders[0].Price);
Assert.AreEqual(2, openOrders[0].Volume);
Assert.AreEqual(0, openOrders[0].VolumeExecuted);
Assert.AreEqual(2, openOrders[0].OpenQuantity);
Assert.AreEqual("Limit", openOrders[0].Type);
Assert.AreEqual("Buy", openOrders[0].Side);
Assert.AreEqual("Accepted", openOrders[0].Status);
//------------------- Open Orders -------------------------
//------------------- Closed Orders -------------------------
IHttpActionResult closedOrdersResponse = GetClosedOrders(orderController);
OkNegotiatedContentResult<List<OrderReadModel>> okClosedOrdersResponse = (OkNegotiatedContentResult<List<OrderReadModel>>)closedOrdersResponse;
List<OrderReadModel> closedOrders = okClosedOrdersResponse.Content;
Assert.AreEqual(252, closedOrders[3].Price);
Assert.AreEqual(5, closedOrders[3].Volume);
Assert.AreEqual(5, closedOrders[3].VolumeExecuted);
Assert.AreEqual(0, closedOrders[3].OpenQuantity);
Assert.AreEqual("Limit", closedOrders[3].Type);
Assert.AreEqual("Sell", closedOrders[3].Side);
Assert.AreEqual("Complete", closedOrders[3].Status);
Assert.AreEqual(0, closedOrders[2].Price);
Assert.AreEqual(3, closedOrders[2].Volume);
Assert.AreEqual(3, closedOrders[2].VolumeExecuted);
Assert.AreEqual(0, closedOrders[2].OpenQuantity);
Assert.AreEqual("Market", closedOrders[2].Type);
Assert.AreEqual("Buy", closedOrders[2].Side);
Assert.AreEqual("Complete", closedOrders[2].Status);
Assert.AreEqual(253, closedOrders[1].Price);
Assert.AreEqual(2, closedOrders[1].Volume);
Assert.AreEqual(2, closedOrders[1].VolumeExecuted);
Assert.AreEqual(0, closedOrders[1].OpenQuantity);
Assert.AreEqual("Limit", closedOrders[1].Type);
Assert.AreEqual("Buy", closedOrders[1].Side);
Assert.AreEqual("Complete", closedOrders[1].Status);
Assert.AreEqual(0, closedOrders[0].Price);
Assert.AreEqual(5, closedOrders[0].Volume);
Assert.AreEqual(5, closedOrders[0].VolumeExecuted);
Assert.AreEqual(0, closedOrders[0].OpenQuantity);
Assert.AreEqual("Market", closedOrders[0].Type);
Assert.AreEqual("Sell", closedOrders[0].Side);
Assert.AreEqual("Complete", closedOrders[0].Status);
//------------------- Closed Orders -------------------------
//------------------- Trades -------------------------
IHttpActionResult tradesResponse = GetTrades(tradeController);
OkNegotiatedContentResult<object> okTradeResponse = (OkNegotiatedContentResult<object>) tradesResponse;
IList<object> tradesintermediateList = (IList<object>)okTradeResponse.Content;
IList<object[]> trades = new List<object[]>();
for (int i = 0; i < tradesintermediateList.Count; i++)
{
object[] objects = tradesintermediateList[i] as object[];
trades.Add(objects);
}
// This call return list of object, so we have to explicitly check values within elements
Assert.AreEqual(252, trades[2][2]);// Price
Assert.AreEqual(3, trades[2][3]);// Volume
Assert.AreEqual("BTCLTC", trades[2][4]);
Assert.AreEqual(252, trades[1][2]);
Assert.AreEqual(2, trades[1][3]);
Assert.AreEqual("BTCLTC", trades[0][4]);
Assert.AreEqual(250, trades[0][2]);
Assert.AreEqual(5, trades[0][3]);
Assert.AreEqual("BTCLTC", trades[0][4]);
//------------------- Trades -------------------------
}
[Test]
[Category("Integration")]
public void Scenario2Test_TestsScenario2AndItsOutcome_VerifiesThroughMarketDataOrderAndTradesResults()
{
// Get the context
IApplicationContext applicationContext = ContextRegistry.GetContext();
// Get the instance through Spring configuration
OrderController orderController = (OrderController)applicationContext["OrderController"];
TradeController tradeController = (TradeController)applicationContext["TradeController"];
MarketController marketController = (MarketController)applicationContext["MarketController"];
orderController.Request = new HttpRequestMessage(HttpMethod.Post, "");
orderController.Request.Headers.Add("Auth", "123456789");
tradeController.Request = new HttpRequestMessage(HttpMethod.Post, "");
tradeController.Request.Headers.Add("Auth", "123456789");
marketController.Request = new HttpRequestMessage(HttpMethod.Post, "");
marketController.Request.Headers.Add("Auth", "123456789");
Scenario2OrderCreation(orderController);
// ------------------------------- Order Book ------------------------------
IHttpActionResult orderBookResponse = marketController.GetOrderBook("BTCLTC");
OkNegotiatedContentResult<object> okOrderBookResponse =
(OkNegotiatedContentResult<object>)orderBookResponse;
OrderBookRepresentation representation = okOrderBookResponse.Content as OrderBookRepresentation;
Tuple<OrderRepresentationList, OrderRepresentationList> orderBook = new Tuple<OrderRepresentationList, OrderRepresentationList>(representation.Bids,representation.Asks);
// Item1 = Bid Book, Item1[i].Item1 = Volume of 'i' Bid, Item1[i].Item2 = Price of 'i' Bid
Assert.AreEqual(1, orderBook.Item1.Count());
Assert.AreEqual(1, orderBook.Item1.ToList()[0].Volume);
Assert.AreEqual(245, orderBook.Item1.ToList()[0].Price);
// Item2 = Bid Book, Item2[i].Item1 = Volume of Ask at index 'i', Item2[i].Item2 = Price of Bid at index 'i'
Assert.AreEqual(0, orderBook.Item2.Count());
// ------------------------------------------------------------------------
// --------------------------------- Depth ---------------------------------
IHttpActionResult depthResponse = marketController.GetDepth("BTCLTC");
OkNegotiatedContentResult<object> okDepth
= (OkNegotiatedContentResult<object>)depthResponse;
DepthTupleRepresentation depth = okDepth.Content as DepthTupleRepresentation;
// Item1 = Bid Book, Item1.Item1 = Aggregated Volume, Item1.Item2 = Price, Item1.Item3 = Number of Orders
Assert.AreEqual(1, depth.BidDepth[0].Volume);
Assert.AreEqual(245, depth.BidDepth[0].Price);
Assert.AreEqual(1, depth.BidDepth[0].OrderCount);
Assert.IsNull(depth.BidDepth[1]);
Assert.IsNull(depth.BidDepth[2]);
Assert.IsNull(depth.BidDepth[3]);
Assert.IsNull(depth.BidDepth[4]);
// Item2 = Bid Book, Item2.Item1 = Aggregated Volume, Item2.Item2 = Price, Item2.Item3 = Number of Orders
Assert.IsNull(depth.AskDepth[0]);
Assert.IsNull(depth.AskDepth[1]);
Assert.IsNull(depth.AskDepth[2]);
Assert.IsNull(depth.AskDepth[3]);
Assert.IsNull(depth.AskDepth[4]);
// -----------------------------------------------------------------------
//------------------------- Open Orders ----------------------------------
IHttpActionResult openOrdersResponse = GetOpenOrders(orderController);
OkNegotiatedContentResult<List<OrderReadModel>> okOpenOrdersResponse = (OkNegotiatedContentResult<List<OrderReadModel>>)openOrdersResponse;
List<OrderReadModel> openOrders = okOpenOrdersResponse.Content;
Assert.AreEqual(1, openOrders.Count);
// First Open Order
Assert.AreEqual(245, openOrders[0].Price);
Assert.AreEqual(8, openOrders[0].Volume);
Assert.AreEqual(7, openOrders[0].VolumeExecuted);
Assert.AreEqual(1, openOrders[0].OpenQuantity);
Assert.AreEqual("Limit", openOrders[0].Type);
Assert.AreEqual("Buy", openOrders[0].Side);
Assert.AreEqual("PartiallyFilled", openOrders[0].Status);
//---------------------------------------------------------------------
//-------------------------- Closed Orders ----------------------------
IHttpActionResult closedOrdersResponse = GetClosedOrders(orderController);
OkNegotiatedContentResult<List<OrderReadModel>> okClosedOrdersResponse = (OkNegotiatedContentResult<List<OrderReadModel>>)closedOrdersResponse;
List<OrderReadModel> closedOrders = okClosedOrdersResponse.Content;
// Order List comes in descending order, so asserts are placed that way too
Assert.AreEqual(0, closedOrders[7].Price);
Assert.AreEqual(10, closedOrders[7].Volume);
Assert.AreEqual(0, closedOrders[7].VolumeExecuted);
Assert.AreEqual(10, closedOrders[7].OpenQuantity);
Assert.AreEqual("Market", closedOrders[7].Type);
Assert.AreEqual("Buy", closedOrders[7].Side);
Assert.AreEqual("Rejected", closedOrders[7].Status);
Assert.AreEqual(252, closedOrders[6].Price);
Assert.AreEqual(5, closedOrders[6].Volume);
Assert.AreEqual(3, closedOrders[6].VolumeExecuted);
Assert.AreEqual(2, closedOrders[6].OpenQuantity);
Assert.AreEqual("Limit", closedOrders[6].Type);
Assert.AreEqual("Sell", closedOrders[6].Side);
Assert.AreEqual("Cancelled", closedOrders[6].Status);
Assert.AreEqual(250, closedOrders[5].Price);
Assert.AreEqual(7, closedOrders[5].Volume);
Assert.AreEqual(7, closedOrders[5].VolumeExecuted);
Assert.AreEqual(0, closedOrders[5].OpenQuantity);
Assert.AreEqual("Limit", closedOrders[5].Type);
Assert.AreEqual("Buy", closedOrders[5].Side);
Assert.AreEqual("Complete", closedOrders[5].Status);
Assert.AreEqual(0, closedOrders[4].Price);
Assert.AreEqual(3, closedOrders[4].Volume);
Assert.AreEqual(3, closedOrders[4].VolumeExecuted);
Assert.AreEqual(0, closedOrders[4].OpenQuantity);
Assert.AreEqual("Market", closedOrders[4].Type);
Assert.AreEqual("Buy", closedOrders[4].Side);
Assert.AreEqual("Complete", closedOrders[4].Status);
Assert.AreEqual(0, closedOrders[3].Price);
Assert.AreEqual(10, closedOrders[3].Volume);
Assert.AreEqual(0, closedOrders[3].VolumeExecuted);
Assert.AreEqual(10, closedOrders[3].OpenQuantity);
Assert.AreEqual("Market", closedOrders[3].Type);
Assert.AreEqual("Buy", closedOrders[3].Side);
Assert.AreEqual("Rejected", closedOrders[3].Status);
Assert.AreEqual(0, closedOrders[2].Price);
Assert.AreEqual(5, closedOrders[2].Volume);
Assert.AreEqual(5, closedOrders[2].VolumeExecuted);
Assert.AreEqual(0, closedOrders[2].OpenQuantity);
Assert.AreEqual("Market", closedOrders[2].Type);
Assert.AreEqual("Sell", closedOrders[2].Side);
Assert.AreEqual("Complete", closedOrders[2].Status);
Assert.AreEqual(0, closedOrders[1].Price);
Assert.AreEqual(4, closedOrders[1].Volume);
Assert.AreEqual(4, closedOrders[1].VolumeExecuted);
Assert.AreEqual(0, closedOrders[1].OpenQuantity);
Assert.AreEqual("Market", closedOrders[1].Type);
Assert.AreEqual("Sell", closedOrders[1].Side);
Assert.AreEqual("Complete", closedOrders[1].Status);
Assert.AreEqual(0, closedOrders[0].Price);
Assert.AreEqual(5, closedOrders[0].Volume);
Assert.AreEqual(5, closedOrders[0].VolumeExecuted);
Assert.AreEqual(0, closedOrders[0].OpenQuantity);
Assert.AreEqual("Market", closedOrders[0].Type);
Assert.AreEqual("Sell", closedOrders[0].Side);
Assert.AreEqual("Complete", closedOrders[0].Status);
//------------------------------------------------------------------------
//------------------- Trades -------------------------
IHttpActionResult tradesResponse = GetTrades(tradeController);
OkNegotiatedContentResult<object> okTradeResponse = (OkNegotiatedContentResult<object>)tradesResponse;
IList<object> tradesintermediateList = (IList<object>)okTradeResponse.Content;
IList<object[]> trades = new List<object[]>();
for (int i = 0; i < tradesintermediateList.Count; i++)
{
object[] objects = tradesintermediateList[i] as object[];
trades.Add(objects);
}
// This call return list of object, so we have to explicitly check values within elements
Assert.AreEqual(252, trades[4][2]);// Price
Assert.AreEqual(3, trades[4][3]);// Volume
Assert.AreEqual("BTCLTC", trades[4][4]);
Assert.AreEqual(250, trades[3][2]);
Assert.AreEqual(5, trades[3][3]);
Assert.AreEqual("BTCLTC", trades[3][4]);
// These trades execute simultaneously, so when queried from the database and sorted as per the time when
// they were saved in the database, they can be queried out of the order as we expected because they have the
// same time. So we check if one trade came before the other and place assertions for it then for the other and
// vice versa
if ((decimal)trades[2][2] == 250 && (decimal)trades[2][3] == 2)
{
Assert.AreEqual(250, trades[2][2]);
Assert.AreEqual(2, trades[2][3]);
Assert.AreEqual("BTCLTC", trades[2][4]);
}
else if ((decimal)trades[2][2] == 245 && (decimal)trades[2][3] == 2)
{
Assert.AreEqual(245, trades[2][2]);
Assert.AreEqual(2, trades[2][3]);
Assert.AreEqual("BTCLTC", trades[2][4]);
}
else
{
throw new Exception("No assertions could be made on expected trade");
}
if ((decimal)trades[1][2] == 250 && (decimal)trades[1][3] == 2)
{
Assert.AreEqual(250, trades[1][2]);
Assert.AreEqual(2, trades[1][3]);
Assert.AreEqual("BTCLTC", trades[1][4]);
}
else if ((decimal)trades[1][2] == 245 && (decimal)trades[1][3] == 2)
{
Assert.AreEqual(245, trades[1][2]);
Assert.AreEqual(2, trades[1][3]);
Assert.AreEqual("BTCLTC", trades[1][4]);
}
else
{
throw new Exception("No assertions could be made on expected trade");
}
Assert.AreEqual(245, trades[0][2]);
Assert.AreEqual(5, trades[0][3]);
Assert.AreEqual("BTCLTC", trades[0][4]);
//-----------------------------------------------------------------------
}
[Test]
[Category("Integration")]
public void Scenario3Test_TestsScenario3AndItsOutcome_VerifiesThroughMarketDataOrderAndTradesResults()
{
// Get the context
IApplicationContext applicationContext = ContextRegistry.GetContext();
// Get the instance through Spring configuration
OrderController orderController = (OrderController)applicationContext["OrderController"];
TradeController tradeController = (TradeController)applicationContext["TradeController"];
MarketController marketController = (MarketController)applicationContext["MarketController"];
orderController.Request = new HttpRequestMessage(HttpMethod.Post, "");
orderController.Request.Headers.Add("Auth", "123456789");
tradeController.Request = new HttpRequestMessage(HttpMethod.Post, "");
tradeController.Request.Headers.Add("Auth", "123456789");
marketController.Request = new HttpRequestMessage(HttpMethod.Post, "");
marketController.Request.Headers.Add("Auth", "123456789");
Scenario3OrderCreation(orderController);
// ------------------------------- Order Book ------------------------------
IHttpActionResult orderBookResponse = marketController.GetOrderBook("BTCLTC");
OkNegotiatedContentResult<object> okOrderBookResponse =
(OkNegotiatedContentResult<object>)orderBookResponse;
OrderBookRepresentation representation = okOrderBookResponse.Content as OrderBookRepresentation;
Tuple<OrderRepresentationList, OrderRepresentationList> orderBook = new Tuple<OrderRepresentationList, OrderRepresentationList>(representation.Bids,representation.Asks);
// Item1 = Bid Book, Item1[i].Item1 = Volume of 'i' Bid, Item1[i].Item2 = Price of 'i' Bid
Assert.AreEqual(0, orderBook.Item1.Count());
// Item2 = Bid Book, Item2[i].Item1 = Volume of Ask at index 'i', Item2[i].Item2 = Price of Bid at index 'i'
Assert.AreEqual(0, orderBook.Item2.Count());
// ------------------------------------------------------------------------
// --------------------------------- Depth ---------------------------------
IHttpActionResult depthResponse = marketController.GetDepth("BTCLTC");
OkNegotiatedContentResult<object> okDepth
= (OkNegotiatedContentResult<object>)depthResponse;
DepthTupleRepresentation depth = okDepth.Content as DepthTupleRepresentation;
// Item1 = Bid Book, Item1.Item1 = Aggregated Volume, Item1.Item2 = Price, Item1.Item3 = Number of Orders
Assert.IsNull(depth.BidDepth[0]);
Assert.IsNull(depth.BidDepth[1]);
Assert.IsNull(depth.BidDepth[2]);
Assert.IsNull(depth.BidDepth[3]);
Assert.IsNull(depth.BidDepth[4]);
// Item2 = Bid Book, Item2.Item1 = Aggregated Volume, Item2.Item2 = Price, Item2.Item3 = Number of Orders
Assert.IsNull(depth.AskDepth[0]);
Assert.IsNull(depth.AskDepth[1]);
Assert.IsNull(depth.AskDepth[2]);
Assert.IsNull(depth.AskDepth[3]);
Assert.IsNull(depth.AskDepth[4]);
// -----------------------------------------------------------------------
//------------------------- Open Orders ----------------------------------
IHttpActionResult openOrdersResponse = GetOpenOrders(orderController);
OkNegotiatedContentResult<List<OrderReadModel>> okOpenOrdersResponse = (OkNegotiatedContentResult<List<OrderReadModel>>)openOrdersResponse;
List<OrderReadModel> openOrders = okOpenOrdersResponse.Content;
Assert.AreEqual(0, openOrders.Count);
//---------------------------------------------------------------------
//-------------------------- Closed Orders ----------------------------
IHttpActionResult closedOrdersResponse = GetClosedOrders(orderController);
OkNegotiatedContentResult<List<OrderReadModel>> okClosedOrdersResponse = (OkNegotiatedContentResult<List<OrderReadModel>>)closedOrdersResponse;
List<OrderReadModel> closedOrders = okClosedOrdersResponse.Content;
// Order List comes in descending order, so asserts are placed that way too
Assert.AreEqual(252, closedOrders[8].Price);
Assert.AreEqual(5, closedOrders[8].Volume);
Assert.AreEqual(0, closedOrders[8].VolumeExecuted);
Assert.AreEqual(5, closedOrders[8].OpenQuantity);
Assert.AreEqual("Limit", closedOrders[8].Type);
Assert.AreEqual("Sell", closedOrders[8].Side);
Assert.AreEqual("Cancelled", closedOrders[8].Status);
Assert.AreEqual(245, closedOrders[7].Price);
Assert.AreEqual(8, closedOrders[7].Volume);
Assert.AreEqual(0, closedOrders[7].VolumeExecuted);
Assert.AreEqual(8, closedOrders[7].OpenQuantity);
Assert.AreEqual("Limit", closedOrders[7].Type);
Assert.AreEqual("Buy", closedOrders[7].Side);
Assert.AreEqual("Cancelled", closedOrders[7].Status);
Assert.AreEqual(250, closedOrders[6].Price);
Assert.AreEqual(7, closedOrders[6].Volume);
Assert.AreEqual(7, closedOrders[6].VolumeExecuted);
Assert.AreEqual(0, closedOrders[6].OpenQuantity);
Assert.AreEqual("Limit", closedOrders[6].Type);
Assert.AreEqual("Buy", closedOrders[6].Side);
Assert.AreEqual("Complete", closedOrders[6].Status);
Assert.AreEqual(250, closedOrders[5].Price);
Assert.AreEqual(3, closedOrders[5].Volume);
Assert.AreEqual(2, closedOrders[5].VolumeExecuted);
Assert.AreEqual(1, closedOrders[5].OpenQuantity);
Assert.AreEqual("Limit", closedOrders[5].Type);
Assert.AreEqual("Buy", closedOrders[5].Side);
Assert.AreEqual("Cancelled", closedOrders[5].Status);
Assert.AreEqual(253, closedOrders[4].Price);
Assert.AreEqual(5, closedOrders[4].Volume);
Assert.AreEqual(0, closedOrders[4].VolumeExecuted);
Assert.AreEqual(5, closedOrders[4].OpenQuantity);
Assert.AreEqual("Limit", closedOrders[4].Type);
Assert.AreEqual("Sell", closedOrders[4].Side);
Assert.AreEqual("Cancelled", closedOrders[4].Status);
Assert.AreEqual(240, closedOrders[3].Price);
Assert.AreEqual(8, closedOrders[3].Volume);
Assert.AreEqual(0, closedOrders[3].VolumeExecuted);
Assert.AreEqual(8, closedOrders[3].OpenQuantity);
Assert.AreEqual("Limit", closedOrders[3].Type);
Assert.AreEqual("Buy", closedOrders[3].Side);
Assert.AreEqual("Cancelled", closedOrders[3].Status);
Assert.AreEqual(245, closedOrders[2].Price);
Assert.AreEqual(7, closedOrders[2].Volume);
Assert.AreEqual(0, closedOrders[2].VolumeExecuted);
Assert.AreEqual(7, closedOrders[2].OpenQuantity);
Assert.AreEqual("Limit", closedOrders[2].Type);
Assert.AreEqual("Buy", closedOrders[2].Side);
Assert.AreEqual("Cancelled", closedOrders[2].Status);
Assert.AreEqual(247, closedOrders[1].Price);
Assert.AreEqual(3, closedOrders[1].Volume);
Assert.AreEqual(0, closedOrders[1].VolumeExecuted);
Assert.AreEqual(3, closedOrders[1].OpenQuantity);
Assert.AreEqual("Limit", closedOrders[1].Type);
Assert.AreEqual("Buy", closedOrders[1].Side);
Assert.AreEqual("Cancelled", closedOrders[1].Status);
Assert.AreEqual(0, closedOrders[0].Price);
Assert.AreEqual(9, closedOrders[0].Volume);
Assert.AreEqual(9, closedOrders[0].VolumeExecuted);
Assert.AreEqual(0, closedOrders[0].OpenQuantity);
Assert.AreEqual("Market", closedOrders[0].Type);
Assert.AreEqual("Sell", closedOrders[0].Side);
Assert.AreEqual("Complete", closedOrders[0].Status);
//------------------------------------------------------------------------
//------------------- Trades -------------------------
IHttpActionResult tradesResponse = GetTrades(tradeController);
OkNegotiatedContentResult<object> okTradeResponse = (OkNegotiatedContentResult<object>)tradesResponse;
IList<object> tradesintermediateList = (IList<object>)okTradeResponse.Content;
IList<object[]> trades = new List<object[]>();
for (int i = 0; i < tradesintermediateList.Count; i++)
{
object[] objects = tradesintermediateList[i] as object[];
trades.Add(objects);
}
// These trades execute simultaneously, so when queried from the database and sorted as per the time when
// they were saved in the database, they can be queried out of the order as we expected because they have the
// same time. So we check if one trade came before the other and place assertions for it then for the other and
// vice versa
if ((decimal)trades[1][3] == 7)
{
Assert.AreEqual(250, trades[1][2]);// Price
Assert.AreEqual(7, trades[1][3]); // Volume
Assert.AreEqual("BTCLTC", trades[1][4]); // CurrencyPair
}
else if ((decimal)trades[1][3] == 2)
{
Assert.AreEqual(250, trades[1][2]);
Assert.AreEqual(2, trades[1][3]);
Assert.AreEqual("BTCLTC", trades[1][4]);
}
else
{
throw new Exception("No assertions could be made on expected trade");
}
if ((decimal)trades[0][3] == 7)
{
Assert.AreEqual(250, trades[0][2]);// Price
Assert.AreEqual(7, trades[0][3]); // Volume
Assert.AreEqual("BTCLTC", trades[0][4]); // CurrencyPair
}
else if ((decimal)trades[0][3] == 2)
{
Assert.AreEqual(250, trades[0][2]);// Price
Assert.AreEqual(2, trades[0][3]); // Volume
Assert.AreEqual("BTCLTC", trades[0][4]); // CurrencyPair
}
else
{
throw new Exception("No assertions could be made on expected trade");
}
//-----------------------------------------------------------------------
}
#region Client Methods
/// <summary>
/// Testing scenario 1
/// </summary>
private void Scenario1OrderCreation(OrderController orderController)
{
string currecyPair = "BTCLTC";
//Create orders
Console.WriteLine(orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "limit", 250, 10)));
Thread.Sleep(2000);
Console.WriteLine(orderController.CreateOrder(new CreateOrderParam(currecyPair, "sell", "limit", 252, 5)));
Thread.Sleep(2000);
Console.WriteLine(orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "market", 0, 3)));
Thread.Sleep(2000);
Console.WriteLine(orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "limit", 253, 2)));
Thread.Sleep(2000);
Console.WriteLine(orderController.CreateOrder(new CreateOrderParam(currecyPair, "sell", "market", 0, 5)));
Thread.Sleep(2000);
Console.WriteLine(orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "limit", 250, 2)));
Thread.Sleep(4000);
}
/// <summary>
/// Scenrio 2 order creation and sending
/// </summary>
/// <param name="orderController"></param>
private void Scenario2OrderCreation(OrderController orderController)
{
string currecyPair = "BTCLTC";
IHttpActionResult httpActionResult1 = (orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "market", 0, 10)));
Thread.Sleep(2000);
string orderId1 = this.GetOrderId(httpActionResult1);
IHttpActionResult httpActionResult2 = orderController.CreateOrder(new CreateOrderParam(currecyPair, "sell", "limit", 252, 5));
string orderId2 = this.GetOrderId(httpActionResult2);
Thread.Sleep(2000);
IHttpActionResult httpActionResult3 = orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "limit", 245, 8));
string orderId3 = this.GetOrderId(httpActionResult3);
Thread.Sleep(2000);
IHttpActionResult httpActionResult4 = orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "limit", 250, 7));
string orderId4 = this.GetOrderId(httpActionResult4);
Thread.Sleep(2000);
orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "market", 0, 3));
Thread.Sleep(2000);
System.Console.WriteLine(orderController.CancelOrder(orderId2));
Thread.Sleep(2000);
orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "market", 0, 10));
Thread.Sleep(2000);
orderController.CreateOrder(new CreateOrderParam(currecyPair, "sell", "market", 0, 5));
Thread.Sleep(2000);
System.Console.WriteLine(orderController.CancelOrder(orderId2));
Thread.Sleep(2000);
orderController.CreateOrder(new CreateOrderParam(currecyPair, "sell", "market", 0, 4));
Thread.Sleep(2000);
orderController.CreateOrder(new CreateOrderParam(currecyPair, "sell", "market", 0, 5));
Thread.Sleep(4000);
}
/// <summary>
/// Creates and sends order for Scenario 3
/// </summary>
/// <param name="orderController"></param>
private void Scenario3OrderCreation(OrderController orderController)
{
string currecyPair = "BTCLTC";
IHttpActionResult httpActionResult1 = orderController.CreateOrder(new CreateOrderParam(currecyPair, "sell", "limit", 252, 5));
Thread.Sleep(2000);
string orderId1 = this.GetOrderId(httpActionResult1);
IHttpActionResult httpActionResult2 = orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "limit", 245, 8));
Thread.Sleep(2000);
string orderId2 = this.GetOrderId(httpActionResult2);
IHttpActionResult httpActionResult3 = orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "limit", 250, 7));
Thread.Sleep(2000);
string orderId3 = this.GetOrderId(httpActionResult3);
IHttpActionResult httpActionResult4 = orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "limit", 250, 3));
Thread.Sleep(2000);
string orderId4 = this.GetOrderId(httpActionResult4);
IHttpActionResult httpActionResult5 = orderController.CreateOrder(new CreateOrderParam(currecyPair, "sell", "limit", 253, 5));
Thread.Sleep(2000);
string orderId5 = this.GetOrderId(httpActionResult5);
IHttpActionResult httpActionResult6 = orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "limit", 240, 8));
Thread.Sleep(2000);
string orderId6 = this.GetOrderId(httpActionResult6);
IHttpActionResult httpActionResult7 = orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "limit", 245, 7));
Thread.Sleep(2000);
string orderId7 = this.GetOrderId(httpActionResult7);
IHttpActionResult httpActionResult8 = orderController.CreateOrder(new CreateOrderParam(currecyPair, "buy", "limit", 247, 3));
Thread.Sleep(2000);
string orderId8 = this.GetOrderId(httpActionResult8);
System.Console.WriteLine(orderController.CancelOrder(orderId6));
Thread.Sleep(2000);
System.Console.WriteLine(orderController.CancelOrder(orderId1));
Thread.Sleep(2000);
orderController.CreateOrder(new CreateOrderParam(currecyPair, "sell", "market", 0, 9));
Thread.Sleep(2000);
System.Console.WriteLine(orderController.CancelOrder(orderId8));
Thread.Sleep(2000);
System.Console.WriteLine(orderController.CancelOrder(orderId7));
Thread.Sleep(2000);
System.Console.WriteLine(orderController.CancelOrder(orderId6));
Thread.Sleep(2000);
System.Console.WriteLine(orderController.CancelOrder(orderId5));
Thread.Sleep(2000);
System.Console.WriteLine(orderController.CancelOrder(orderId4));
Thread.Sleep(2000);
System.Console.WriteLine(orderController.CancelOrder(orderId3));
Thread.Sleep(2000);
System.Console.WriteLine(orderController.CancelOrder(orderId2));
Thread.Sleep(2000);
System.Console.WriteLine(orderController.CancelOrder(orderId1));
Thread.Sleep(5000);
}
/// <summary>
/// Extracts OrderID from the HttpActionresult
/// </summary>
/// <param name="httpActionResult"></param>
/// <returns></returns>
public string GetOrderId(IHttpActionResult httpActionResult)
{
OkNegotiatedContentResult<NewOrderRepresentation> okResponseMessage =
(OkNegotiatedContentResult<NewOrderRepresentation>)httpActionResult;
NewOrderRepresentation newOrderRepresentation = okResponseMessage.Content;
return newOrderRepresentation.OrderId;
}
/// <summary>
/// Get Open Orders
/// </summary>
private dynamic GetOpenOrders(OrderController orderController)
{
return orderController.QueryOpenOrders("true");
}
/// <summary>
/// Get Closed Orders
/// </summary>
/// <param name="orderController"></param>
/// <returns></returns>
private dynamic GetClosedOrders(OrderController orderController)
{
return orderController.QueryClosedOrders(new QueryClosedOrdersParams(true, "", ""));
}
/// <summary>
/// Get Trades
/// </summary>
/// <param name="tradeController"></param>
/// <returns></returns>
private dynamic GetTrades(TradeController tradeController)
{
return tradeController.GetTradeHistory(new TradeHistoryParams("", ""));
}
#endregion Client Methods
}
}
| 53.844471 | 182 | 0.598863 | [
"Apache-2.0"
] | 3plcoins/coin-exchange-backend | src/Trades/CoinExchange.Trades.Port.Adapter.Rest.IntegrationTests/EndToEndTests.cs | 44,316 | C# |
namespace Enclave.Sdk.Api.Data.Authority;
/// <summary>
/// Defines bit-flags indicating what a certificate can be used for.
/// </summary>
[Flags]
public enum CertificatePermittedUse : byte
{
/// <summary>
/// No Permitted Uses.
/// </summary>
None = 0x0,
/// <summary>
/// For individual endpoints.
/// </summary>
/// <remarks>
/// Certificate commonName is assigned by the root or intermediate, the public key owners identity is not validated.
/// Certificate may only be signed by an intermediate or root. issued to a primary key.
/// Certificate may not be used to signed by another. Certificates signed by endpoints are considered invalid.
/// </remarks>
Endpoint = 0x2,
/// <summary>
/// Special class of endpoint certificate reserved for operational infrastructure, discovery service, relay services etc.
/// </summary>
Infrastructure = 0x4,
/// <summary>
/// For intermediate level certificates
/// ===================================
/// This class may only sign endpoints (class 0), and can only be signed by a root.
/// </summary>
Intermediate = 0x8,
/// <summary>
/// For root level certificates
/// ===========================
/// This class may only be used to sign intermediates and must be signed with own public key.
/// </summary>
Root = 0x10,
}
| 32.255814 | 125 | 0.621485 | [
"MIT"
] | enclave-networks/Enclave.Sdk.Api | src/Enclave.Sdk/Data/Authority/CertificatePermittedUse.cs | 1,389 | C# |
using SharpReact.Core;
namespace SharpReact.Wpf.Components
{
public class ScrollViewer<TProps, TElement>: ContentControl<TProps, TElement>
where TProps : Props.ScrollViewer
where TElement : global::System.Windows.Controls.ScrollViewer, new()
{
public override void AssignProperties(ISharpRenderer<global::System.Windows.UIElement> renderer, int level, NewState newState, TProps previous, TProps nextProps)
{
base.AssignProperties(renderer, level, newState, previous, nextProps);
if (nextProps.CanContentScroll.HasValue)
{
Element.CanContentScroll = nextProps.CanContentScroll.Value.Value;
}
if (nextProps.HorizontalScrollBarVisibility.HasValue)
{
Element.HorizontalScrollBarVisibility = nextProps.HorizontalScrollBarVisibility.Value.Value;
}
if (nextProps.VerticalScrollBarVisibility.HasValue)
{
Element.VerticalScrollBarVisibility = nextProps.VerticalScrollBarVisibility.Value.Value;
}
if (nextProps.IsDeferredScrollingEnabled.HasValue)
{
Element.IsDeferredScrollingEnabled = nextProps.IsDeferredScrollingEnabled.Value.Value;
}
if (nextProps.PanningMode.HasValue)
{
Element.PanningMode = nextProps.PanningMode.Value.Value;
}
if (nextProps.PanningDeceleration.HasValue)
{
Element.PanningDeceleration = nextProps.PanningDeceleration.Value.Value;
}
if (nextProps.PanningRatio.HasValue)
{
Element.PanningRatio = nextProps.PanningRatio.Value.Value;
}
if (!ReferenceEquals(previous?.ScrollChanged, null) && ReferenceEquals(nextProps.ScrollChanged, null))
{
Element.ScrollChanged -= nextProps.ScrollChanged;
}
if (ReferenceEquals(previous?.ScrollChanged, null) && !ReferenceEquals(nextProps.ScrollChanged, null))
{
Element.ScrollChanged += nextProps.ScrollChanged;
}
}
}
}
| 35.333333 | 163 | 0.765261 | [
"MIT"
] | MihaMarkic/SharpReact | src/Implementations/Wpf/SharpReact.Wpf/Components/ScrollViewer.cs | 1,802 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using LocalizedText.Internal;
using UnityEngine;
namespace LocalizedText
{
public class TextSet : ScriptableObject
{
[SerializeField] private List<Language> languageList = new List<Language>();
[SerializeField] private Dictionary<string, string> currentLanguageTextSet;
private static SystemLanguage currentSystemLanguage;
public SystemLanguage CurrentSystemLanguage
{
get { return currentSystemLanguage; }
set
{
currentSystemLanguage = value;
var language = FindLanguage(value);
if(language != null)
{
currentLanguageTextSet = language.TextDictionary;
return;
}
language = DefaultLanguage();
if(language!= null)
{
currentLanguageTextSet = language.TextDictionary;
}
}
}
private void OnEnable()
{
CurrentSystemLanguage = Application.systemLanguage;
}
public string this[string key]
{
get { return Text(key); }
}
public string Text(string key)
{
var text = "";
try
{
text = currentLanguageTextSet[key];
}
#pragma warning disable 168
catch(NullReferenceException e)
#pragma warning restore 168
{
LocalTextLogger.Error("No value found for key {0}. Confirm TextSet Inspector.", key);
}
return text;
}
public string Format(string key, params object[] parasmsObjects)
{
return string.Format(Text(key), parasmsObjects);
}
private Language DefaultLanguage()
{
return languageList.FirstOrDefault(langSet => langSet.IsDefaultLanguage);
}
private Language FindLanguage(SystemLanguage systemLanguage)
{
return languageList.FirstOrDefault(langSet => langSet.SystemLanguage == systemLanguage);
}
#region UnityEditor
[Conditional("UNITY_EDITOR")]
public void Clear()
{
languageList.Clear();
}
[Conditional("UNITY_EDITOR")]
public void AddLanguage(Language language)
{
languageList.Add(language);
}
#endregion
[Serializable]
public struct StringKeyValuePair
{
public string Key;
public string Value;
}
[Serializable]
public class Language : ISerializationCallbackReceiver
{
[SerializeField]private SystemLanguage systemLanguage;
[SerializeField] private bool isDefaultLanguage;
[SerializeField] private List<StringKeyValuePair> serializeTextList = new List<StringKeyValuePair>();
private Dictionary<string, string> textDictionary;
public SystemLanguage SystemLanguage
{
get { return systemLanguage; }
}
public Dictionary<string, string> TextDictionary
{
get { return textDictionary; }
}
public bool IsDefaultLanguage
{
get { return isDefaultLanguage; }
}
public Language(SystemLanguage systemLanguage, Dictionary<string, string> textDictionary,
bool isDefaultLanguage = false)
{
this.systemLanguage = systemLanguage;
this.textDictionary = textDictionary;
this.isDefaultLanguage = isDefaultLanguage;
}
public void OnBeforeSerialize()
{
serializeTextList.Clear();
foreach(var keyValuePair in textDictionary)
{
serializeTextList.Add(new StringKeyValuePair()
{
Key = keyValuePair.Key,
Value = keyValuePair.Value
});
}
}
public void OnAfterDeserialize()
{
if(serializeTextList == null)
{
return;
}
textDictionary = serializeTextList.ToDictionary(element => element.Key, element => element.Value);
}
}
}
}
| 28.06135 | 114 | 0.537167 | [
"MIT"
] | fullcorder/UnityLocalizedText | Assets/LocalizedText/Scripts/TextSet.cs | 4,576 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/MSChapp.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
using System.Runtime.InteropServices;
namespace TerraFX.Interop
{
public static unsafe partial class Windows
{
[DllImport("advapi32", ExactSpelling = true)]
[return: NativeTypeName("DWORD")]
public static extern uint MSChapSrvChangePassword([NativeTypeName("PWSTR")] ushort* ServerName, [NativeTypeName("PWSTR")] ushort* UserName, [NativeTypeName("BOOLEAN")] byte LmOldPresent, [NativeTypeName("PLM_OWF_PASSWORD")] LM_OWF_PASSWORD* LmOldOwfPassword, [NativeTypeName("PLM_OWF_PASSWORD")] LM_OWF_PASSWORD* LmNewOwfPassword, [NativeTypeName("PNT_OWF_PASSWORD")] LM_OWF_PASSWORD* NtOldOwfPassword, [NativeTypeName("PNT_OWF_PASSWORD")] LM_OWF_PASSWORD* NtNewOwfPassword);
[DllImport("advapi32", ExactSpelling = true)]
[return: NativeTypeName("DWORD")]
public static extern uint MSChapSrvChangePassword2([NativeTypeName("PWSTR")] ushort* ServerName, [NativeTypeName("PWSTR")] ushort* UserName, [NativeTypeName("PSAMPR_ENCRYPTED_USER_PASSWORD")] SAMPR_ENCRYPTED_USER_PASSWORD* NewPasswordEncryptedWithOldNt, [NativeTypeName("PENCRYPTED_NT_OWF_PASSWORD")] ENCRYPTED_LM_OWF_PASSWORD* OldNtOwfPasswordEncryptedWithNewNt, [NativeTypeName("BOOLEAN")] byte LmPresent, [NativeTypeName("PSAMPR_ENCRYPTED_USER_PASSWORD")] SAMPR_ENCRYPTED_USER_PASSWORD* NewPasswordEncryptedWithOldLm, [NativeTypeName("PENCRYPTED_LM_OWF_PASSWORD")] ENCRYPTED_LM_OWF_PASSWORD* OldLmOwfPasswordEncryptedWithNewLmOrNt);
[NativeTypeName("#define CYPHER_BLOCK_LENGTH 8")]
public const int CYPHER_BLOCK_LENGTH = 8;
}
}
| 76.833333 | 643 | 0.787961 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/MSChapp/Windows.cs | 1,846 | C# |
using System;
using System.Threading.Tasks;
namespace Underscore.Action
{
public interface IDelayComponent
{
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<Task> Delay(System.Action action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, Task> Delay<T1>(Action<T1> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, Task> Delay<T1, T2>(Action<T1, T2> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, T3, Task> Delay<T1, T2, T3>(Action<T1, T2, T3> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, T3, T4, Task> Delay<T1, T2, T3, T4>(Action<T1, T2, T3, T4> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, T3, T4, T5, Task> Delay<T1, T2, T3, T4, T5>(Action<T1, T2, T3, T4, T5> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, T3, T4, T5, T6, Task> Delay<T1, T2, T3, T4, T5, T6>(Action<T1, T2, T3, T4, T5, T6> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, T3, T4, T5, T6, T7, Task> Delay<T1, T2, T3, T4, T5, T6, T7>(Action<T1, T2, T3, T4, T5, T6, T7> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, T3, T4, T5, T6, T7, T8, Task> Delay<T1, T2, T3, T4, T5, T6, T7, T8>(Action<T1, T2, T3, T4, T5, T6, T7, T8> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, Task> Delay<T1, T2, T3, T4, T5, T6, T7, T8, T9>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, Task> Delay<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, Task> Delay<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, Task> Delay<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, Task> Delay<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, Task> Delay<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, Task> Delay<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15> action, int milliseconds);
/// <summary>
/// Creates a delayed version of passed function, delaying passed milliseconds value
/// before executing
/// </summary>
Func<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16, Task> Delay<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16>(Action<T1, T2, T3, T4, T5, T6, T7, T8, T9, T10, T11, T12, T13, T14, T15, T16> action, int milliseconds);
}
}
| 46.747748 | 265 | 0.644247 | [
"MIT"
] | konkked/Underscore.cs | Underscore.cs/Action/Contract/Synch/IDelay.cs | 5,191 | C# |
using System.Collections.Generic;
using JetBrains.Annotations;
namespace MetaBrainz.ListenBrainz.Interfaces;
/// <summary>Information about how many listens a user has submitted over a period of time.</summary>
[PublicAPI]
public interface IUserListeningActivity : IUserStatistics {
/// <summary>The user's listening activity.</summary>
IReadOnlyList<IListenTimeRange>? Activity { get; }
}
| 26.6 | 101 | 0.784461 | [
"MIT"
] | Zastai/ListenBrainz | MetaBrainz.ListenBrainz/Interfaces/IUserListeningActivity.cs | 399 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
using Discord.Addons.MpGame.Collections;
namespace MpGame.Tests
{
internal sealed class TestPile : Pile<ITestCard>, ITestPileEvents
{
private readonly PilePerms _perms;
public TestPile(PilePerms withPerms, IEnumerable<ITestCard> items)
: this(withPerms, items, false)
{
}
public TestPile(PilePerms withPerms, IEnumerable<ITestCard> items, bool initShuffle)
: base(items, initShuffle: initShuffle)
{
_perms = withPerms;
}
public override bool CanBrowse => HasPerm(PilePerms.CanBrowse);
public override bool CanClear => HasPerm(PilePerms.CanClear);
public override bool CanCut => HasPerm(PilePerms.CanCut);
public override bool CanDraw => HasPerm(PilePerms.CanDraw);
public override bool CanDrawBottom => HasPerm(PilePerms.CanDrawBottom);
public override bool CanInsert => HasPerm(PilePerms.CanInsert);
public override bool CanPeek => HasPerm(PilePerms.CanPeek);
public override bool CanPut => HasPerm(PilePerms.CanPut);
public override bool CanPutBottom => HasPerm(PilePerms.CanPutBottom);
public override bool CanShuffle => HasPerm(PilePerms.CanShuffle);
public override bool CanTake => HasPerm(PilePerms.CanTake);
public event EventHandler<EventArgs>? LastRemoveCalled;
protected override void OnLastRemoved()
{
base.OnLastRemoved();
LastRemoveCalled?.Invoke(this, EventArgs.Empty);
}
public event EventHandler<PutEventArgs>? PutCalled;
protected override void OnPut(ITestCard card)
{
base.OnPut(card);
PutCalled?.Invoke(this, new PutEventArgs(card));
}
public Func<IEnumerable<ITestCard>, IEnumerable<ITestCard>>? ShuffleFuncOverride { private get; set; }
public event EventHandler<ShuffleEventArgs>? ShuffleCalled;
protected override IEnumerable<ITestCard> ShuffleItems(IEnumerable<ITestCard> items)
{
var shuffled = (ShuffleFuncOverride is null)
? items.Reverse()
: ShuffleFuncOverride.Invoke(items);
ShuffleCalled?.Invoke(this,
new ShuffleEventArgs(originalSequence: items, newSequence: shuffled));
return shuffled;
}
private bool HasPerm(PilePerms perm) => (_perms & perm) == perm;
}
[Flags]
public enum PilePerms
{
None = 0,
CanBrowse = 1 << 0,
CanClear = 1 << 1,
CanCut = 1 << 2,
CanDraw = 1 << 3,
CanDrawBottom = 1 << 4,
CanInsert = 1 << 5,
CanPeek = 1 << 6,
CanPut = 1 << 7,
CanPutBottom = 1 << 8,
CanShuffle = 1 << 9,
CanTake = 1 << 10,
All = CanBrowse | CanClear | CanCut | CanDraw | CanDrawBottom
| CanInsert | CanPeek | CanPut | CanPutBottom | CanShuffle | CanTake
}
}
| 35.775281 | 110 | 0.605842 | [
"MIT"
] | Joe4evr/Discord.Addons | test/MpGame.Tests/Common/TestPile-1.cs | 3,186 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace ExcelWebProject
{
public interface IExportavelCsvExcel { }
}
| 17.545455 | 44 | 0.792746 | [
"Apache-2.0"
] | Paulofsr/excel-example | ExcelWebProject/ExcelWebProject/IExportavelCsvExcel.cs | 195 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Experimental.Rendering.Universal;
public class Flashlight : Enemy
{
public Transform[] hitPts;
public LayerMask layerMask;
public float hitDistance = 3f;
float tempHitDistance;
// burnout
Light2D light2D;
public float startIntensity = 1f;
public float decaySpeed = 0.1f;
public float scareTime = 3f;
public ParticleSystem DestructionEffect;
// Start is called before the first frame update
void Start()
{
light2D = GetComponent<Light2D>();
light2D.intensity = 0;
}
// Update is called once per frame
void Update()
{
if(light2D.intensity <= 0) return;
for (int i = 0; i < hitPts.Length; i++)
{
RaycastHit2D h = Physics2D.Raycast(transform.position, (hitPts[i].position - transform.position).normalized, hitDistance, layerMask);
Debug.DrawLine(transform.position,(h.point != null) ? (Vector3)h.point : hitPts[i].position, Color.yellow);
if (h.collider != null)
{
Enemy enemy = h.collider.gameObject.GetComponent<Enemy>();
if (enemy)
{
enemy.inLight = true;
enemy.currLightTimer = scareTime;
h.collider.gameObject.transform.localScale = h.collider.gameObject.transform.localScale / 1.01f;
ParticleSystem explosionEffect = Instantiate(DestructionEffect) as ParticleSystem;
explosionEffect.transform.position = h.collider.gameObject.transform.position;
explosionEffect.loop = false;
explosionEffect.Play();
Destroy(h.collider.gameObject, 5f);
}
}
}
if (light2D.intensity > 0f)
{
light2D.intensity -= Time.deltaTime * decaySpeed;
}
}
public void Refresh()
{
light2D.intensity = startIntensity;
}
}
| 25.58209 | 136 | 0.717036 | [
"CC0-1.0"
] | dfields16/GGJ_2021 | Assets/Scripts/Flashlight.cs | 1,714 | C# |
using System;
using DryIoc;
using JetBrains.Annotations;
using LVK.DryIoc;
namespace LVK.Net.Http.Server
{
[PublicAPI]
public class ServicesBootstrapper : IServicesBootstrapper
{
public void Bootstrap(IContainer container)
{
if (container == null)
throw new ArgumentNullException(nameof(container));
container.Bootstrap<LVK.Configuration.ServicesBootstrapper>();
container.Bootstrap<Core.Services.ServicesBootstrapper>();
container.Bootstrap<Logging.ServicesBootstrapper>();
container.Register<IWebServer, WebServer>(Reuse.Singleton);
}
}
} | 25.5 | 74 | 0.668175 | [
"MIT"
] | FeatureToggleStudy/LVK | src/LVK.Net.Http.Server/ServicesBootstrapper.cs | 665 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("SociumApp.Services")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("SociumApp.Services")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cb17308f-8c3f-4a5e-9278-eeed79d81d9a")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.081081 | 84 | 0.745919 | [
"MIT"
] | David-Mavrodiev/Socium | SociumApp/SociumApp.Services/Properties/AssemblyInfo.cs | 1,412 | C# |
using System;
namespace Swiftly.Parsers.ProductInfo.Executable
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Hello World!");
}
}
} | 17.083333 | 48 | 0.570732 | [
"MIT"
] | erickhouse/code-exercise | src/Swiftly.Parsers.ProductInfo.Executable/Program.cs | 207 | C# |
/*
* Copyright(c) 2020 Samsung Electronics Co., Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
using System.Collections.Generic;
using System.ComponentModel;
using Tizen.NUI.BaseComponents;
using Tizen.NUI.Binding;
namespace Tizen.NUI.Components
{
/// <summary>
/// LoadingStyle is a class which saves Loading's ux data.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public class LoadingStyle : ControlStyle
{
/// <summary>The FrameRateSelector bindable property.</summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static readonly BindableProperty FrameRateSelectorProperty = BindableProperty.Create("FrameRateSelector", typeof(Selector<int?>), typeof(LoadingStyle), null, propertyChanged: (bindable, oldValue, newValue) =>
{
((LoadingStyle)bindable).frameRate = ((Selector<int?>)newValue)?.Clone();
},
defaultValueCreator: (bindable) =>
{
return ((LoadingStyle)bindable).frameRate;
});
/// <summary>The LoadingSize bindable property.</summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static readonly BindableProperty LoadingSizeProperty = BindableProperty.Create(nameof(LoadingSize), typeof(Size), typeof(LoadingStyle), null, propertyChanged: (bindable, oldValue, newValue) =>
{
((LoadingStyle)bindable).Size = (Size)newValue;
},
defaultValueCreator: (bindable) =>
{
return ((LoadingStyle)bindable).Size;
});
/// <summary>The Images bindable property.</summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static readonly BindableProperty ImagesProperty = BindableProperty.Create(nameof(Images), typeof(string[]), typeof(LoadingStyle), null, propertyChanged: (bindable, oldValue, newValue) =>
{
((LoadingStyle)bindable).images = newValue == null ? null : new List<string>((string[])newValue);
},
defaultValueCreator: (bindable) => ((LoadingStyle)bindable).images?.ToArray()
);
/// <summary>The Images bindable property.</summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static readonly BindableProperty ImageListProperty = BindableProperty.Create(nameof(ImageList), typeof(IList<string>), typeof(LoadingStyle), null, propertyChanged: (bindable, oldValue, newValue) =>
{
((LoadingStyle)bindable).images = newValue as List<string>;
},
defaultValueCreator: (bindable) => ((LoadingStyle)bindable).images
);
private Selector<int?> frameRate;
private List<string> images;
static LoadingStyle() { }
/// <summary>
/// Creates a new instance of a LoadingStyle.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public LoadingStyle() : base() { }
/// <summary>
/// Creates a new instance of a LoadingStyle with style.
/// </summary>
/// <param name="style">Create LoadingStyle by style customized by user.</param>
/// <since_tizen> 8 </since_tizen>
public LoadingStyle(LoadingStyle style) : base(style)
{
}
/// <summary>
/// Gets or sets loading image resources.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public string[] Images
{
get => (ImageList as List<string>)?.ToArray();
set => SetValue(ImagesProperty, value);
}
/// <summary>
/// Gets loading image resources.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public IList<string> ImageList
{
get
{
if (images == null)
{
images = new List<string>();
}
return GetValue(ImageListProperty) as List<string>;
}
internal set => SetValue(ImageListProperty, value);
}
/// <summary>
/// Gets or sets loading image size.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public Size LoadingSize
{
get => (Size)GetValue(LoadingSizeProperty);
set => SetValue(LoadingSizeProperty, value);
}
/// <summary>
/// Gets or sets loading frame per second.
/// </summary>
/// <since_tizen> 8 </since_tizen>
public Selector<int?> FrameRate
{
get => (Selector<int?>)GetValue(FrameRateSelectorProperty);
set => SetValue(FrameRateSelectorProperty, value);
}
/// <summary>
/// Style's clone function.
/// </summary>
/// <param name="bindableObject">The style that need to copy.</param>
/// <since_tizen> 8 </since_tizen>
public override void CopyFrom(BindableObject bindableObject)
{
base.CopyFrom(bindableObject);
}
}
}
| 37.283784 | 223 | 0.610547 | [
"Apache-2.0",
"MIT"
] | AchoWang/TizenFX | src/Tizen.NUI.Components/Style/LoadingStyle.cs | 5,520 | C# |
using System;
using System.Collections.Generic;
using System.Globalization;
using System.Linq;
namespace TileMapService.MBTiles
{
/// <summary>
/// Represents metadata set from MBTiles database.
/// </summary>
class Metadata
{
private readonly List<MetadataItem> metadataItems;
public Metadata(IEnumerable<MetadataItem> metadata)
{
this.metadataItems = metadata.ToList();
this.Name = GetItem(MetadataItem.KeyName)?.Value;
this.Format = GetItem(MetadataItem.KeyFormat)?.Value;
var bounds = GetItem(MetadataItem.KeyBounds);
if (bounds != null)
{
if (!String.IsNullOrEmpty(bounds.Value))
{
this.Bounds = Models.Bounds.FromMBTilesMetadataString(bounds.Value);
}
}
var center = GetItem(MetadataItem.KeyCenter);
if (center != null)
{
if (!String.IsNullOrEmpty(center.Value))
{
this.Center = Models.GeographicalPointWithZoom.FromMBTilesMetadataString(center.Value);
}
}
var minzoom = GetItem(MetadataItem.KeyMinZoom);
if (minzoom != null)
{
if (Int32.TryParse(minzoom.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int minZoomValue))
{
this.MinZoom = minZoomValue;
}
}
var maxzoom = GetItem(MetadataItem.KeyMaxZoom);
if (maxzoom != null)
{
if (Int32.TryParse(maxzoom.Value, NumberStyles.Integer, CultureInfo.InvariantCulture, out int maxZoomValue))
{
this.MaxZoom = maxZoomValue;
}
}
this.Attribution = GetItem(MetadataItem.KeyAttribution)?.Value;
this.Description = GetItem(MetadataItem.KeyDescription)?.Value;
this.Type = GetItem(MetadataItem.KeyType)?.Value;
this.Version = GetItem(MetadataItem.KeyVersion)?.Value;
this.Json = GetItem(MetadataItem.KeyJson)?.Value;
}
/// <summary>
/// The human-readable name of the tileset.
/// </summary>
public string Name { get; private set; }
/// <summary>
/// The file format of the tile data: pbf, jpg, png, webp, or an IETF media type for other formats.
/// </summary>
public string Format { get; private set; }
/// <summary>
/// The maximum extent of the rendered map area (as WGS 84 latitude and longitude values, in the OpenLayers Bounds format: left, bottom, right, top), string of comma-separated numbers.
/// </summary>
public Models.Bounds Bounds { get; private set; }
/// <summary>
/// The longitude, latitude, and zoom level of the default view of the map, string of comma-separated numbers.
/// </summary>
public Models.GeographicalPointWithZoom Center { get; private set; }
/// <summary>
/// The lowest zoom level (number) for which the tileset provides data.
/// </summary>
public int? MinZoom { get; private set; }
/// <summary>
/// The highest zoom level (number) for which the tileset provides data.
/// </summary>
public int? MaxZoom { get; private set; }
/// <summary>
/// An attribution (HTML) string, which explains the sources of data and/or style for the map.
/// </summary>
public string Attribution { get; private set; }
/// <summary>
/// A description of the tileset content.
/// </summary>
public string Description { get; private set; }
/// <summary>
/// Type of tileset: "overlay" or "baselayer".
/// </summary>
public string Type { get; private set; }
/// <summary>
/// The version (revision) of the tileset.
/// </summary>
/// <remarks>
/// Version is a number, according to specification, but actually can be a string in real datasets.
/// </remarks>
public string Version { get; private set; }
/// <summary>
/// Lists the layers that appear in the vector tiles and the names and types of the attributes of features that appear in those layers in case of pbf format.
/// </summary>
/// <remarks>
/// See https://github.com/mapbox/mbtiles-spec/blob/master/1.3/spec.md#vector-tileset-metadata
/// </remarks>
public string Json { get; private set; }
private MetadataItem GetItem(string name)
{
return this.metadataItems.FirstOrDefault(i => i.Name == name);
}
}
}
| 36.484848 | 192 | 0.571221 | [
"MIT"
] | apdevelop/tile-map-service-net5 | Src/TileMapService/MBTiles/Metadata.cs | 4,818 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: EntityType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type Managed App Protection.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class ManagedAppProtection : ManagedAppPolicy
{
///<summary>
/// The internal ManagedAppProtection constructor
///</summary>
protected internal ManagedAppProtection()
{
// Don't allow initialization of abstract entity types
}
/// <summary>
/// Gets or sets allowed data ingestion locations.
/// Data storage locations where a user may store managed data.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "allowedDataIngestionLocations", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<ManagedAppDataIngestionLocation> AllowedDataIngestionLocations { get; set; }
/// <summary>
/// Gets or sets allowed data storage locations.
/// Data storage locations where a user may store managed data.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "allowedDataStorageLocations", Required = Newtonsoft.Json.Required.Default)]
public IEnumerable<ManagedAppDataStorageLocation> AllowedDataStorageLocations { get; set; }
/// <summary>
/// Gets or sets allowed inbound data transfer sources.
/// Sources from which data is allowed to be transferred. Possible values are: allApps, managedApps, none.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "allowedInboundDataTransferSources", Required = Newtonsoft.Json.Required.Default)]
public ManagedAppDataTransferLevel? AllowedInboundDataTransferSources { get; set; }
/// <summary>
/// Gets or sets allowed outbound clipboard sharing exception length.
/// Specify the number of characters that may be cut or copied from Org data and accounts to any application. This setting overrides the AllowedOutboundClipboardSharingLevel restriction. Default value of '0' means no exception is allowed.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "allowedOutboundClipboardSharingExceptionLength", Required = Newtonsoft.Json.Required.Default)]
public Int32? AllowedOutboundClipboardSharingExceptionLength { get; set; }
/// <summary>
/// Gets or sets allowed outbound clipboard sharing level.
/// The level to which the clipboard may be shared between apps on the managed device. Possible values are: allApps, managedAppsWithPasteIn, managedApps, blocked.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "allowedOutboundClipboardSharingLevel", Required = Newtonsoft.Json.Required.Default)]
public ManagedAppClipboardSharingLevel? AllowedOutboundClipboardSharingLevel { get; set; }
/// <summary>
/// Gets or sets allowed outbound data transfer destinations.
/// Destinations to which data is allowed to be transferred. Possible values are: allApps, managedApps, none.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "allowedOutboundDataTransferDestinations", Required = Newtonsoft.Json.Required.Default)]
public ManagedAppDataTransferLevel? AllowedOutboundDataTransferDestinations { get; set; }
/// <summary>
/// Gets or sets app action if device compliance required.
/// Defines a managed app behavior, either block or wipe, when the device is either rooted or jailbroken, if DeviceComplianceRequired is set to true. Possible values are: block, wipe, warn.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "appActionIfDeviceComplianceRequired", Required = Newtonsoft.Json.Required.Default)]
public ManagedAppRemediationAction? AppActionIfDeviceComplianceRequired { get; set; }
/// <summary>
/// Gets or sets app action if maximum pin retries exceeded.
/// Defines a managed app behavior, either block or wipe, based on maximum number of incorrect pin retry attempts. Possible values are: block, wipe, warn.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "appActionIfMaximumPinRetriesExceeded", Required = Newtonsoft.Json.Required.Default)]
public ManagedAppRemediationAction? AppActionIfMaximumPinRetriesExceeded { get; set; }
/// <summary>
/// Gets or sets app action if unable to authenticate user.
/// If set, it will specify what action to take in the case where the user is unable to checkin because their authentication token is invalid. This happens when the user is deleted or disabled in AAD. Possible values are: block, wipe, warn.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "appActionIfUnableToAuthenticateUser", Required = Newtonsoft.Json.Required.Default)]
public ManagedAppRemediationAction? AppActionIfUnableToAuthenticateUser { get; set; }
/// <summary>
/// Gets or sets block data ingestion into organization documents.
/// Indicates whether a user can bring data into org documents.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "blockDataIngestionIntoOrganizationDocuments", Required = Newtonsoft.Json.Required.Default)]
public bool? BlockDataIngestionIntoOrganizationDocuments { get; set; }
/// <summary>
/// Gets or sets contact sync blocked.
/// Indicates whether contacts can be synced to the user's device.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "contactSyncBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? ContactSyncBlocked { get; set; }
/// <summary>
/// Gets or sets data backup blocked.
/// Indicates whether the backup of a managed app's data is blocked.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "dataBackupBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? DataBackupBlocked { get; set; }
/// <summary>
/// Gets or sets device compliance required.
/// Indicates whether device compliance is required.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "deviceComplianceRequired", Required = Newtonsoft.Json.Required.Default)]
public bool? DeviceComplianceRequired { get; set; }
/// <summary>
/// Gets or sets dialer restriction level.
/// The classes of dialer apps that are allowed to click-to-open a phone number. Possible values are: allApps, managedApps, customApp, blocked.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "dialerRestrictionLevel", Required = Newtonsoft.Json.Required.Default)]
public ManagedAppPhoneNumberRedirectLevel? DialerRestrictionLevel { get; set; }
/// <summary>
/// Gets or sets disable app pin if device pin is set.
/// Indicates whether use of the app pin is required if the device pin is set.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "disableAppPinIfDevicePinIsSet", Required = Newtonsoft.Json.Required.Default)]
public bool? DisableAppPinIfDevicePinIsSet { get; set; }
/// <summary>
/// Gets or sets fingerprint blocked.
/// Indicates whether use of the fingerprint reader is allowed in place of a pin if PinRequired is set to True.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "fingerprintBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? FingerprintBlocked { get; set; }
/// <summary>
/// Gets or sets managed browser.
/// Indicates in which managed browser(s) that internet links should be opened. When this property is configured, ManagedBrowserToOpenLinksRequired should be true. Possible values are: notConfigured, microsoftEdge.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "managedBrowser", Required = Newtonsoft.Json.Required.Default)]
public ManagedBrowserType? ManagedBrowser { get; set; }
/// <summary>
/// Gets or sets managed browser to open links required.
/// Indicates whether internet links should be opened in the managed browser app, or any custom browser specified by CustomBrowserProtocol (for iOS) or CustomBrowserPackageId/CustomBrowserDisplayName (for Android)
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "managedBrowserToOpenLinksRequired", Required = Newtonsoft.Json.Required.Default)]
public bool? ManagedBrowserToOpenLinksRequired { get; set; }
/// <summary>
/// Gets or sets maximum allowed device threat level.
/// Maximum allowed device threat level, as reported by the MTD app. Possible values are: notConfigured, secured, low, medium, high.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "maximumAllowedDeviceThreatLevel", Required = Newtonsoft.Json.Required.Default)]
public ManagedAppDeviceThreatLevel? MaximumAllowedDeviceThreatLevel { get; set; }
/// <summary>
/// Gets or sets maximum pin retries.
/// Maximum number of incorrect pin retry attempts before the managed app is either blocked or wiped.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "maximumPinRetries", Required = Newtonsoft.Json.Required.Default)]
public Int32? MaximumPinRetries { get; set; }
/// <summary>
/// Gets or sets minimum pin length.
/// Minimum pin length required for an app-level pin if PinRequired is set to True
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "minimumPinLength", Required = Newtonsoft.Json.Required.Default)]
public Int32? MinimumPinLength { get; set; }
/// <summary>
/// Gets or sets minimum required app version.
/// Versions less than the specified version will block the managed app from accessing company data.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "minimumRequiredAppVersion", Required = Newtonsoft.Json.Required.Default)]
public string MinimumRequiredAppVersion { get; set; }
/// <summary>
/// Gets or sets minimum required os version.
/// Versions less than the specified version will block the managed app from accessing company data.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "minimumRequiredOsVersion", Required = Newtonsoft.Json.Required.Default)]
public string MinimumRequiredOsVersion { get; set; }
/// <summary>
/// Gets or sets minimum warning app version.
/// Versions less than the specified version will result in warning message on the managed app.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "minimumWarningAppVersion", Required = Newtonsoft.Json.Required.Default)]
public string MinimumWarningAppVersion { get; set; }
/// <summary>
/// Gets or sets minimum warning os version.
/// Versions less than the specified version will result in warning message on the managed app from accessing company data.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "minimumWarningOsVersion", Required = Newtonsoft.Json.Required.Default)]
public string MinimumWarningOsVersion { get; set; }
/// <summary>
/// Gets or sets minimum wipe app version.
/// Versions less than or equal to the specified version will wipe the managed app and the associated company data.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "minimumWipeAppVersion", Required = Newtonsoft.Json.Required.Default)]
public string MinimumWipeAppVersion { get; set; }
/// <summary>
/// Gets or sets minimum wipe os version.
/// Versions less than or equal to the specified version will wipe the managed app and the associated company data.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "minimumWipeOsVersion", Required = Newtonsoft.Json.Required.Default)]
public string MinimumWipeOsVersion { get; set; }
/// <summary>
/// Gets or sets mobile threat defense remediation action.
/// Determines what action to take if the mobile threat defense threat threshold isn't met. Warn isn't a supported value for this property. Possible values are: block, wipe, warn.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "mobileThreatDefenseRemediationAction", Required = Newtonsoft.Json.Required.Default)]
public ManagedAppRemediationAction? MobileThreatDefenseRemediationAction { get; set; }
/// <summary>
/// Gets or sets notification restriction.
/// Specify app notification restriction. Possible values are: allow, blockOrganizationalData, block.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "notificationRestriction", Required = Newtonsoft.Json.Required.Default)]
public ManagedAppNotificationRestriction? NotificationRestriction { get; set; }
/// <summary>
/// Gets or sets organizational credentials required.
/// Indicates whether organizational credentials are required for app use.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "organizationalCredentialsRequired", Required = Newtonsoft.Json.Required.Default)]
public bool? OrganizationalCredentialsRequired { get; set; }
/// <summary>
/// Gets or sets period before pin reset.
/// TimePeriod before the all-level pin must be reset if PinRequired is set to True.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "periodBeforePinReset", Required = Newtonsoft.Json.Required.Default)]
public Duration PeriodBeforePinReset { get; set; }
/// <summary>
/// Gets or sets period offline before access check.
/// The period after which access is checked when the device is not connected to the internet.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "periodOfflineBeforeAccessCheck", Required = Newtonsoft.Json.Required.Default)]
public Duration PeriodOfflineBeforeAccessCheck { get; set; }
/// <summary>
/// Gets or sets period offline before wipe is enforced.
/// The amount of time an app is allowed to remain disconnected from the internet before all managed data it is wiped.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "periodOfflineBeforeWipeIsEnforced", Required = Newtonsoft.Json.Required.Default)]
public Duration PeriodOfflineBeforeWipeIsEnforced { get; set; }
/// <summary>
/// Gets or sets period online before access check.
/// The period after which access is checked when the device is connected to the internet.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "periodOnlineBeforeAccessCheck", Required = Newtonsoft.Json.Required.Default)]
public Duration PeriodOnlineBeforeAccessCheck { get; set; }
/// <summary>
/// Gets or sets pin character set.
/// Character set which may be used for an app-level pin if PinRequired is set to True. Possible values are: numeric, alphanumericAndSymbol.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "pinCharacterSet", Required = Newtonsoft.Json.Required.Default)]
public ManagedAppPinCharacterSet? PinCharacterSet { get; set; }
/// <summary>
/// Gets or sets pin required.
/// Indicates whether an app-level pin is required.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "pinRequired", Required = Newtonsoft.Json.Required.Default)]
public bool? PinRequired { get; set; }
/// <summary>
/// Gets or sets pin required instead of biometric timeout.
/// Timeout in minutes for an app pin instead of non biometrics passcode
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "pinRequiredInsteadOfBiometricTimeout", Required = Newtonsoft.Json.Required.Default)]
public Duration PinRequiredInsteadOfBiometricTimeout { get; set; }
/// <summary>
/// Gets or sets previous pin block count.
/// Requires a pin to be unique from the number specified in this property.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "previousPinBlockCount", Required = Newtonsoft.Json.Required.Default)]
public Int32? PreviousPinBlockCount { get; set; }
/// <summary>
/// Gets or sets print blocked.
/// Indicates whether printing is allowed from managed apps.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "printBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? PrintBlocked { get; set; }
/// <summary>
/// Gets or sets save as blocked.
/// Indicates whether users may use the 'Save As' menu item to save a copy of protected files.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "saveAsBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? SaveAsBlocked { get; set; }
/// <summary>
/// Gets or sets simple pin blocked.
/// Indicates whether simplePin is blocked.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "simplePinBlocked", Required = Newtonsoft.Json.Required.Default)]
public bool? SimplePinBlocked { get; set; }
}
}
| 61.356037 | 248 | 0.687708 | [
"MIT"
] | GeertVL/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/model/ManagedAppProtection.cs | 19,818 | C# |
namespace MvcBootstrap.Web.Mvc.Controllers
{
public static class BootstrapActionName
{
public const string List = "List";
public const string Create = "Create";
public const string Read = "Read";
public const string Update = "Update";
public const string Delete = "Delete";
}
}
| 20.9375 | 46 | 0.629851 | [
"MIT"
] | carlgieringer/MvcBootstrap | MvcBootstrap/Web/Mvc/Controllers/BootstrapActionName.cs | 337 | C# |
using System;
using System.ComponentModel;
namespace PhotoStoryToBloomConverter.Utilities
{
public static class EnumExtensions
{
public static string ToDescriptionString(this Enum val)
{
DescriptionAttribute[] attributes = (DescriptionAttribute[]) val
.GetType()
.GetField(val.ToString())
.GetCustomAttributes(typeof(DescriptionAttribute), false);
return attributes.Length > 0 ? attributes[0].Description : string.Empty;
}
}
}
| 24.052632 | 75 | 0.752735 | [
"MIT"
] | BloomBooks/PhotoStoryToBloomConverter | PhotoStoryToBloomConverter/Utilities/EnumExtensions.cs | 459 | C# |
/*
* Intersight REST API
*
* This is Intersight REST API
*
* OpenAPI spec version: 0.1.0-559
*
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using RestSharp;
using intersight.Client;
using intersight.Model;
namespace intersight.Api
{
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public interface IIamDomainGroupApi : IApiAccessor
{
#region Synchronous Operations
/// <summary>
/// Get a list of 'iamDomainGroup' instances
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>IamDomainGroupList</returns>
IamDomainGroupList IamDomainGroupsGet (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null);
/// <summary>
/// Get a list of 'iamDomainGroup' instances
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>ApiResponse of IamDomainGroupList</returns>
ApiResponse<IamDomainGroupList> IamDomainGroupsGetWithHttpInfo (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null);
/// <summary>
/// Get a specific instance of 'iamDomainGroup'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the iamDomainGroup instance.</param>
/// <returns>IamDomainGroup</returns>
IamDomainGroup IamDomainGroupsMoidGet (string moid);
/// <summary>
/// Get a specific instance of 'iamDomainGroup'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the iamDomainGroup instance.</param>
/// <returns>ApiResponse of IamDomainGroup</returns>
ApiResponse<IamDomainGroup> IamDomainGroupsMoidGetWithHttpInfo (string moid);
#endregion Synchronous Operations
#region Asynchronous Operations
/// <summary>
/// Get a list of 'iamDomainGroup' instances
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>Task of IamDomainGroupList</returns>
System.Threading.Tasks.Task<IamDomainGroupList> IamDomainGroupsGetAsync (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null);
/// <summary>
/// Get a list of 'iamDomainGroup' instances
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>Task of ApiResponse (IamDomainGroupList)</returns>
System.Threading.Tasks.Task<ApiResponse<IamDomainGroupList>> IamDomainGroupsGetAsyncWithHttpInfo (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null);
/// <summary>
/// Get a specific instance of 'iamDomainGroup'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the iamDomainGroup instance.</param>
/// <returns>Task of IamDomainGroup</returns>
System.Threading.Tasks.Task<IamDomainGroup> IamDomainGroupsMoidGetAsync (string moid);
/// <summary>
/// Get a specific instance of 'iamDomainGroup'
/// </summary>
/// <remarks>
///
/// </remarks>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the iamDomainGroup instance.</param>
/// <returns>Task of ApiResponse (IamDomainGroup)</returns>
System.Threading.Tasks.Task<ApiResponse<IamDomainGroup>> IamDomainGroupsMoidGetAsyncWithHttpInfo (string moid);
#endregion Asynchronous Operations
}
/// <summary>
/// Represents a collection of functions to interact with the API endpoints
/// </summary>
public partial class IamDomainGroupApi : IIamDomainGroupApi
{
private intersight.Client.ExceptionFactory _exceptionFactory = (name, response) => null;
/// <summary>
/// Initializes a new instance of the <see cref="IamDomainGroupApi"/> class.
/// </summary>
/// <returns></returns>
public IamDomainGroupApi(String basePath)
{
this.Configuration = new Configuration(new ApiClient(basePath));
ExceptionFactory = intersight.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Initializes a new instance of the <see cref="IamDomainGroupApi"/> class
/// using Configuration object
/// </summary>
/// <param name="configuration">An instance of Configuration</param>
/// <returns></returns>
public IamDomainGroupApi(Configuration configuration = null)
{
if (configuration == null) // use the default one in Configuration
this.Configuration = Configuration.Default;
else
this.Configuration = configuration;
ExceptionFactory = intersight.Client.Configuration.DefaultExceptionFactory;
// ensure API client has configuration ready
if (Configuration.ApiClient.Configuration == null)
{
this.Configuration.ApiClient.Configuration = this.Configuration;
}
}
/// <summary>
/// Gets the base path of the API client.
/// </summary>
/// <value>The base path</value>
public String GetBasePath()
{
return this.Configuration.ApiClient.RestClient.BaseUrl.ToString();
}
/// <summary>
/// Sets the base path of the API client.
/// </summary>
/// <value>The base path</value>
[Obsolete("SetBasePath is deprecated, please do 'Configuration.ApiClient = new ApiClient(\"http://new-path\")' instead.")]
public void SetBasePath(String basePath)
{
// do nothing
}
/// <summary>
/// Gets or sets the configuration object
/// </summary>
/// <value>An instance of the Configuration</value>
public Configuration Configuration {get; set;}
/// <summary>
/// Provides a factory method hook for the creation of exceptions.
/// </summary>
public intersight.Client.ExceptionFactory ExceptionFactory
{
get
{
if (_exceptionFactory != null && _exceptionFactory.GetInvocationList().Length > 1)
{
throw new InvalidOperationException("Multicast delegate for ExceptionFactory is unsupported.");
}
return _exceptionFactory;
}
set { _exceptionFactory = value; }
}
/// <summary>
/// Gets the default header.
/// </summary>
/// <returns>Dictionary of HTTP header</returns>
[Obsolete("DefaultHeader is deprecated, please use Configuration.DefaultHeader instead.")]
public Dictionary<String, String> DefaultHeader()
{
return this.Configuration.DefaultHeader;
}
/// <summary>
/// Add default header.
/// </summary>
/// <param name="key">Header field name.</param>
/// <param name="value">Header field value.</param>
/// <returns></returns>
[Obsolete("AddDefaultHeader is deprecated, please use Configuration.AddDefaultHeader instead.")]
public void AddDefaultHeader(string key, string value)
{
this.Configuration.AddDefaultHeader(key, value);
}
/// <summary>
/// Get a list of 'iamDomainGroup' instances
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>IamDomainGroupList</returns>
public IamDomainGroupList IamDomainGroupsGet (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null)
{
ApiResponse<IamDomainGroupList> localVarResponse = IamDomainGroupsGetWithHttpInfo(count, inlinecount, top, skip, filter, select, orderby, expand);
return localVarResponse.Data;
}
/// <summary>
/// Get a list of 'iamDomainGroup' instances
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>ApiResponse of IamDomainGroupList</returns>
public ApiResponse< IamDomainGroupList > IamDomainGroupsGetWithHttpInfo (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null)
{
var localVarPath = "/iam/DomainGroups";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (count != null) localVarQueryParams.Add("$count", Configuration.ApiClient.ParameterToString(count)); // query parameter
if (inlinecount != null) localVarQueryParams.Add("$inlinecount", Configuration.ApiClient.ParameterToString(inlinecount)); // query parameter
if (top != null) localVarQueryParams.Add("$top", Configuration.ApiClient.ParameterToString(top)); // query parameter
if (skip != null) localVarQueryParams.Add("$skip", Configuration.ApiClient.ParameterToString(skip)); // query parameter
if (filter != null) localVarQueryParams.Add("$filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
if (select != null) localVarQueryParams.Add("$select", Configuration.ApiClient.ParameterToString(select)); // query parameter
if (orderby != null) localVarQueryParams.Add("$orderby", Configuration.ApiClient.ParameterToString(orderby)); // query parameter
if (expand != null) localVarQueryParams.Add("$expand", Configuration.ApiClient.ParameterToString(expand)); // query parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("IamDomainGroupsGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<IamDomainGroupList>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(IamDomainGroupList) Configuration.ApiClient.Deserialize(localVarResponse, typeof(IamDomainGroupList)));
}
/// <summary>
/// Get a list of 'iamDomainGroup' instances
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>Task of IamDomainGroupList</returns>
public async System.Threading.Tasks.Task<IamDomainGroupList> IamDomainGroupsGetAsync (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null)
{
ApiResponse<IamDomainGroupList> localVarResponse = await IamDomainGroupsGetAsyncWithHttpInfo(count, inlinecount, top, skip, filter, select, orderby, expand);
return localVarResponse.Data;
}
/// <summary>
/// Get a list of 'iamDomainGroup' instances
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="count">The $count query option allows clients to request a count of the matching resources. (optional)</param>
/// <param name="inlinecount">The $inlinecount query option allows clients to request an inline count of the matching resources included with the resources in the response (optional)</param>
/// <param name="top">The max number of records to return (optional)</param>
/// <param name="skip">The number of records to skip (optional)</param>
/// <param name="filter">Filter criteria for records to return. A URI with a $filter System Query Option identifies a subset of the Entries from the Collection of Entries identified by the Resource Path section of the URI. The subset is determined by selecting only the Entries that satisfy the predicate expression specified by the query option. The expression language that is used in $filter operators supports references to properties and literals. The literal values can be strings enclosed in single quotes, numbers and boolean values (true or false) or any of the additional literal representations shown in the Abstract Type System section. Query examples: $filter=Name eq 'Bob' $filter=Tags/any(t: t/Key eq 'Site') $filter=Tags/any(t: t/Key eq 'Site' and t/Value eq 'London') (optional)</param>
/// <param name="select">Specifies a subset of properties to return (optional)</param>
/// <param name="orderby">Determines what values are used to order a collection of records (optional)</param>
/// <param name="expand">Specify additional attributes or related records to return. Supports only 'DisplayNames' attribute now. Query examples: $expand=DisplayNames (optional)</param>
/// <returns>Task of ApiResponse (IamDomainGroupList)</returns>
public async System.Threading.Tasks.Task<ApiResponse<IamDomainGroupList>> IamDomainGroupsGetAsyncWithHttpInfo (bool? count = null, string inlinecount = null, int? top = null, int? skip = null, string filter = null, string select = null, string orderby = null, string expand = null)
{
var localVarPath = "/iam/DomainGroups";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (count != null) localVarQueryParams.Add("$count", Configuration.ApiClient.ParameterToString(count)); // query parameter
if (inlinecount != null) localVarQueryParams.Add("$inlinecount", Configuration.ApiClient.ParameterToString(inlinecount)); // query parameter
if (top != null) localVarQueryParams.Add("$top", Configuration.ApiClient.ParameterToString(top)); // query parameter
if (skip != null) localVarQueryParams.Add("$skip", Configuration.ApiClient.ParameterToString(skip)); // query parameter
if (filter != null) localVarQueryParams.Add("$filter", Configuration.ApiClient.ParameterToString(filter)); // query parameter
if (select != null) localVarQueryParams.Add("$select", Configuration.ApiClient.ParameterToString(select)); // query parameter
if (orderby != null) localVarQueryParams.Add("$orderby", Configuration.ApiClient.ParameterToString(orderby)); // query parameter
if (expand != null) localVarQueryParams.Add("$expand", Configuration.ApiClient.ParameterToString(expand)); // query parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("IamDomainGroupsGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<IamDomainGroupList>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(IamDomainGroupList) Configuration.ApiClient.Deserialize(localVarResponse, typeof(IamDomainGroupList)));
}
/// <summary>
/// Get a specific instance of 'iamDomainGroup'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the iamDomainGroup instance.</param>
/// <returns>IamDomainGroup</returns>
public IamDomainGroup IamDomainGroupsMoidGet (string moid)
{
ApiResponse<IamDomainGroup> localVarResponse = IamDomainGroupsMoidGetWithHttpInfo(moid);
return localVarResponse.Data;
}
/// <summary>
/// Get a specific instance of 'iamDomainGroup'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the iamDomainGroup instance.</param>
/// <returns>ApiResponse of IamDomainGroup</returns>
public ApiResponse< IamDomainGroup > IamDomainGroupsMoidGetWithHttpInfo (string moid)
{
// verify the required parameter 'moid' is set
if (moid == null)
throw new ApiException(400, "Missing required parameter 'moid' when calling IamDomainGroupApi->IamDomainGroupsMoidGet");
var localVarPath = "/iam/DomainGroups/{moid}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (moid != null) localVarPathParams.Add("moid", Configuration.ApiClient.ParameterToString(moid)); // path parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) Configuration.ApiClient.CallApi(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("IamDomainGroupsMoidGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<IamDomainGroup>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(IamDomainGroup) Configuration.ApiClient.Deserialize(localVarResponse, typeof(IamDomainGroup)));
}
/// <summary>
/// Get a specific instance of 'iamDomainGroup'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the iamDomainGroup instance.</param>
/// <returns>Task of IamDomainGroup</returns>
public async System.Threading.Tasks.Task<IamDomainGroup> IamDomainGroupsMoidGetAsync (string moid)
{
ApiResponse<IamDomainGroup> localVarResponse = await IamDomainGroupsMoidGetAsyncWithHttpInfo(moid);
return localVarResponse.Data;
}
/// <summary>
/// Get a specific instance of 'iamDomainGroup'
/// </summary>
/// <exception cref="intersight.Client.ApiException">Thrown when fails to make API call</exception>
/// <param name="moid">The moid of the iamDomainGroup instance.</param>
/// <returns>Task of ApiResponse (IamDomainGroup)</returns>
public async System.Threading.Tasks.Task<ApiResponse<IamDomainGroup>> IamDomainGroupsMoidGetAsyncWithHttpInfo (string moid)
{
// verify the required parameter 'moid' is set
if (moid == null)
throw new ApiException(400, "Missing required parameter 'moid' when calling IamDomainGroupApi->IamDomainGroupsMoidGet");
var localVarPath = "/iam/DomainGroups/{moid}";
var localVarPathParams = new Dictionary<String, String>();
var localVarQueryParams = new Dictionary<String, String>();
var localVarHeaderParams = new Dictionary<String, String>(Configuration.DefaultHeader);
var localVarFormParams = new Dictionary<String, String>();
var localVarFileParams = new Dictionary<String, FileParameter>();
Object localVarPostBody = null;
// to determine the Content-Type header
String[] localVarHttpContentTypes = new String[] {
"application/json"
};
String localVarHttpContentType = Configuration.ApiClient.SelectHeaderContentType(localVarHttpContentTypes);
// to determine the Accept header
String[] localVarHttpHeaderAccepts = new String[] {
"application/json"
};
String localVarHttpHeaderAccept = Configuration.ApiClient.SelectHeaderAccept(localVarHttpHeaderAccepts);
if (localVarHttpHeaderAccept != null)
localVarHeaderParams.Add("Accept", localVarHttpHeaderAccept);
if (moid != null) localVarPathParams.Add("moid", Configuration.ApiClient.ParameterToString(moid)); // path parameter
// make the HTTP request
IRestResponse localVarResponse = (IRestResponse) await Configuration.ApiClient.CallApiAsync(localVarPath,
Method.GET, localVarQueryParams, localVarPostBody, localVarHeaderParams, localVarFormParams, localVarFileParams,
localVarPathParams, localVarHttpContentType);
int localVarStatusCode = (int) localVarResponse.StatusCode;
if (ExceptionFactory != null)
{
Exception exception = ExceptionFactory("IamDomainGroupsMoidGet", localVarResponse);
if (exception != null) throw exception;
}
return new ApiResponse<IamDomainGroup>(localVarStatusCode,
localVarResponse.Headers.ToDictionary(x => x.Name, x => x.Value.ToString()),
(IamDomainGroup) Configuration.ApiClient.Deserialize(localVarResponse, typeof(IamDomainGroup)));
}
}
}
| 70.607843 | 859 | 0.678246 | [
"Apache-2.0"
] | CiscoUcs/intersight-powershell | csharp/swaggerClient/src/intersight/Api/IamDomainGroupApi.cs | 39,627 | C# |
using Application.Common.Interfaces;
using Application.Common.Queries;
using Application.Dtos;
using AutoMapper;
using AutoMapper.QueryableExtensions;
using MediatR;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
namespace Application.Features.Communities.Queries
{
public class GetAllCommunitiesQuery : IRequest<Response<CommunityDTO>>
{
}
public class GetAllCommunitiesQueryHandler : IRequestHandler<GetAllCommunitiesQuery, Response<CommunityDTO>>
{
private readonly IApplicationDbContext _context;
private readonly IMapper _mapper;
public GetAllCommunitiesQueryHandler(IApplicationDbContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task<Response<CommunityDTO>> Handle(GetAllCommunitiesQuery request, CancellationToken cancellationToken)
{
return new Response<CommunityDTO>() {Data = _context.Communities
.OrderBy(community => community.Name)
.ProjectTo<CommunityDTO>(_mapper.ConfigurationProvider)
.ToList()
};
}
}
}
| 30.268293 | 125 | 0.707494 | [
"MIT"
] | micbelgique/SpatialAnchorForCommunities | WebSolution/Application/Features/Communities/Queries/GetAllCommunitiesQuery.cs | 1,243 | C# |
namespace QuickView.Services
{
using QuickView.Services.Feeds;
using System.Collections.Generic;
public class AddFeedRequest : IFeedRequest
{
public string Name { get; set; }
public string Source { get; set; }
public Dictionary<string, string> Subjects { get; set; }
}
} | 24.384615 | 64 | 0.652997 | [
"MIT"
] | smithderekm/quickview | src/QuickView.Services/Feeds/AddFeedRequest.cs | 319 | C# |
/*
Copyright (c) 2013, 2014 Paolo Patierno
All rights reserved. This program and the accompanying materials
are made available under the terms of the Eclipse Public License v1.0
and Eclipse Distribution License v1.0 which accompany this distribution.
The Eclipse Public License is available at
http://www.eclipse.org/legal/epl-v10.html
and the Eclipse Distribution License is available at
http://www.eclipse.org/org/documents/edl-v10.php.
Contributors:
Paolo Patierno - initial API and implementation and/or initial documentation
*/
using System;
using System.Text;
using System.Threading.Tasks;
using M2Mqtt;
namespace uPLibrary.Networking.M2Mqtt
{
/// <summary>
/// Interface for channel under MQTT library
/// </summary>
public interface IMqttNetworkChannel
{
/// <summary>
/// Data available on channel
/// </summary>
bool DataAvailable { get; }
/// <summary>
/// Receive data from the network channel
/// </summary>
/// <param name="buffer">Data buffer for receiving data</param>
/// <returns>Number of bytes received</returns>
int Receive(byte[] buffer);
/// <summary>
/// Receive data from the network channel with a specified timeout
/// </summary>
/// <param name="buffer">Data buffer for receiving data</param>
/// <param name="timeout">Timeout on receiving (in milliseconds)</param>
/// <returns>Number of bytes received</returns>
int Receive(byte[] buffer, int timeout);
/// <summary>
/// Send data on the network channel to the broker
/// </summary>
/// <param name="buffer">Data buffer to send</param>
/// <returns>Number of byte sent</returns>
int Send(byte[] buffer);
/// <summary>
/// Close the network channel
/// </summary>
void Close();
/// <summary>
/// Connect to remote server
/// </summary>
Task<M2MqttConnectResultType> Connect(TimeSpan connectTimeout);
/// <summary>
/// Accept client connection
/// </summary>
void Accept();
}
}
| 30.444444 | 80 | 0.621807 | [
"EPL-1.0"
] | toomasz/paho.mqtt.m2mqtt | M2Mqtt/IMqttNetworkChannel.cs | 2,194 | C# |
namespace Machete.X12Schema.V5010
{
using X12;
public interface Loop2010BA_837I :
X12Layout
{
Segment<NM1> Subscriber { get; }
Segment<N3> Address { get; }
Segment<N4> GeographicInformation { get; }
Segment<DMG> DemographicInformation { get; }
Segment<REF> SecondaryIdentification { get; }
Segment<REF> PropertyAndCasualtyClaimNumber { get; }
}
} | 22.190476 | 60 | 0.570815 | [
"Apache-2.0"
] | ahives/Machete | src/Machete.X12Schema/V5010/Layouts/Loop2010BA_837I.cs | 468 | C# |
using UnityEngine;
using System.Collections;
public class UM_PushRegistrationResult : UM_BaseResult {
private string _deviceId;
public UM_PushRegistrationResult(string id, bool res) {
_deviceId = id;
_IsSucceeded = res;
}
public string deviceId {
get {
return _deviceId;
}
}
}
| 15.789474 | 56 | 0.73 | [
"MIT"
] | Bregermann/TargetCrack | Target Crack/Assets/Extensions/UltimateMobile/Scripts/NativeAPI/Notifications/UM_PushRegistrationResult.cs | 302 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
//-----------------------------------------------------------------------------
//
// Description:
// This is a class for representing a PackageRelationshipCollection. This is an internal
// class for manipulating relationships associated with a part
//
// Details:
// This class handles serialization to/from relationship parts, creation of those parts
// and offers methods to create, delete and enumerate relationships. This code was
// moved from the PackageRelationshipCollection class.
//
//-----------------------------------------------------------------------------
using System.Collections;
using System.Collections.Generic;
using System.Xml; // for XmlReader/Writer
using System.Diagnostics;
namespace System.IO.Packaging
{
/// <summary>
/// Collection of all the relationships corresponding to a given source PackagePart
/// </summary>
internal class InternalRelationshipCollection : IEnumerable<PackageRelationship>
{
// Mono will parse a URI starting with '/' as an absolute URI, while .NET Core and
// .NET Framework will parse this as relative. This will break internal relationships
// in packaging. For more information, see
// http://www.mono-project.com/docs/faq/known-issues/urikind-relativeorabsolute/
private static readonly UriKind DotNetRelativeOrAbsolute = Type.GetType ("Mono.Runtime") == null ? UriKind.RelativeOrAbsolute : (UriKind)300;
#region IEnumerable
/// <summary>
/// Returns an enumerator over all the relationships for a Package or a PackagePart
/// </summary>
/// <returns></returns>
IEnumerator IEnumerable.GetEnumerator()
{
return _relationships.GetEnumerator();
}
/// <summary>
/// Returns an enumerator over all the relationships for a Package or a PackagePart
/// </summary>
/// <returns></returns>
IEnumerator<PackageRelationship> IEnumerable<PackageRelationship>.GetEnumerator()
{
return _relationships.GetEnumerator();
}
/// <summary>
/// Returns an enumerator over all the relationships for a Package or a PackagePart
/// </summary>
/// <returns></returns>
public List<PackageRelationship>.Enumerator GetEnumerator()
{
return _relationships.GetEnumerator();
}
#endregion
#region Internal Methods
/// <summary>
/// Constructor
/// </summary>
/// <remarks>For use by PackagePart</remarks>
internal InternalRelationshipCollection(PackagePart part) : this(part.Package, part)
{
}
/// <summary>
/// Constructor
/// </summary>
/// <remarks>For use by Package</remarks>
internal InternalRelationshipCollection(Package package) : this(package, null)
{
}
/// <summary>
/// Add new relationship
/// </summary>
/// <param name="targetUri">target</param>
/// <param name="targetMode">Enumeration indicating the base uri for the target uri</param>
/// <param name="relationshipType">relationship type that uniquely defines the role of the relationship</param>
/// <param name="id">String that conforms to the xsd:ID datatype. Unique across the source's relationships.
/// Null OK (ID will be generated).</param>
internal PackageRelationship Add(Uri targetUri, TargetMode targetMode, string relationshipType, string id)
{
return Add(targetUri, targetMode, relationshipType, id, parsing: false);
}
/// <summary>
/// Return the relationship whose id is 'id', and null if not found.
/// </summary>
internal PackageRelationship GetRelationship(string id)
{
int index = GetRelationshipIndex(id);
if (index == -1)
return null;
return _relationships[index];
}
/// <summary>
/// Delete relationship with ID 'id'
/// </summary>
/// <param name="id">ID of the relationship to remove</param>
internal void Delete(string id)
{
int index = GetRelationshipIndex(id);
if (index == -1)
return;
_relationships.RemoveAt(index);
_dirty = true;
}
/// <summary>
/// Clear all the relationships in this collection
/// Today it is only used when the entire relationship part is being deleted
/// </summary>
internal void Clear()
{
_relationships.Clear();
_dirty = true;
}
/// <summary>
/// Flush to stream (destructive)
/// </summary>
/// <remarks>
/// Flush part.
/// </remarks>
internal void Flush()
{
if (!_dirty)
return;
if (_relationships.Count == 0) // empty?
{
// delete the part
if (_package.PartExists(_uri))
{
_package.DeletePart(_uri);
}
_relationshipPart = null;
}
else
{
EnsureRelationshipPart(); // lazy init
// write xml
WriteRelationshipPart(_relationshipPart);
}
_dirty = false;
}
internal static void ThrowIfInvalidRelationshipType(string relationshipType)
{
// Look for empty string or string with just spaces
if (relationshipType.Trim() == string.Empty)
throw new ArgumentException(SR.InvalidRelationshipType);
}
// If 'id' is not of the xsd type ID, throw an exception.
internal static void ThrowIfInvalidXsdId(string id)
{
Debug.Assert(id != null, "id should not be null");
try
{
// An XSD ID is an NCName that is unique.
XmlConvert.VerifyNCName(id);
}
catch (XmlException exception)
{
throw new XmlException(SR.Format(SR.NotAValidXmlIdString, id), exception);
}
}
#endregion Internal Methods
#region Private Methods
/// <summary>
/// Constructor
/// </summary>
/// <param name="package">package</param>
/// <param name="part">part will be null if package is the source of the relationships</param>
/// <remarks>Shared constructor</remarks>
private InternalRelationshipCollection(Package package, PackagePart part)
{
Debug.Assert(package != null, "package parameter passed should never be null");
_package = package;
_sourcePart = part;
//_sourcePart may be null representing that the relationships are at the package level
_uri = GetRelationshipPartUri(_sourcePart);
_relationships = new List<PackageRelationship>(4);
// Load if available (not applicable to write-only mode).
if ((package.FileOpenAccess == FileAccess.Read ||
package.FileOpenAccess == FileAccess.ReadWrite) && package.PartExists(_uri))
{
_relationshipPart = package.GetPart(_uri);
ThrowIfIncorrectContentType(_relationshipPart.ValidatedContentType);
ParseRelationshipPart(_relationshipPart);
}
//Any initialization in the constructor should not set the dirty flag to true.
_dirty = false;
}
/// <summary>
/// Returns the associated RelationshipPart for this part
/// </summary>
/// <param name="part">may be null</param>
/// <returns>name of relationship part for the given part</returns>
private static Uri GetRelationshipPartUri(PackagePart part)
{
Uri sourceUri;
if (part == null)
sourceUri = PackUriHelper.PackageRootUri;
else
sourceUri = part.Uri;
return PackUriHelper.GetRelationshipPartUri(sourceUri);
}
/// <summary>
/// Parse PackageRelationship Stream
/// </summary>
/// <param name="part">relationship part</param>
/// <exception cref="XmlException">Thrown if XML is malformed</exception>
private void ParseRelationshipPart(PackagePart part)
{
//We can safely open the stream as FileAccess.Read, as this code
//should only be invoked if the Package has been opened in Read or ReadWrite mode.
Debug.Assert(_package.FileOpenAccess == FileAccess.Read || _package.FileOpenAccess == FileAccess.ReadWrite,
"This method should only be called when FileAccess is Read or ReadWrite");
using (Stream s = part.GetStream(FileMode.Open, FileAccess.Read))
{
// load from the relationship part associated with the given part
using (XmlReader baseReader = XmlReader.Create(s))
{
using (XmlCompatibilityReader reader = new XmlCompatibilityReader(baseReader, s_relationshipKnownNamespaces))
{
//This method expects the reader to be in ReadState.Initial.
//It will make the first read call.
PackagingUtilities.PerformInitialReadAndVerifyEncoding(baseReader);
//Note: After the previous method call the reader should be at the first tag in the markup.
//MoveToContent - Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
// look for our tag and namespace pair - throw if other elements are encountered
// Make sure that the current node read is an Element
if (reader.NodeType == XmlNodeType.Element
&& (reader.Depth == 0)
&& (string.CompareOrdinal(s_relationshipsTagName, reader.LocalName) == 0)
&& (string.CompareOrdinal(PackagingUtilities.RelationshipNamespaceUri, reader.NamespaceURI) == 0))
{
ThrowIfXmlBaseAttributeIsPresent(reader);
//There should be a namespace Attribute present at this level.
//Also any other attribute on the <Relationships> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) > 0)
throw new XmlException(SR.RelationshipsTagHasExtraAttributes, null, reader.LineNumber, reader.LinePosition);
// start tag encountered for Relationships
// now parse individual Relationship tags
while (reader.Read())
{
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
//If the reader is currently at a content node then this function call is a no-op
reader.MoveToContent();
//If MoveToContent() takes us to the end of the content
if (reader.NodeType == XmlNodeType.None)
continue;
if (reader.NodeType == XmlNodeType.Element
&& (reader.Depth == 1)
&& (string.CompareOrdinal(s_relationshipTagName, reader.LocalName) == 0)
&& (string.CompareOrdinal(PackagingUtilities.RelationshipNamespaceUri, reader.NamespaceURI) == 0))
{
ThrowIfXmlBaseAttributeIsPresent(reader);
int expectedAttributesCount = 3;
string targetModeAttributeValue = reader.GetAttribute(s_targetModeAttributeName);
if (targetModeAttributeValue != null)
expectedAttributesCount++;
//check if there are expected number of attributes.
//Also any other attribute on the <Relationship> tag is an error including xml: and xsi: attributes
if (PackagingUtilities.GetNonXmlnsAttributeCount(reader) == expectedAttributesCount)
{
ProcessRelationshipAttributes(reader);
//Skip the EndElement for Relationship
if (!reader.IsEmptyElement)
ProcessEndElementForRelationshipTag(reader);
}
else
{
throw new XmlException(SR.RelationshipTagDoesntMatchSchema, null, reader.LineNumber, reader.LinePosition);
}
}
else
if (!(string.CompareOrdinal(s_relationshipsTagName, reader.LocalName) == 0 && (reader.NodeType == XmlNodeType.EndElement)))
throw new XmlException(SR.UnknownTagEncountered, null, reader.LineNumber, reader.LinePosition);
}
}
else throw new XmlException(SR.ExpectedRelationshipsElementTag, null, reader.LineNumber, reader.LinePosition);
}
}
}
}
//This method processes the attributes that are present on the Relationship element
private void ProcessRelationshipAttributes(XmlCompatibilityReader reader)
{
// Attribute : TargetMode
string targetModeAttributeValue = reader.GetAttribute(s_targetModeAttributeName);
//If the TargetMode attribute is missing in the underlying markup then we assume it to be internal
TargetMode relationshipTargetMode = TargetMode.Internal;
if (targetModeAttributeValue != null)
{
try
{
relationshipTargetMode = (TargetMode)(Enum.Parse(typeof(TargetMode), targetModeAttributeValue, ignoreCase: false));
}
catch (ArgumentNullException argNullEx)
{
ThrowForInvalidAttributeValue(reader, s_targetModeAttributeName, argNullEx);
}
catch (ArgumentException argEx)
{
//if the targetModeAttributeValue is not Internal|External then Argument Exception will be thrown.
ThrowForInvalidAttributeValue(reader, s_targetModeAttributeName, argEx);
}
}
// Attribute : Target
// create a new PackageRelationship
string targetAttributeValue = reader.GetAttribute(s_targetAttributeName);
if (string.IsNullOrEmpty(targetAttributeValue))
throw new XmlException(SR.Format(SR.RequiredRelationshipAttributeMissing, s_targetAttributeName), null, reader.LineNumber, reader.LinePosition);
Uri targetUri = new Uri(targetAttributeValue, DotNetRelativeOrAbsolute);
// Attribute : Type
string typeAttributeValue = reader.GetAttribute(s_typeAttributeName);
if (string.IsNullOrEmpty(typeAttributeValue))
throw new XmlException(SR.Format(SR.RequiredRelationshipAttributeMissing, s_typeAttributeName), null, reader.LineNumber, reader.LinePosition);
// Attribute : Id
// Get the Id attribute (required attribute).
string idAttributeValue = reader.GetAttribute(s_idAttributeName);
if (string.IsNullOrEmpty(idAttributeValue))
throw new XmlException(SR.Format(SR.RequiredRelationshipAttributeMissing, s_idAttributeName), null, reader.LineNumber, reader.LinePosition);
// Add the relationship to the collection
Add(targetUri, relationshipTargetMode, typeAttributeValue, idAttributeValue, parsing: true);
}
//If End element is present for Relationship then we process it
private void ProcessEndElementForRelationshipTag(XmlCompatibilityReader reader)
{
Debug.Assert(!reader.IsEmptyElement, "This method should only be called if the Relationship Element is not empty");
reader.Read();
//Skips over the following - ProcessingInstruction, DocumentType, Comment, Whitespace, or SignificantWhitespace
reader.MoveToContent();
if (reader.NodeType == XmlNodeType.EndElement && string.CompareOrdinal(s_relationshipTagName, reader.LocalName) == 0)
return;
else
throw new XmlException(SR.Format(SR.ElementIsNotEmptyElement, s_relationshipTagName), null, reader.LineNumber, reader.LinePosition);
}
/// <summary>
/// Add new relationship to the Collection
/// </summary>
/// <param name="targetUri">target</param>
/// <param name="targetMode">Enumeration indicating the base uri for the target uri</param>
/// <param name="relationshipType">relationship type that uniquely defines the role of the relationship</param>
/// <param name="id">String that conforms to the xsd:ID datatype. Unique across the source's relationships.
/// Null OK (ID will be generated).</param>
/// <param name="parsing">Indicates whether the add call is made while parsing existing relationships
/// from a relationship part, or we are adding a new relationship</param>
private PackageRelationship Add(Uri targetUri, TargetMode targetMode, string relationshipType, string id, bool parsing)
{
if (targetUri == null)
throw new ArgumentNullException(nameof(targetUri));
if (relationshipType == null)
throw new ArgumentNullException(nameof(relationshipType));
ThrowIfInvalidRelationshipType(relationshipType);
//Verify if the Enum value is valid
if (targetMode < TargetMode.Internal || targetMode > TargetMode.External)
throw new ArgumentOutOfRangeException(nameof(targetMode));
// don't accept absolute Uri's if targetMode is Internal.
if (targetMode == TargetMode.Internal && targetUri.IsAbsoluteUri)
throw new ArgumentException(SR.RelationshipTargetMustBeRelative, nameof(targetUri));
// don't allow relationships to relationships
// This check should be made for following cases
// 1. Uri is absolute and it is pack Uri
// 2. Uri is NOT absolute and its target mode is internal (or NOT external)
// Note: if the target is absolute uri and its not a pack scheme then we cannot determine if it is a rels part
// Note: if the target is relative uri and target mode is external, we cannot determine if it is a rels part
if ((!targetUri.IsAbsoluteUri && targetMode != TargetMode.External)
|| (targetUri.IsAbsoluteUri && targetUri.Scheme == PackUriHelper.UriSchemePack))
{
Uri resolvedUri = GetResolvedTargetUri(targetUri, targetMode);
//GetResolvedTargetUri returns a null if the target mode is external and the
//target Uri is a packUri with no "part" component, so in that case we know that
//its not a relationship part.
if (resolvedUri != null)
{
if (PackUriHelper.IsRelationshipPartUri(resolvedUri))
throw new ArgumentException(SR.RelationshipToRelationshipIllegal, nameof(targetUri));
}
}
// Generate an ID if id is null. Throw exception if neither null nor a valid unique xsd:ID.
if (id == null)
id = GenerateUniqueRelationshipId();
else
ValidateUniqueRelationshipId(id);
// create and add
PackageRelationship relationship = new PackageRelationship(_package, _sourcePart, targetUri, targetMode, relationshipType, id);
_relationships.Add(relationship);
//If we are adding relationships as a part of Parsing the underlying relationship part, we should not set
//the dirty flag to false.
_dirty = !parsing;
return relationship;
}
/// <summary>
/// Write PackageRelationship Stream
/// </summary>
/// <param name="part">part to persist to</param>
private void WriteRelationshipPart(PackagePart part)
{
using (Stream partStream = part.GetStream())
using (IgnoreFlushAndCloseStream s = new IgnoreFlushAndCloseStream(partStream))
{
if (_package.FileOpenAccess != FileAccess.Write)
{
s.SetLength(0); // truncate to resolve PS 954048
}
// use UTF-8 encoding by default
using (XmlWriter writer = XmlWriter.Create(s, new XmlWriterSettings { Encoding = System.Text.Encoding.UTF8 }))
{
writer.WriteStartDocument();
// start outer Relationships tag
writer.WriteStartElement(s_relationshipsTagName, PackagingUtilities.RelationshipNamespaceUri);
// Write Relationship elements.
WriteRelationshipsAsXml(
writer,
_relationships,
false /* do not systematically write target mode */
);
// end of Relationships tag
writer.WriteEndElement();
// close the document
writer.WriteEndDocument();
}
}
}
/// <summary>
/// Write one Relationship element for each member of relationships.
/// This method is used by XmlDigitalSignatureProcessor code as well
/// </summary>
internal static void WriteRelationshipsAsXml(XmlWriter writer, IEnumerable<PackageRelationship> relationships, bool alwaysWriteTargetModeAttribute)
{
foreach (PackageRelationship relationship in relationships)
{
writer.WriteStartElement(s_relationshipTagName);
// Write RelationshipType attribute.
writer.WriteAttributeString(s_typeAttributeName, relationship.RelationshipType);
// Write Target attribute.
// We would like to persist the uri as passed in by the user and so we use the
// OriginalString property. This makes the persisting behavior consistent
// for relative and absolute Uris.
// Since we accepted the Uri as a string, we are at the minimum guaranteed that
// the string can be converted to a valid Uri.
// Also, we are just using it here to persist the information and we are not
// resolving or fetching a resource based on this Uri.
writer.WriteAttributeString(s_targetAttributeName, relationship.TargetUri.OriginalString);
// TargetMode is optional attribute in the markup and its default value is TargetMode="Internal"
if (alwaysWriteTargetModeAttribute || relationship.TargetMode == TargetMode.External)
writer.WriteAttributeString(s_targetModeAttributeName, relationship.TargetMode.ToString());
// Write Id attribute.
writer.WriteAttributeString(s_idAttributeName, relationship.Id);
writer.WriteEndElement();
}
}
/// <summary>
/// Ensures that the PackageRelationship PackagePart has been created - lazy init
/// </summary>
/// <remarks>
/// </remarks>
private void EnsureRelationshipPart()
{
if (_relationshipPart == null || _relationshipPart.IsDeleted)
{
if (_package.PartExists(_uri))
{
_relationshipPart = _package.GetPart(_uri);
ThrowIfIncorrectContentType(_relationshipPart.ValidatedContentType);
}
else
{
CompressionOption compressionOption = _sourcePart == null ? CompressionOption.NotCompressed : _sourcePart.CompressionOption;
_relationshipPart = _package.CreatePart(_uri, PackagingUtilities.RelationshipPartContentType.ToString(), compressionOption);
}
}
}
/// <summary>
/// Resolves the target uri in the relationship against the source part or the
/// package root. This resolved Uri is then used by the Add method to figure
/// out if a relationship is being created to another relationship part.
/// </summary>
/// <param name="target">PackageRelationship target uri</param>
/// <param name="targetMode"> Enum value specifying the interpretation of the base uri
/// for the relationship target uri</param>
/// <returns>Resolved Uri</returns>
private Uri GetResolvedTargetUri(Uri target, TargetMode targetMode)
{
Debug.Assert(targetMode == TargetMode.Internal);
Debug.Assert(!target.IsAbsoluteUri, "Uri should be relative at this stage");
if (_sourcePart == null) //indicates that the source is the package root
return PackUriHelper.ResolvePartUri(PackUriHelper.PackageRootUri, target);
else
return PackUriHelper.ResolvePartUri(_sourcePart.Uri, target);
}
//Throws an exception if the relationship part does not have the correct content type
private void ThrowIfIncorrectContentType(ContentType contentType)
{
if (!contentType.AreTypeAndSubTypeEqual(PackagingUtilities.RelationshipPartContentType))
throw new FileFormatException(SR.RelationshipPartIncorrectContentType);
}
//Throws an exception if the xml:base attribute is present in the Relationships XML
private void ThrowIfXmlBaseAttributeIsPresent(XmlCompatibilityReader reader)
{
string xmlBaseAttributeValue = reader.GetAttribute(s_xmlBaseAttributeName);
if (xmlBaseAttributeValue != null)
throw new XmlException(SR.Format(SR.InvalidXmlBaseAttributePresent, s_xmlBaseAttributeName), null, reader.LineNumber, reader.LinePosition);
}
//Throws an XML exception if the attribute value is invalid
private void ThrowForInvalidAttributeValue(XmlCompatibilityReader reader, string attributeName, Exception ex)
{
throw new XmlException(SR.Format(SR.InvalidValueForTheAttribute, attributeName), ex, reader.LineNumber, reader.LinePosition);
}
// Generate a unique relation ID.
private string GenerateUniqueRelationshipId()
{
string id;
do
{
id = GenerateRelationshipId();
} while (GetRelationship(id) != null);
return id;
}
// Build an ID string consisting of the letter 'R' followed by an 8-byte GUID timestamp.
// Guid.ToString() outputs the bytes in the big-endian order (higher order byte first)
private string GenerateRelationshipId()
{
// The timestamp consists of the first 8 hex octets of the GUID.
return string.Concat("R", Guid.NewGuid().ToString("N").Substring(0, s_timestampLength));
}
// If 'id' is not of the xsd type ID or is not unique for this collection, throw an exception.
private void ValidateUniqueRelationshipId(string id)
{
// An XSD ID is an NCName that is unique.
ThrowIfInvalidXsdId(id);
// Check for uniqueness.
if (GetRelationshipIndex(id) >= 0)
throw new XmlException(SR.Format(SR.NotAUniqueRelationshipId, id));
}
// Retrieve a relationship's index in _relationships given its id.
// Return a negative value if not found.
private int GetRelationshipIndex(string id)
{
for (int index = 0; index < _relationships.Count; ++index)
if (string.Equals(_relationships[index].Id, id, StringComparison.Ordinal))
return index;
return -1;
}
#endregion
#region Private Properties
#endregion Private Properties
#region Private Members
private List<PackageRelationship> _relationships;
private bool _dirty; // true if we have uncommitted changes to _relationships
private Package _package; // our package - in case _sourcePart is null
private PackagePart _sourcePart; // owning part - null if package is the owner
private PackagePart _relationshipPart; // where our relationships are persisted
private Uri _uri; // the URI of our relationship part
//------------------------------------------------------
//
// Private Fields
//
//------------------------------------------------------
// segment that indicates a relationship part
private static readonly int s_timestampLength = 16;
private static readonly string s_relationshipsTagName = "Relationships";
private static readonly string s_relationshipTagName = "Relationship";
private static readonly string s_targetAttributeName = "Target";
private static readonly string s_typeAttributeName = "Type";
private static readonly string s_idAttributeName = "Id";
private static readonly string s_xmlBaseAttributeName = "xml:base";
private static readonly string s_targetModeAttributeName = "TargetMode";
private static readonly string[] s_relationshipKnownNamespaces
= new string[] { PackagingUtilities.RelationshipNamespaceUri };
#endregion
}
}
| 46.475556 | 160 | 0.590195 | [
"MIT"
] | ARhj/corefx | src/System.IO.Packaging/src/System/IO/Packaging/InternalRelationshipCollection.cs | 31,371 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
/* IDEAS
* - Throw this in with the physics system to unify it all
* - Adjust gravity based on tilt/rotation of car (but shifted 90deg still)
*/
public class ParentGravityHandler : MonoBehaviour
{
public bool dampenVerticalVelocity = true;
public float dampenThreshold = 10f;
private void FixedUpdate () {
// Artificially add gravity depending on parent's down-axis
Transform parent = transform.parent;
Vector3 gravity_adjusted = -Physics.gravity.magnitude * parent.up;
Rigidbody rb = GetComponent<Rigidbody>();
// If raising height too quickly, increase the gravity adjustment
bool moving_up = Vector3.Dot(parent.up, rb.velocity) > 0.1;
if(moving_up) {
float mag = Vector3.Scale(parent.up, rb.velocity).sqrMagnitude;
print(mag);
if (mag > dampenThreshold) {
gravity_adjusted *= (mag/dampenThreshold);
}
}
rb.velocity += gravity_adjusted * Time.fixedDeltaTime;
}
}
| 32.5 | 75 | 0.660633 | [
"MIT"
] | nkrim/mailman-simulator | Assets/ParentGravityHandler.cs | 1,107 | C# |
using UnityEngine;
using System.Collections;
using Ceto.Common.Containers.Interpolation;
namespace Ceto
{
public static class ShoreMaskGenerator
{
public static float[] CreateHeightMap(Terrain terrain)
{
TerrainData data = terrain.terrainData;
int resolution = data.heightmapResolution;
Vector3 scale = data.heightmapScale;
float[,] heights = data.GetHeights(0, 0, resolution, resolution);
float[] map = new float[resolution * resolution];
for(int y = 0; y < resolution; y++)
{
for(int x = 0; x < resolution; x++)
{
map[x + y * resolution] = heights[y,x] * scale.y + terrain.transform.position.y;
}
}
return map;
}
public static Texture2D CreateMask(float[] heightMap, int size, float shoreLevel, float spread, TextureFormat format)
{
Texture2D mask = new Texture2D(size, size, format, false, true);
mask.filterMode = FilterMode.Bilinear;
int s2 = size * size;
Color[] colors = new Color[s2];
for(int i = 0; i < s2; i++)
{
float h = Mathf.Clamp(shoreLevel - heightMap[i], 0.0f, spread);
h = 1.0f - h / spread;
colors[i].r = h;
colors[i].g = h;
colors[i].b = h;
colors[i].a = h;
}
mask.SetPixels(colors);
mask.Apply();
return mask;
}
public static Texture2D CreateMask(InterpolatedArray2f heightMap, int width, int height, float shoreLevel, float spread, TextureFormat format)
{
Texture2D mask = new Texture2D(width, height, format, false, true);
mask.filterMode = FilterMode.Bilinear;
Color[] colors = new Color[width * height];
bool matches = width == heightMap.SX && height == heightMap.SY;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int i = x + y * height;
float h = 0.0f;
if (matches)
{
h = Mathf.Clamp(shoreLevel - heightMap.Data[i], 0.0f, spread);
}
else
{
float fx = x / (width - 1.0f);
float fy = y / (height - 1.0f);
h = Mathf.Clamp(shoreLevel - heightMap.Get(fx, fy, 0), 0.0f, spread);
}
h = 1.0f - h / spread;
colors[i].r = h;
colors[i].g = h;
colors[i].b = h;
colors[i].a = h;
}
}
mask.SetPixels(colors);
mask.Apply();
return mask;
}
public static Texture2D CreateClipMask(float[] heightMap, int size, float shoreLevel, TextureFormat format)
{
Texture2D mask = new Texture2D(size, size, format, false, true);
mask.filterMode = FilterMode.Bilinear;
int s2 = size * size;
Color[] colors = new Color[s2];
for (int i = 0; i < s2; i++)
{
float h = Mathf.Clamp(heightMap[i] - shoreLevel, 0.0f, 1.0f);
if (h > 0.0f) h = 1.0f;
colors[i].r = h;
colors[i].g = h;
colors[i].b = h;
colors[i].a = h;
}
mask.SetPixels(colors);
mask.Apply();
return mask;
}
public static Texture2D CreateClipMask(InterpolatedArray2f heightMap, int width, int height, float shoreLevel, TextureFormat format)
{
Texture2D mask = new Texture2D(width, height, format, false, true);
mask.filterMode = FilterMode.Bilinear;
Color[] colors = new Color[width * height];
bool matches = width == heightMap.SX && height == heightMap.SY;
for (int y = 0; y < height; y++)
{
for (int x = 0; x < width; x++)
{
int i = x + y * height;
float h = 0.0f;
if (matches)
{
h = Mathf.Clamp(heightMap.Data[i] - shoreLevel, 0.0f, 1.0f);
}
else
{
float fx = x / (width - 1.0f);
float fy = y / (height - 1.0f);
h = Mathf.Clamp(heightMap.Get(fx, fy, 0) - shoreLevel, 0.0f, 1.0f);
}
if (h > 0.0f) h = 1.0f;
colors[i].r = h;
colors[i].g = h;
colors[i].b = h;
colors[i].a = h;
}
}
mask.SetPixels(colors);
mask.Apply();
return mask;
}
}
}
| 25.663212 | 150 | 0.452655 | [
"MIT"
] | CyberSys/Ceto | Assets/Ceto/Scripts/Utility/ShoreMaskGenerator.cs | 4,955 | C# |
namespace TheCollection.Application.Services.Queries.Tea {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using TheCollection.Domain;
using TheCollection.Domain.Core.Contracts;
using TheCollection.Domain.Core.Contracts.Repository;
using TheCollection.Domain.Tea;
public class BagsCountByBrandsQueryHandler : IAsyncQueryHandler<BagsCountByBrandsQuery> {
public BagsCountByBrandsQueryHandler(IGetRepository<Dashboard<IEnumerable<CountBy<RefValue>>>> repository) {
Repository = repository;
}
IGetRepository<Dashboard<IEnumerable<CountBy<RefValue>>>> Repository { get; }
public async Task<IQueryResult> ExecuteAsync(BagsCountByBrandsQuery query) {
var bagsCountByBrand = await Repository.GetItemAsync(DashBoardTypes.BagsCountByBrands.Key.ToString());
if (bagsCountByBrand == null) {
return new NotFoundResult();
}
return new OkResult(bagsCountByBrand.Data.Take(Math.Min(query.Top, 30)).OrderBy(x => x.Value?.Name));
}
}
}
| 40.285714 | 116 | 0.70656 | [
"Apache-2.0"
] | projecteon/thecollection | TheCollection.Application.Services/Queries/Tea/BagsCountByBrandsQueryHandler.cs | 1,128 | C# |
// <copyright file="AutoCloseDefinedParameters.cs" company="Johann Blais">
// Copyright (c) 2008 All Right Reserved
// </copyright>
// <author>Johann Blais</author>
// <summary>Defines constant representing the parameters specified for the auto-close feature</summary>
namespace InfoBox
{
/// <summary>
/// Defines constant representing the parameters specified for the auto-close feature.
/// </summary>
public enum AutoCloseDefinedParameters
{
/// <summary>
/// The button to use is defined.
/// </summary>
Button,
/// <summary>
/// Only the time to wait is defined.
/// </summary>
TimeOnly,
/// <summary>
/// The InformationBoxResult is defined.
/// </summary>
Result,
}
} | 28.482759 | 104 | 0.588378 | [
"ECL-2.0",
"Apache-2.0"
] | Hybrid-SaaS/InformationBox | InfoBox/Enums/AutoCloseDefinedParameters.cs | 826 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Threading.Tasks;
using Microsoft.Azure.WebJobs.Extensions.Http;
using Microsoft.Azure.WebJobs.Host;
using Microsoft.Azure.WebJobs.Script.Config;
using Microsoft.Azure.WebJobs.Script.Eventing;
using Microsoft.Azure.WebJobs.Script.WebHost;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Microsoft.Extensions.Logging.Abstractions;
using Microsoft.Extensions.Options;
using Microsoft.WebJobs.Script.Tests;
using Moq;
using WebJobs.Script.Tests;
using Xunit;
namespace Microsoft.Azure.WebJobs.Script.Tests.Host
{
public class WebScriptHostManagerTimeoutTests : IDisposable
{
private readonly TempDirectory _secretsDirectory = new TempDirectory();
private TestLoggerProvider _loggerProvider = new TestLoggerProvider();
[Fact(Skip = "Investigate test failure")]
public async Task OnTimeoutException_IgnoreToken_StopsManager()
{
IHost host = null;
try
{
IScriptJobHost scriptHost;
IScriptHostManager jobHostManager;
(host, scriptHost, jobHostManager) = await RunTimeoutExceptionTest(handleCancellation: false);
await TestHelpers.Await(() => !(jobHostManager.State == ScriptHostState.Running), userMessageCallback: () => "Expected host to not be running");
var traces = _loggerProvider.GetAllLogMessages();
Assert.DoesNotContain(traces, t => t.FormattedMessage.StartsWith("Done"));
Assert.Contains(traces, t => t.FormattedMessage.StartsWith("Timeout value of 00:00:03 exceeded by function 'Functions.TimeoutToken' (Id: "));
Assert.Contains(traces, t => t.FormattedMessage == "A function timeout has occurred. Host is shutting down.");
}
finally
{
host?.Dispose();
}
}
[Fact(Skip = "Investigate test failure")]
public async Task OnTimeoutException_UsesToken_ManagerKeepsRunning()
{
IHost host = null;
try
{
IScriptJobHost scriptHost;
IScriptHostManager jobHostManager;
(host, scriptHost, jobHostManager) = await RunTimeoutExceptionTest(handleCancellation: true);
// wait a few seconds to make sure the manager doesn't die
await Assert.ThrowsAsync<ApplicationException>(() => TestHelpers.Await(() => !(jobHostManager.State == ScriptHostState.Running),
timeout: 3000, throwWhenDebugging: true, userMessageCallback: () => "Expected host manager not to die"));
var messages = _loggerProvider.GetAllLogMessages();
Assert.Contains(messages, t => t.FormattedMessage.StartsWith("Done"));
Assert.Contains(messages, t => t.FormattedMessage.StartsWith("Timeout value of 00:00:03 exceeded by function 'Functions.TimeoutToken' (Id: "));
Assert.DoesNotContain(messages, t => t.FormattedMessage == "A function timeout has occurred. Host is shutting down.");
}
finally
{
host?.Dispose();
}
}
private async Task<(IHost, IScriptJobHost, IScriptHostManager)> RunTimeoutExceptionTest(bool handleCancellation)
{
TimeSpan gracePeriod = TimeSpan.FromMilliseconds(5000);
var (host, jobhost, jobHostManager) = await CreateAndStartWebScriptHost();
string scenarioName = handleCancellation ? "useToken" : "ignoreToken";
var args = new Dictionary<string, object>
{
{ "input", scenarioName }
};
await Assert.ThrowsAsync<FunctionTimeoutException>(() => jobhost.CallAsync("TimeoutToken", args));
return (host, jobhost, jobHostManager);
}
private async Task<(IHost, IScriptJobHost, IScriptHostManager)> CreateAndStartWebScriptHost()
{
var functions = new Collection<string> { "TimeoutToken" };
var options = new ScriptJobHostOptions()
{
RootScriptPath = $@"TestScripts\CSharp",
FileLoggingMode = FileLoggingMode.Always,
Functions = functions,
FunctionTimeout = TimeSpan.FromSeconds(3)
};
var mockEventManager = new Mock<IScriptEventManager>();
var mockRouter = new Mock<IWebJobsRouter>();
var host = new HostBuilder()
.ConfigureDefaultTestWebScriptHost()
.ConfigureServices(s =>
{
s.AddSingleton<IWebJobsRouter>(mockRouter.Object);
s.AddSingleton<ISecretManagerProvider>(new TestSecretManagerProvider());
s.AddSingleton<IScriptEventManager>(mockEventManager.Object);
s.AddSingleton<IOptions<ScriptJobHostOptions>>(new OptionsWrapper<ScriptJobHostOptions>(options));
s.AddSingleton<IOptions<ScriptApplicationHostOptions>>(new OptionsWrapper<ScriptApplicationHostOptions>(new ScriptApplicationHostOptions { SecretsPath = _secretsDirectory.Path }));
s.AddSingleton<ILoggerFactory>(NullLoggerFactory.Instance);
s.AddSingleton(ScriptSettingsManager.Instance);
})
.Build();
await host.StartAsync();
var manager = host.Services.GetService<IScriptHostManager>();
await TestHelpers.Await(() => manager.State == ScriptHostState.Running, userMessageCallback: () => "Expected host to be running");
IScriptJobHost scriptHost = host.GetScriptHost();
return (host, scriptHost, manager);
}
public void Dispose()
{
_secretsDirectory.Dispose();
}
}
}
| 43.801418 | 200 | 0.636658 | [
"Apache-2.0",
"MIT"
] | Angr1st/azure-functions-host | test/WebJobs.Script.Tests.Integration/Host/WebScriptHostManagerTimeoutTests.cs | 6,178 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System.Collections.Generic;
using System.Text.Json;
using Azure.Core;
namespace Azure.Analytics.Synapse.Artifacts.Models
{
public partial class AzureMySqlTableDataset : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("type");
writer.WriteStringValue(Type);
if (Description != null)
{
writer.WritePropertyName("description");
writer.WriteStringValue(Description);
}
if (Structure != null)
{
writer.WritePropertyName("structure");
writer.WriteObjectValue(Structure);
}
if (Schema != null)
{
writer.WritePropertyName("schema");
writer.WriteObjectValue(Schema);
}
writer.WritePropertyName("linkedServiceName");
writer.WriteObjectValue(LinkedServiceName);
if (Parameters != null)
{
writer.WritePropertyName("parameters");
writer.WriteStartObject();
foreach (var item in Parameters)
{
writer.WritePropertyName(item.Key);
writer.WriteObjectValue(item.Value);
}
writer.WriteEndObject();
}
if (Annotations != null)
{
writer.WritePropertyName("annotations");
writer.WriteStartArray();
foreach (var item in Annotations)
{
writer.WriteObjectValue(item);
}
writer.WriteEndArray();
}
if (Folder != null)
{
writer.WritePropertyName("folder");
writer.WriteObjectValue(Folder);
}
writer.WritePropertyName("typeProperties");
writer.WriteStartObject();
if (TableName != null)
{
writer.WritePropertyName("tableName");
writer.WriteObjectValue(TableName);
}
if (Table != null)
{
writer.WritePropertyName("table");
writer.WriteObjectValue(Table);
}
writer.WriteEndObject();
foreach (var item in AdditionalProperties)
{
writer.WritePropertyName(item.Key);
writer.WriteObjectValue(item.Value);
}
writer.WriteEndObject();
}
internal static AzureMySqlTableDataset DeserializeAzureMySqlTableDataset(JsonElement element)
{
string type = default;
string description = default;
object structure = default;
object schema = default;
LinkedServiceReference linkedServiceName = default;
IDictionary<string, ParameterSpecification> parameters = default;
IList<object> annotations = default;
DatasetFolder folder = default;
object tableName = default;
object table = default;
IDictionary<string, object> additionalProperties = default;
Dictionary<string, object> additionalPropertiesDictionary = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("type"))
{
type = property.Value.GetString();
continue;
}
if (property.NameEquals("description"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
description = property.Value.GetString();
continue;
}
if (property.NameEquals("structure"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
structure = property.Value.GetObject();
continue;
}
if (property.NameEquals("schema"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
schema = property.Value.GetObject();
continue;
}
if (property.NameEquals("linkedServiceName"))
{
linkedServiceName = LinkedServiceReference.DeserializeLinkedServiceReference(property.Value);
continue;
}
if (property.NameEquals("parameters"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
Dictionary<string, ParameterSpecification> dictionary = new Dictionary<string, ParameterSpecification>();
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
dictionary.Add(property0.Name, null);
}
else
{
dictionary.Add(property0.Name, ParameterSpecification.DeserializeParameterSpecification(property0.Value));
}
}
parameters = dictionary;
continue;
}
if (property.NameEquals("annotations"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
List<object> array = new List<object>();
foreach (var item in property.Value.EnumerateArray())
{
if (item.ValueKind == JsonValueKind.Null)
{
array.Add(null);
}
else
{
array.Add(item.GetObject());
}
}
annotations = array;
continue;
}
if (property.NameEquals("folder"))
{
if (property.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
folder = DatasetFolder.DeserializeDatasetFolder(property.Value);
continue;
}
if (property.NameEquals("typeProperties"))
{
foreach (var property0 in property.Value.EnumerateObject())
{
if (property0.NameEquals("tableName"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
tableName = property0.Value.GetObject();
continue;
}
if (property0.NameEquals("table"))
{
if (property0.Value.ValueKind == JsonValueKind.Null)
{
continue;
}
table = property0.Value.GetObject();
continue;
}
}
continue;
}
additionalPropertiesDictionary ??= new Dictionary<string, object>();
if (property.Value.ValueKind == JsonValueKind.Null)
{
additionalPropertiesDictionary.Add(property.Name, null);
}
else
{
additionalPropertiesDictionary.Add(property.Name, property.Value.GetObject());
}
}
additionalProperties = additionalPropertiesDictionary;
return new AzureMySqlTableDataset(type, description, structure, schema, linkedServiceName, parameters, annotations, folder, additionalProperties, tableName, table);
}
}
}
| 38.641921 | 176 | 0.453837 | [
"MIT"
] | AzureDataBox/azure-sdk-for-net | sdk/synapse/Azure.Analytics.Synapse.Artifacts/src/Generated/Models/AzureMySqlTableDataset.Serialization.cs | 8,849 | C# |
using System.IO;
using UnityEngine;
using UnityEditor;
public class CopyLuaScripts
{
private static string m_sourcePath = Application.dataPath + "/LuaScripts/src";
private static string m_targetPath = PathTools.GetABOutPath() + "/LUA";
[MenuItem("HotFix/CopyLuaScripts")]
public static void CopyLuaFile()
{
DirectoryInfo dirInfo = new DirectoryInfo(m_sourcePath);
FileInfo[] fileInfo = dirInfo.GetFiles();
if(!Directory.Exists(m_targetPath))
{
Directory.CreateDirectory(m_targetPath);
}
foreach(var item in fileInfo)
{
File.Copy(item.FullName,m_targetPath+"/"+item.Name,true);
}
Debug.Log("lua 文件拷贝完成");
AssetDatabase.SaveAssets();
AssetDatabase.Refresh();
}
}
| 25.363636 | 83 | 0.615293 | [
"MIT"
] | xzjGitHub/HitFix | HotFix/Assets/Scripts/HotFix/Editor/CopyLuaScripts.cs | 851 | C# |
using System;
using Aop.Api.Domain;
using System.Collections.Generic;
using Aop.Api.Response;
namespace Aop.Api.Request
{
/// <summary>
/// AOP API: alipay.open.mini.setintentiondata.set
/// </summary>
public class AlipayOpenMiniSetintentiondataSetRequest : IAopRequest<AlipayOpenMiniSetintentiondataSetResponse>
{
/// <summary>
/// 开发者配置意图数据
/// </summary>
public string BizContent { get; set; }
#region IAopRequest Members
private bool needEncrypt=false;
private string apiVersion = "1.0";
private string terminalType;
private string terminalInfo;
private string prodCode;
private string notifyUrl;
private string returnUrl;
private AopObject bizModel;
private Dictionary<string, string> udfParams; //add user-defined text parameters
public void SetNeedEncrypt(bool needEncrypt){
this.needEncrypt=needEncrypt;
}
public bool GetNeedEncrypt(){
return this.needEncrypt;
}
public void SetNotifyUrl(string notifyUrl){
this.notifyUrl = notifyUrl;
}
public string GetNotifyUrl(){
return this.notifyUrl;
}
public void SetReturnUrl(string returnUrl){
this.returnUrl = returnUrl;
}
public string GetReturnUrl(){
return this.returnUrl;
}
public void SetTerminalType(String terminalType){
this.terminalType=terminalType;
}
public string GetTerminalType(){
return this.terminalType;
}
public void SetTerminalInfo(String terminalInfo){
this.terminalInfo=terminalInfo;
}
public string GetTerminalInfo(){
return this.terminalInfo;
}
public void SetProdCode(String prodCode){
this.prodCode=prodCode;
}
public string GetProdCode(){
return this.prodCode;
}
public string GetApiName()
{
return "alipay.open.mini.setintentiondata.set";
}
public void SetApiVersion(string apiVersion){
this.apiVersion=apiVersion;
}
public string GetApiVersion(){
return this.apiVersion;
}
public void PutOtherTextParam(string key, string value)
{
if(this.udfParams == null)
{
this.udfParams = new Dictionary<string, string>();
}
this.udfParams.Add(key, value);
}
public IDictionary<string, string> GetParameters()
{
AopDictionary parameters = new AopDictionary();
parameters.Add("biz_content", this.BizContent);
if(udfParams != null)
{
parameters.AddAll(this.udfParams);
}
return parameters;
}
public AopObject GetBizModel()
{
return this.bizModel;
}
public void SetBizModel(AopObject bizModel)
{
this.bizModel = bizModel;
}
#endregion
}
}
| 25.943548 | 115 | 0.566677 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Request/AlipayOpenMiniSetintentiondataSetRequest.cs | 3,235 | C# |
using HumansTxtLanguageService.Syntax;
using Microsoft.VisualStudio.Text.Tagging;
using System.Collections.Generic;
namespace HumansTxtLanguageService.Diagnostics
{
public interface ISyntaxNodeAnalyzer<TSyntaxNode> : IDiagnosticAnalyzer where TSyntaxNode : SyntaxNode
{
IEnumerable<ITagSpan<IErrorTag>> Analyze(TSyntaxNode node);
}
}
| 29.666667 | 106 | 0.800562 | [
"MIT"
] | Peter-Juhasz/HumansTxtLanguageService | HumansTxtLanguageService/Diagnostics/ISyntaxNodeAnalyzer.cs | 358 | C# |
using System;
using System.Collections.Generic;
using Grynwald.ChangeLog.Configuration;
using Grynwald.Utilities.IO;
using Xunit;
namespace Grynwald.ChangeLog.Test.Configuration
{
/// <summary>
/// Tests for <see cref="ConfigurationValidator"/>
/// </summary>
public class ConfigurationValidatorTest
{
[Fact]
public void Validate_checks_arguments_for_null()
{
var sut = new ConfigurationValidator();
Assert.Throws<ArgumentNullException>(() => sut.Validate((ChangeLogConfiguration)null!));
}
[Fact]
public void No_errors_are_found_in_default_configuration()
{
// ARRANGE
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(ChangeLogConfigurationLoader.GetDefaultConfiguration());
// ASSERT
Assert.True(result.IsValid);
}
[Theory]
[InlineData("")]
[InlineData("\t")]
[InlineData(" ")]
public void Scope_name_must_not_be_empty_or_whitespace(string scopeName)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Scopes = new Dictionary<string, ChangeLogConfiguration.ScopeConfiguration>()
{
{ scopeName, new ChangeLogConfiguration.ScopeConfiguration(){ DisplayName = "Display Name"} }
};
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'Scope Name'", error.ErrorMessage);
}
[Theory]
[InlineData("some-scope")]
public void Scope_name_must_be_unique(string scopeName)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Scopes = new Dictionary<string, ChangeLogConfiguration.ScopeConfiguration>()
{
{ scopeName.ToLower(), new ChangeLogConfiguration.ScopeConfiguration() },
{ scopeName.ToUpper(), new ChangeLogConfiguration.ScopeConfiguration() }
};
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'Scope Name' must be unique", error.ErrorMessage);
}
[Theory]
[InlineData("")]
[InlineData("\t")]
[InlineData(" ")]
public void Footer_name_must_not_be_empty_or_whitespace(string footerName)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Footers = new Dictionary<string, ChangeLogConfiguration.FooterConfiguration>()
{
{ footerName, new ChangeLogConfiguration.FooterConfiguration() { DisplayName = "Display Name"} }
};
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'Footer Name'", error.ErrorMessage);
}
[Theory]
[InlineData("some-footer")]
public void Footer_name_must_be_unique(string footerName)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Footers = new Dictionary<string, ChangeLogConfiguration.FooterConfiguration>()
{
{ footerName.ToLower(), new ChangeLogConfiguration.FooterConfiguration() },
{ footerName.ToUpper(), new ChangeLogConfiguration.FooterConfiguration() }
};
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'Footer Name' must be unique", error.ErrorMessage);
}
[Theory]
[InlineData("")]
[InlineData(null)]
public void VersionRange_can_be_null_or_empty(string versionRange)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.VersionRange = versionRange;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[InlineData("\t")]
[InlineData(" ")]
[InlineData("not-a-version-range")]
public void VersionRange_must_be_valid_if_set(string versionRange)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.VersionRange = versionRange;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
Assert.All(result.Errors, error => Assert.Contains("'Version Range'", error.ErrorMessage));
}
[Theory]
[InlineData("")]
[InlineData(null)]
public void CurrentVersion_can_be_null_or_empty(string currentVersion)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.CurrentVersion = currentVersion;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[InlineData("\t")]
[InlineData(" ")]
[InlineData("not-a-version-range")]
public void CurrentVersion_must_be_valid_if_set(string currentVersion)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.CurrentVersion = currentVersion;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
Assert.All(result.Errors, error => Assert.Contains("'Current Version'", error.ErrorMessage));
}
[Theory]
[InlineData("")]
[InlineData("\t")]
[InlineData(" ")]
public void Entry_type_must_not_be_empty_or_whitespace(string entryType)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.EntryTypes = new Dictionary<string, ChangeLogConfiguration.EntryTypeConfiguration>()
{
{ entryType, new ChangeLogConfiguration.EntryTypeConfiguration() { DisplayName = "Display Name" } }
};
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'Entry Type'", error.ErrorMessage);
}
[Theory]
[InlineData("feat")]
public void Entry_types_must_not_be_unique(string entryType)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.EntryTypes = new Dictionary<string, ChangeLogConfiguration.EntryTypeConfiguration>()
{
{ entryType.ToLower(), new ChangeLogConfiguration.EntryTypeConfiguration() { DisplayName = "Display Name" } },
{ entryType.ToUpper(), new ChangeLogConfiguration.EntryTypeConfiguration() { DisplayName = "Display Name" } }
};
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'Entry Type' must be unique", error.ErrorMessage);
}
[Theory]
[InlineData("")]
[InlineData(null)]
public void GitHub_AccessToken_can_be_null_or_empty(string accessToken)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitHub.AccessToken = accessToken;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[InlineData("\t")]
[InlineData(" ")]
public void GitHub_AccessToken_must_not_be_whitespace(string accessToken)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitHub.AccessToken = accessToken;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'GitHub Access Token'", error.ErrorMessage);
}
[Theory]
[InlineData("")]
[InlineData(null)]
[InlineData("\t")]
[InlineData(" ")]
public void GitHub_RemoteName_must_not_be_null_or_whitespace(string remoteName)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitHub.RemoteName = remoteName;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'GitHub Remote Name'", error.ErrorMessage);
}
[Theory]
[InlineData("")]
[InlineData(null)]
public void GitHub_Host_can_be_null_or_empty(string host)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitHub.Host = host;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[InlineData("\t")]
[InlineData(" ")]
public void GitHub_Host_must_not_be_whitespace(string host)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitHub.Host = host;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'GitHub Host'", error.ErrorMessage);
}
[Theory]
[InlineData("")]
[InlineData(null)]
public void GitHub_Owner_can_be_null_or_empty(string owner)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitHub.Owner = owner;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[InlineData("\t")]
[InlineData(" ")]
public void GitHub_Owner_must_not_be_whitespace(string owner)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitHub.Owner = owner;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'GitHub Repository Owner'", error.ErrorMessage);
}
[Theory]
[InlineData("")]
[InlineData(null)]
public void GitHub_Repository_can_be_null_or_empty(string repository)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitHub.Repository = repository;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[InlineData("\t")]
[InlineData(" ")]
public void GitHub_Repository_must_not_be_whitespace(string repository)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitHub.Repository = repository;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'GitHub Repository Name'", error.ErrorMessage);
}
[Theory]
[InlineData("")]
[InlineData(null)]
public void GitLab_AccessToken_can_be_null_or_empty(string accessToken)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitLab.AccessToken = accessToken;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[InlineData("\t")]
[InlineData(" ")]
public void GitLab_AccessToken_must_not_be_whitespace(string accessToken)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitLab.AccessToken = accessToken;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'GitLab Access Token'", error.ErrorMessage);
}
[Theory]
[InlineData("")]
[InlineData(null)]
[InlineData("\t")]
[InlineData(" ")]
public void GitLab_RemoteName_must_not_be_null_or_whitespace(string remoteName)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitLab.RemoteName = remoteName;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'GitLab Remote Name'", error.ErrorMessage);
}
[Theory]
[InlineData("")]
[InlineData(null)]
public void GitLab_Host_can_be_null_or_empty(string host)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitLab.Host = host;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[InlineData("\t")]
[InlineData(" ")]
public void GitLab_Host_must_not_be_whitespace(string host)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitLab.Host = host;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'GitLab Host'", error.ErrorMessage);
}
[Theory]
[InlineData("")]
[InlineData(null)]
public void GitLab_Namespace_can_be_null_or_empty(string @namespace)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitLab.Namespace = @namespace;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[InlineData("\t")]
[InlineData(" ")]
public void GitLab_Namespace_must_not_be_whitespace(string @namespace)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitLab.Namespace = @namespace;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'GitLab Namespace'", error.ErrorMessage);
}
[Theory]
[InlineData("")]
[InlineData(null)]
public void GitLab_Project_can_be_null_or_empty(string project)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitLab.Project = project;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[InlineData("\t")]
[InlineData(" ")]
public void GitLab_Project_must_not_be_whitespace(string project)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Integrations.GitLab.Project = project;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
var error = Assert.Single(result.Errors);
Assert.Contains("'GitLab Project Name'", error.ErrorMessage);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Filter_Type_expression_can_be_null_or_empty(string filterType)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Filter.Include = new[]
{
new ChangeLogConfiguration.FilterExpressionConfiguration()
{
Type = filterType
}
};
config.Filter.Exclude = new[]
{
new ChangeLogConfiguration.FilterExpressionConfiguration()
{
Type = filterType
}
};
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[InlineData("\t")]
[InlineData(" ")]
public void Filter_Type_expression_must_not_be_whitespace(string filterType)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Filter.Include = new[]
{
new ChangeLogConfiguration.FilterExpressionConfiguration()
{
Type = filterType
}
};
config.Filter.Exclude = new[]
{
new ChangeLogConfiguration.FilterExpressionConfiguration()
{
Type = filterType
}
};
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
Assert.Collection(result.Errors,
error => Assert.Contains("'Filter Type Expression'", error.ErrorMessage),
error => Assert.Contains("'Filter Type Expression'", error.ErrorMessage)
);
}
[Theory]
[InlineData(null)]
[InlineData("")]
public void Filter_Scope_expression_can_be_null_or_empty(string filterType)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Filter.Include = new[]
{
new ChangeLogConfiguration.FilterExpressionConfiguration()
{
Scope = filterType
}
};
config.Filter.Exclude = new[]
{
new ChangeLogConfiguration.FilterExpressionConfiguration()
{
Scope = filterType
}
};
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[InlineData("\t")]
[InlineData(" ")]
public void Filter_Scope_expression_must_not_be_whitespace(string filterType)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
config.Filter.Include = new[]
{
new ChangeLogConfiguration.FilterExpressionConfiguration()
{
Scope = filterType
}
};
config.Filter.Exclude = new[]
{
new ChangeLogConfiguration.FilterExpressionConfiguration()
{
Scope = filterType
}
};
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
Assert.Collection(result.Errors,
error => Assert.Contains("'Filter Scope Expression'", error.ErrorMessage),
error => Assert.Contains("'Filter Scope Expression'", error.ErrorMessage)
);
}
[Theory]
[CombinatorialData]
public void Template_custom_directory_can_be_null_or_empty(
ChangeLogConfiguration.TemplateName template,
[CombinatorialValues(null, "")] string customDirectory)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
var customDirectoryProperty = config.Template.GetType().GetProperty(template.ToString());
var templateSettings = (ChangeLogConfiguration.TemplateSettings)customDirectoryProperty!.GetValue(config.Template)!;
templateSettings.CustomDirectory = customDirectory;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
[Theory]
[CombinatorialData]
public void Template_custom_directory_must_not_be_whitespace(
ChangeLogConfiguration.TemplateName template,
[CombinatorialValues("\t", " ")] string customDirectory)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
var customDirectoryProperty = config.Template.GetType().GetProperty(template.ToString());
var templateSettings = (ChangeLogConfiguration.TemplateSettings)customDirectoryProperty!.GetValue(config.Template)!;
templateSettings.CustomDirectory = customDirectory;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
Assert.Collection(result.Errors,
error => Assert.Contains("'Template Custom Directory'", error.ErrorMessage)
);
}
[Theory]
[CombinatorialData]
public void Template_custom_directory_must_exist_when_it_is_not_null_or_empty(ChangeLogConfiguration.TemplateName template)
{
// ARRANGE
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
var customDirectoryProperty = config.Template.GetType().GetProperty(template.ToString());
var templateSettings = (ChangeLogConfiguration.TemplateSettings)customDirectoryProperty!.GetValue(config.Template)!;
templateSettings.CustomDirectory = "/Some-Directory";
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.False(result.IsValid);
Assert.Collection(result.Errors,
error =>
{
Assert.Contains("'Template Custom Directory'", error.ErrorMessage);
Assert.Contains("'/Some-Directory'", error.ErrorMessage);
}
);
}
[Theory]
[CombinatorialData]
public void Template_custom_directory_is_valid_when_directory_exists(ChangeLogConfiguration.TemplateName template)
{
// ARRANGE
using var temporaryDirectory = new TemporaryDirectory();
var config = ChangeLogConfigurationLoader.GetDefaultConfiguration();
var customDirectoryProperty = config.Template.GetType().GetProperty(template.ToString());
var templateSettings = (ChangeLogConfiguration.TemplateSettings)customDirectoryProperty!.GetValue(config.Template)!;
templateSettings.CustomDirectory = temporaryDirectory;
var sut = new ConfigurationValidator();
// ACT
var result = sut.Validate(config);
// ASSERT
Assert.True(result.IsValid);
Assert.Empty(result.Errors);
}
}
}
| 32.599764 | 131 | 0.567181 | [
"MIT"
] | ap0llo/changelo | src/ChangeLog.Test/Configuration/ConfigurationValidatorTest.cs | 27,614 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("MeetingCalendar.TestConsole")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("MeetingCalendar.TestConsole")]
[assembly: AssemblyCopyright("Copyright © 2021")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("2d1fb966-bdea-4c86-af6d-022b830a5997")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.432432 | 84 | 0.751758 | [
"MIT"
] | AntaryamiBasuri/MeetingCalender | MeetingCalendar.TestConsole/Properties/AssemblyInfo.cs | 1,425 | C# |
/* Copyright 2015-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using System;
using System.Linq.Expressions;
using System.Threading;
namespace MongoDB.Driver.Linq
{
internal static class ExecutionPlanBuilder
{
public static Expression BuildPlan(Expression provider, QueryableTranslation translation)
{
Expression executor = Expression.Call(
provider,
"ExecuteModel",
null,
Expression.Constant(translation.Model, typeof(QueryableExecutionModel)));
executor = Expression.Convert(
executor,
typeof(IAsyncCursor<>).MakeGenericType(translation.Model.OutputType));
// we have an IAsyncCursor at this point... need to change it into an IEnumerable
executor = Expression.Call(
typeof(IAsyncCursorExtensions),
nameof(IAsyncCursorExtensions.ToEnumerable),
new Type[] { translation.Model.OutputType },
executor,
Expression.Constant(CancellationToken.None));
if (translation.ResultTransformer != null)
{
var lambda = translation.ResultTransformer.CreateAggregator(translation.Model.OutputType);
executor = Expression.Invoke(
lambda,
executor);
}
return executor;
}
public static Expression BuildAsyncPlan(Expression provider, QueryableTranslation translation, Expression cancellationToken)
{
Expression executor = Expression.Call(
provider,
"ExecuteModelAsync",
null,
Expression.Constant(translation.Model, typeof(QueryableExecutionModel)),
cancellationToken);
if (translation.ResultTransformer != null)
{
var lambda = translation.ResultTransformer.CreateAsyncAggregator(translation.Model.OutputType);
executor = Expression.Invoke(
lambda,
Expression.Convert(executor, lambda.Parameters[0].Type),
cancellationToken);
}
return executor;
}
}
}
| 36.571429 | 132 | 0.615767 | [
"MIT"
] | 13294029724/ET | Server/ThirdParty/MongoDBDriver/MongoDB.Driver/Linq/ExecutionPlanBuilder.cs | 2,818 | C# |
using System.IO;
using ISAAR.MSolve.LinearAlgebra.Input;
using ISAAR.MSolve.LinearAlgebra.Matrices.Builders;
using ISAAR.MSolve.LinearAlgebra.Output;
using ISAAR.MSolve.LinearAlgebra.Output.Formatting;
using ISAAR.MSolve.LinearAlgebra.Tests.Utilities;
using Xunit;
namespace ISAAR.MSolve.LinearAlgebra.Tests.Input
{
/// <summary>
/// Tests for <see cref="CoordinateTextFileReader"/>.
/// Authors: Serafeim Bakalakos
/// </summary>
public static class CoordinateTextFileReaderTests
{
private static readonly MatrixComparer comparer = new MatrixComparer(1E-10);
[Fact]
private static void TestRandomMatrix()
{
// Create the random matrix and write it to a temporary file
DokSymmetric originalMatrix = RandomUtilities.CreateRandomMatrix(1000, 0.2);
var coordinateWriter = new CoordinateTextFileWriter();
coordinateWriter.NumericFormat = new ExponentialFormat { NumDecimalDigits = 10 };
string tempFile = "temp.txt";
coordinateWriter.WriteToFile(originalMatrix, tempFile);
// Read the temporary file and compare it with the generated matrix
var reader = new CoordinateTextFileReader();
DokSymmetric readMatrix = reader.ReadFileAsDokSymmetricColMajor(tempFile);
bool success = comparer.AreEqual(originalMatrix, readMatrix);
// Clean up
File.Delete(tempFile);
Assert.True(success);
}
}
}
| 37.775 | 93 | 0.685639 | [
"Apache-2.0"
] | TheoChristo/MSolve.Bio | ISAAR.MSolve.LinearAlgebra.Tests/Input/CoordinateTextFileReaderTests.cs | 1,513 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.