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) 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.ResourceManager.Resources.Models
{
public partial class ApplicationNotificationPolicy : IUtf8JsonSerializable
{
void IUtf8JsonSerializable.Write(Utf8JsonWriter writer)
{
writer.WriteStartObject();
writer.WritePropertyName("notificationEndpoints");
writer.WriteStartArray();
foreach (var item in NotificationEndpoints)
{
writer.WriteObjectValue(item);
}
writer.WriteEndArray();
writer.WriteEndObject();
}
internal static ApplicationNotificationPolicy DeserializeApplicationNotificationPolicy(JsonElement element)
{
IList<ApplicationNotificationEndpoint> notificationEndpoints = default;
foreach (var property in element.EnumerateObject())
{
if (property.NameEquals("notificationEndpoints"))
{
List<ApplicationNotificationEndpoint> array = new List<ApplicationNotificationEndpoint>();
foreach (var item in property.Value.EnumerateArray())
{
array.Add(ApplicationNotificationEndpoint.DeserializeApplicationNotificationEndpoint(item));
}
notificationEndpoints = array;
continue;
}
}
return new ApplicationNotificationPolicy(notificationEndpoints);
}
}
}
| 34.816327 | 116 | 0.621923 | [
"MIT"
] | 93mishra/azure-sdk-for-net | sdk/resources/Azure.ResourceManager.Resources/src/Generated/Models/ApplicationNotificationPolicy.Serialization.cs | 1,706 | C# |
using System.Threading.Tasks;
using System.Web.Mvc;
using Abp.Application.Services.Dto;
using Abp.Web.Mvc.Authorization;
using HQF.Daily.Authorization;
using HQF.Daily.MultiTenancy;
namespace HQF.Daily.Web.Controllers
{
[AbpMvcAuthorize(PermissionNames.Pages_Tenants)]
public class TenantsController : DailyControllerBase
{
private readonly ITenantAppService _tenantAppService;
public TenantsController(ITenantAppService tenantAppService)
{
_tenantAppService = tenantAppService;
}
public async Task<ActionResult> Index()
{
var output = await _tenantAppService.GetAll(new PagedResultRequestDto { MaxResultCount = int.MaxValue }); //Paging not implemented yet
return View(output);
}
public async Task<ActionResult> EditTenantModal(int tenantId)
{
var tenantDto = await _tenantAppService.Get(new EntityDto(tenantId));
return View("_EditTenantModal", tenantDto);
}
}
} | 32.03125 | 146 | 0.693659 | [
"MIT"
] | huoxudong125/HQF.ABP.Daily | src/HQF.Daily.Web/Controllers/TenantsController.cs | 1,027 | C# |
// ******************************************************************
// /\ /| @file StateGraphExtention.cs
// \ V/ @brief 集群AI状态机扩展
// | "") @author Shadowrabbit, yingtu0401@gmail.com
// / |
// / \\ @Modified 2021-06-23 09:40:23
// *(__\_\ @Copyright Copyright (c) 2021, Shadowrabbit
// ******************************************************************
using Verse;
using Verse.AI.Group;
namespace SR.ModRimWorld.FactionalWar
{
public static class StateGraphExtention
{
public static T FindToil<T>(this StateGraph stateGraph)
{
foreach (var lordToil in stateGraph.lordToils)
{
if (lordToil is T targetToil)
{
return targetToil;
}
}
Log.Error($"[SR.ModRimWorld.FactionalWar]cant't find type {typeof(T)}");
return default;
}
}
}
| 33.333333 | 84 | 0.423 | [
"Apache-2.0"
] | Proxyer/ModRimWorldFactionalWar | 1.3/Source/ModRimworldFactionalWar/AI/Extension/StateGraphExtention.cs | 1,016 | C# |
namespace CalendarSkill.Models
{
public class FindContactDialogOptions : CalendarSkillDialogOptions
{
public FindContactDialogOptions()
{
FindContactReason = FindContactReasonType.FirstFindContact;
}
public FindContactDialogOptions(
object options,
FindContactReasonType findContactReason = FindContactReasonType.FirstFindContact,
UpdateUserNameReasonType updateUserNameReason = UpdateUserNameReasonType.NotFound,
bool promptMoreContact = true)
{
var calendarOptions = options as CalendarSkillDialogOptions;
FindContactReason = findContactReason;
UpdateUserNameReason = updateUserNameReason;
PromptMoreContact = promptMoreContact;
}
public enum FindContactReasonType
{
/// <summary>
/// FirstFindContact.
/// </summary>
FirstFindContact,
/// <summary>
/// FindContactAgain.
/// </summary>
FindContactAgain,
}
public enum UpdateUserNameReasonType
{
/// <summary>
/// NotADateTime.
/// </summary>
TooMany,
/// <summary>
/// NotFound.
/// </summary>
NotFound,
/// <summary>
/// ConfirmNo.
/// </summary>
ConfirmNo,
/// <summary>
/// ConfirmNo.
/// </summary>
Initialize,
}
public FindContactReasonType FindContactReason { get; set; }
public UpdateUserNameReasonType UpdateUserNameReason { get; set; }
public bool PromptMoreContact { get; set; }
}
}
| 27.461538 | 94 | 0.547339 | [
"MIT"
] | 3ve4me/botframework-solutions | skills/src/csharp/calendarskill/calendarskill/Models/FindContactDialogOptions.cs | 1,787 | 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 System;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class QueryTests : CompilingTestBase
{
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void DegenerateQueryExpression()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from i in c select i;
if (ReferenceEquals(c, r)) throw new Exception();
// List1<int> r = c.Select(i => i);
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1, 2, 3, 4, 5, 6, 7]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void FromClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c select i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from i in c select i')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i')
ReturnedValue:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void QueryContinuation()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from i in c select i into q select q;
if (ReferenceEquals(c, r)) throw new Exception();
// List1<int> r = c.Select(i => i);
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1, 2, 3, 4, 5, 6, 7]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void QueryContinuation_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c select i into q select q/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from i in c ... q select q')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select q')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'select i')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i')
ReturnedValue:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'q')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'q')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'q')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'q')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'q')
ReturnedValue:
IParameterReferenceOperation: q (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'q')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void Select()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from i in c select i+1;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[2, 3, 4, 5, 6, 7, 8]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void SelectClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c select i+1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from i in c select i+1')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i+1')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i+1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i+1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i+1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i+1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i+1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i+1')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void GroupBy01()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
var r = from i in c group i by i % 2;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[1, 3, 5, 7], 0:[2, 4, 6]]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void GroupByClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c group i by i % 2/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Linq.IGrouping<System.Int32, System.Int32>>) (Syntax: 'from i in c ... i by i % 2')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<System.Int32, System.Int32>> System.Linq.Enumerable.GroupBy<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> keySelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Linq.IGrouping<System.Int32, System.Int32>>, IsImplicit) (Syntax: 'group i by i % 2')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i % 2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i % 2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i % 2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i % 2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i % 2')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Remainder) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i % 2')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void GroupBy02()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
var r = from i in c group 10+i by i % 2;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[11, 13, 15, 17], 0:[12, 14, 16]]");
}
[Fact]
public void Cast()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<object> c = new List1<object>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from int i in c select i;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1, 2, 3, 4, 5, 6, 7]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void CastInFromClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<object> c = new List<object>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from int i in c select i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int i in c select i')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int i in c')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int i in c')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Object>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i')
ReturnedValue:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void Where()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<object> c = new List1<object>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from int i in c where i < 5 select i;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1, 2, 3, 4]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void WhereClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<object> c = new List<object>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from int i in c where i < 5 select i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int i ... 5 select i')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Where<System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Boolean> predicate)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'where i < 5')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int i in c')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int i in c')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Object>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i < 5')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Boolean>, IsImplicit) (Syntax: 'i < 5')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i < 5')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i < 5')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i < 5')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void FromJoinSelect()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3, 4, 5, 7);
List1<int> c2 = new List1<int>(10, 30, 40, 50, 60, 70);
List1<int> r = from x1 in c1
join x2 in c2 on x1 equals x2/10
select x1+x2;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[11, 33, 44, 55, 77]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void FromJoinSelect_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c1 = new List<int>() {1, 2, 3, 4, 5, 6, 7};
List<int> c2 = new List<int>() {10, 30, 40, 50, 60, 70};
var r = /*<bind>*/from x1 in c1
join x2 in c2 on x1 equals x2/10
select x1+x2/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from x1 in ... elect x1+x2')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Join<System.Int32, System.Int32, System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> outer, System.Collections.Generic.IEnumerable<System.Int32> inner, System.Func<System.Int32, System.Int32> outerKeySelector, System.Func<System.Int32, System.Int32> innerKeySelector, System.Func<System.Int32, System.Int32, System.Int32> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'join x2 in ... quals x2/10')
Instance Receiver:
null
Arguments(5):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outer) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x1 in c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from x1 in c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'x1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x1')
ReturnedValue:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x2/10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'x2/10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x2/10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x2/10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x2/10')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x2/10')
Left:
IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x1+x2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, System.Int32>, IsImplicit) (Syntax: 'x1+x2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x1+x2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x1+x2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x1+x2')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x1+x2')
Left:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x1')
Right:
IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void OrderBy()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(28, 51, 27, 84, 27, 27, 72, 64, 55, 46, 39);
var r =
from i in c
orderby i/10 descending, i%10
select i;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[84, 72, 64, 51, 55, 46, 39, 27, 27, 27, 28]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void OrderByClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c
orderby i/10 descending, i%10
select i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Linq.IOrderedEnumerable<System.Int32>) (Syntax: 'from i in c ... select i')
Expression:
IInvocationOperation (System.Linq.IOrderedEnumerable<System.Int32> System.Linq.Enumerable.ThenBy<System.Int32, System.Int32>(this System.Linq.IOrderedEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> keySelector)) (OperationKind.Invocation, Type: System.Linq.IOrderedEnumerable<System.Int32>, IsImplicit) (Syntax: 'i%10')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i/10 descending')
IInvocationOperation (System.Linq.IOrderedEnumerable<System.Int32> System.Linq.Enumerable.OrderByDescending<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> keySelector)) (OperationKind.Invocation, Type: System.Linq.IOrderedEnumerable<System.Int32>, IsImplicit) (Syntax: 'i/10 descending')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i/10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i/10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i/10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i/10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i/10')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i/10')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i%10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i%10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i%10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i%10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i%10')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Remainder) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i%10')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void GroupJoin()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3, 4, 5, 7);
List1<int> c2 = new List1<int>(12, 34, 42, 51, 52, 66, 75);
List1<string> r =
from x1 in c1
join x2 in c2 on x1 equals x2 / 10 into g
select x1 + "":"" + g.ToString();
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[12], 2:[], 3:[34], 4:[42], 5:[51, 52], 7:[75]]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void GroupJoinClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{12, 34, 42, 51, 52, 66, 75};
var r =
/*<bind>*/from x1 in c1
join x2 in c2 on x1 equals x2 / 10 into g
select x1 + "":"" + g.ToString()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.String>) (Syntax: 'from x1 in ... .ToString()')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.GroupJoin<System.Int32, System.Int32, System.Int32, System.String>(this System.Collections.Generic.IEnumerable<System.Int32> outer, System.Collections.Generic.IEnumerable<System.Int32> inner, System.Func<System.Int32, System.Int32> outerKeySelector, System.Func<System.Int32, System.Int32> innerKeySelector, System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>, System.String> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'join x2 in ... / 10 into g')
Instance Receiver:
null
Arguments(5):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outer) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x1 in c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from x1 in c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'x1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x1')
ReturnedValue:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x2 / 10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'x2 / 10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x2 / 10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x2 / 10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x2 / 10')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x2 / 10')
Left:
IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>, System.String>, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'x1 + "":"" + g.ToString()')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'x1 + "":""')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'x1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "":"") (Syntax: '"":""')
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'g.ToString()')
Instance Receiver:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'g')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void SelectMany01()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3);
List1<int> c2 = new List1<int>(10, 20, 30);
List1<int> r = from x in c1 from y in c2 select x + y;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[11, 21, 31, 12, 22, 32, 13, 23, 33]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void SelectMany_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{12, 34, 42, 51, 52, 66, 75};
var r = /*<bind>*/from x in c1 from y in c2 select x + y/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from x in c ... elect x + y')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.SelectMany<System.Int32, System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<System.Int32, System.Int32, System.Int32> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from y in c2')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x in c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from x in c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c2')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + y')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, System.Int32>, IsImplicit) (Syntax: 'x + y')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void SelectMany02()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3);
List1<int> c2 = new List1<int>(10, 20, 30);
List1<int> r = from x in c1 from int y in c2 select x + y;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[11, 21, 31, 12, 22, 32, 13, 23, 33]");
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void Let01()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3);
List1<int> r1 =
from int x in c1
let g = x * 10
let z = g + x*100
select x + z;
System.Console.WriteLine(r1);
}
}";
CompileAndVerify(csSource, expectedOutput: "[111, 222, 333]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void LetClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
var r = /*<bind>*/from int x in c1
let g = x * 10
let z = g + x*100
select x + z/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int x ... elect x + z')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, System.Int32>(this System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>> source, System.Func<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select x + z')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let z = g + x*100')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>> System.Linq.Enumerable.Select<<anonymous type: System.Int32 x, System.Int32 g>, <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 g>> source, System.Func<<anonymous type: System.Int32 x, System.Int32 g>, <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>>, IsImplicit) (Syntax: 'let z = g + x*100')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let g = x * 10')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 g>> System.Linq.Enumerable.Select<System.Int32, <anonymous type: System.Int32 x, System.Int32 g>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, <anonymous type: System.Int32 x, System.Int32 g>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 g>>, IsImplicit) (Syntax: 'let g = x * 10')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int x in c1')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int x in c1')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x * 10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, <anonymous type: System.Int32 x, System.Int32 g>>, IsImplicit) (Syntax: 'x * 10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x * 10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x * 10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x * 10')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let g = x * 10')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let g = x * ... elect x + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'let g = x * 10')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let g = x * 10')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'let g = x * 10')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let g = x * 10')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.g { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x * 10')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let g = x * 10')
Right:
IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x * 10')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'g + x*100')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 g>, <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>>, IsImplicit) (Syntax: 'g + x*100')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'g + x*100')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'g + x*100')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'g + x*100')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let z = g + x*100')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let g = x * ... elect x + z')
Left:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 g> <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let z = g + x*100')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let z = g + x*100')
Right:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let z = g + x*100')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let z = g + x*100')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'g + x*100')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let z = g + x*100')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'g + x*100')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.g { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'g')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'g')
Right:
IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x*100')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100) (Syntax: '100')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + z')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, System.Int32>, IsImplicit) (Syntax: 'x + z')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + z')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + z')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + z')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 g> <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void TransparentIdentifiers_FromLet()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
C c3 = new C(100, 200, 300);
C r1 =
from int x in c1
from int y in c2
from int z in c3
let g = x + y + z
where (x + y / 10 + z / 100) < 6
select g;
Console.WriteLine(r1);
}
}";
CompileAndVerify(csSource, expectedOutput: "[111, 211, 311, 121, 221, 131, 112, 212, 122, 113]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void TransparentIdentifiers_FromLet_IOperation()
{
string source = @"
using C = System.Collections.Generic.List<int>;
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
C c1 = new C{1, 2, 3};
C c2 = new C{10, 20, 30};
C c3 = new C{100, 200, 300};
var r1 =
/*<bind>*/from int x in c1
from int y in c2
from int z in c3
let g = x + y + z
where (x + y / 10 + z / 100) < 6
select g/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int x ... select g')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Int32>(this System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> source, System.Func<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select g')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'where (x + ... / 100) < 6')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>(this System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> source, System.Func<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Boolean> predicate)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>, IsImplicit) (Syntax: 'where (x + ... / 100) < 6')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let g = x + y + z')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>(this System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>> source, System.Func<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>, IsImplicit) (Syntax: 'let g = x + y + z')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int z in c3')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>> System.Linq.Enumerable.SelectMany<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> source, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>>, IsImplicit) (Syntax: 'from int z in c3')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> System.Linq.Enumerable.SelectMany<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int x in c1')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int x in c1')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c2')
ReturnedValue:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'from int y in c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'from int y in c2')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c3')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c3')
ReturnedValue:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c3')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c3')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c3')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c3 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int z in c3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>>, IsImplicit) (Syntax: 'from int z in c3')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'from int z in c3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'from int z in c3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'from int z in c3')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'from int z in c3')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int z in c3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'from int z in c3')
Right:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int z in c3')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int z in c3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'from int z in c3')
Right:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int z in c3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + y + z')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>, IsImplicit) (Syntax: 'x + y + z')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + y + z')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + y + z')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y + z')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'let g = x + y + z')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.<>h__TransparentIdentifier1 { get; } (OperationKind.PropertyReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let g = x + y + z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'let g = x + y + z')
Right:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let g = x + y + z')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let g = x + y + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.g { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x + y + z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'let g = x + y + z')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y + z')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'y')
Right:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Boolean>, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: '(x + y / 10 ... / 100) < 6')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y / 10 + z / 100')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y / 10')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.<>h__TransparentIdentifier1 { get; } (OperationKind.PropertyReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier2 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'x')
Right:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'y / 10')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'y')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.<>h__TransparentIdentifier1 { get; } (OperationKind.PropertyReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier2 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Right:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'z / 100')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'z')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.<>h__TransparentIdentifier1 { get; } (OperationKind.PropertyReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier2 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'z')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100) (Syntax: '100')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'g')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Int32>, IsImplicit) (Syntax: 'g')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'g')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'g')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'g')
ReturnedValue:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.g { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'g')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier2 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void TransparentIdentifiers_Join01()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
C r1 =
from int x in c1
join y in c2 on x equals y/10
let z = x+y
select z;
Console.WriteLine(r1);
}
}";
CompileAndVerify(csSource, expectedOutput: "[11, 22, 33]");
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void TransparentIdentifiers_Join02()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3, 4, 5, 7);
List1<int> c2 = new List1<int>(12, 34, 42, 51, 52, 66, 75);
List1<string> r1 = from x1 in c1
join x2 in c2 on x1 equals x2 / 10 into g
where x1 < 7
select x1 + "":"" + g.ToString();
Console.WriteLine(r1);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[12], 2:[], 3:[34], 4:[42], 5:[51, 52]]");
}
[Fact]
public void CodegenBug()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3, 4, 5, 7);
List1<int> c2 = new List1<int>(12, 34, 42, 51, 52, 66, 75);
List1<Tuple<int, List1<int>>> r1 =
c1
.GroupJoin(c2, x1 => x1, x2 => x2 / 10, (x1, g) => new Tuple<int, List1<int>>(x1, g))
;
Func1<Tuple<int, List1<int>>, bool> condition = (Tuple<int, List1<int>> TR1) => TR1.Item1 < 7;
List1<Tuple<int, List1<int>>> r2 =
r1
.Where(condition)
;
Func1<Tuple<int, List1<int>>, string> map = (Tuple<int, List1<int>> TR1) => TR1.Item1.ToString() + "":"" + TR1.Item2.ToString();
List1<string> r3 =
r2
.Select(map)
;
string r4 = r3.ToString();
Console.WriteLine(r4);
return;
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[12], 2:[], 3:[34], 4:[42], 5:[51, 52]]");
}
[Fact]
public void RangeVariables01()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
C c3 = new C(100, 200, 300);
C r1 =
from int x in c1
from int y in c2
from int z in c3
select x + y + z;
Console.WriteLine(r1);
}
}";
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
dynamic methodM = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = methodM.Body.Statements[3].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
var x = model.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
Assert.Equal("Cast", info0.CastInfo.Symbol.Name);
Assert.NotEqual(MethodKind.ReducedExtension, ((IMethodSymbol)info0.CastInfo.Symbol).MethodKind);
Assert.Null(info0.OperationInfo.Symbol);
var info1 = model.GetQueryClauseInfo(q.Body.Clauses[0]);
var y = model.GetDeclaredSymbol(q.Body.Clauses[0]);
Assert.Equal(SymbolKind.RangeVariable, y.Kind);
Assert.Equal("y", y.Name);
Assert.Equal("Cast", info1.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info1.OperationInfo.Symbol.Name);
Assert.NotEqual(MethodKind.ReducedExtension, ((IMethodSymbol)info1.OperationInfo.Symbol).MethodKind);
var info2 = model.GetQueryClauseInfo(q.Body.Clauses[1]);
var z = model.GetDeclaredSymbol(q.Body.Clauses[1]);
Assert.Equal(SymbolKind.RangeVariable, z.Kind);
Assert.Equal("z", z.Name);
Assert.Equal("Cast", info2.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info2.OperationInfo.Symbol.Name);
var info3 = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
Assert.NotNull(info3);
// what about info3's contents ???
var xPyPz = (q.Body.SelectOrGroup as SelectClauseSyntax).Expression as BinaryExpressionSyntax;
var xPy = xPyPz.Left as BinaryExpressionSyntax;
Assert.Equal(x, model.GetSemanticInfoSummary(xPy.Left).Symbol);
Assert.Equal(y, model.GetSemanticInfoSummary(xPy.Right).Symbol);
Assert.Equal(z, model.GetSemanticInfoSummary(xPyPz.Right).Symbol);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void RangeVariables_IOperation()
{
string source = @"
using C = System.Collections.Generic.List<int>;
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
C c1 = new C{1, 2, 3};
C c2 = new C{10, 20, 30};
C c3 = new C{100, 200, 300};
var r1 =
/*<bind>*/from int x in c1
from int y in c2
from int z in c3
select x + y + z/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int x ... t x + y + z')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.SelectMany<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> source, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, System.Int32> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int z in c3')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> System.Linq.Enumerable.SelectMany<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int x in c1')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int x in c1')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c2')
ReturnedValue:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'from int y in c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'from int y in c2')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... t x + y + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... t x + y + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c3')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c3')
ReturnedValue:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c3')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c3')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c3')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c3 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + y + z')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, System.Int32>, IsImplicit) (Syntax: 'x + y + z')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + y + z')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + y + z')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y + z')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y + z')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'y')
Right:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void RangeVariables02()
{
var csSource = @"
using System;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
var c1 = new int[] {1, 2, 3};
var c2 = new int[] {10, 20, 30};
var c3 = new int[] {100, 200, 300};
var r1 =
from int x in c1
from int y in c2
from int z in c3
select x + y + z;
Console.WriteLine(r1);
}
}";
var compilation = CreateCompilation(csSource);
foreach (var dd in compilation.GetDiagnostics()) Console.WriteLine(dd);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
dynamic methodM = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = methodM.Body.Statements[3].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
var x = model.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
Assert.Equal("Cast", info0.CastInfo.Symbol.Name);
Assert.Equal(MethodKind.ReducedExtension, ((IMethodSymbol)info0.CastInfo.Symbol).MethodKind);
Assert.Null(info0.OperationInfo.Symbol);
var info1 = model.GetQueryClauseInfo(q.Body.Clauses[0]);
var y = model.GetDeclaredSymbol(q.Body.Clauses[0]);
Assert.Equal(SymbolKind.RangeVariable, y.Kind);
Assert.Equal("y", y.Name);
Assert.Equal("Cast", info1.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info1.OperationInfo.Symbol.Name);
Assert.Equal(MethodKind.ReducedExtension, ((IMethodSymbol)info1.OperationInfo.Symbol).MethodKind);
var info2 = model.GetQueryClauseInfo(q.Body.Clauses[1]);
var z = model.GetDeclaredSymbol(q.Body.Clauses[1]);
Assert.Equal(SymbolKind.RangeVariable, z.Kind);
Assert.Equal("z", z.Name);
Assert.Equal("Cast", info2.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info2.OperationInfo.Symbol.Name);
var info3 = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
Assert.NotNull(info3);
// what about info3's contents ???
var xPyPz = (q.Body.SelectOrGroup as SelectClauseSyntax).Expression as BinaryExpressionSyntax;
var xPy = xPyPz.Left as BinaryExpressionSyntax;
Assert.Equal(x, model.GetSemanticInfoSummary(xPy.Left).Symbol);
Assert.Equal(y, model.GetSemanticInfoSummary(xPy.Right).Symbol);
Assert.Equal(z, model.GetSemanticInfoSummary(xPyPz.Right).Symbol);
}
[Fact]
public void TestGetSemanticInfo01()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
C r1 =
from int x in c1
from int y in c2
select x + y;
Console.WriteLine(r1);
}
}";
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
dynamic methodM = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = methodM.Body.Statements[2].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
Assert.Equal("Cast", info0.CastInfo.Symbol.Name);
Assert.Null(info0.OperationInfo.Symbol);
Assert.Equal("x", model.GetDeclaredSymbol(q.FromClause).Name);
var info1 = model.GetQueryClauseInfo(q.Body.Clauses[0]);
Assert.Equal("Cast", info1.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info1.OperationInfo.Symbol.Name);
Assert.Equal("y", model.GetDeclaredSymbol(q.Body.Clauses[0]).Name);
var info2 = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
// what about info2's contents?
}
[Fact]
public void TestGetSemanticInfo02()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(28, 51, 27, 84, 27, 27, 72, 64, 55, 46, 39);
var r =
from i in c
orderby i/10 descending, i%10
select i;
Console.WriteLine(r);
}
}";
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
dynamic methodM = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = methodM.Body.Statements[1].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
Assert.Null(info0.CastInfo.Symbol);
Assert.Null(info0.OperationInfo.Symbol);
Assert.Equal("i", model.GetDeclaredSymbol(q.FromClause).Name);
var i = model.GetDeclaredSymbol(q.FromClause);
var info1 = model.GetQueryClauseInfo(q.Body.Clauses[0]);
Assert.Null(info1.CastInfo.Symbol);
Assert.Null(info1.OperationInfo.Symbol);
Assert.Null(model.GetDeclaredSymbol(q.Body.Clauses[0]));
var order = q.Body.Clauses[0] as OrderByClauseSyntax;
var oinfo0 = model.GetSemanticInfoSummary(order.Orderings[0]);
Assert.Equal("OrderByDescending", oinfo0.Symbol.Name);
var oinfo1 = model.GetSemanticInfoSummary(order.Orderings[1]);
Assert.Equal("ThenBy", oinfo1.Symbol.Name);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(541774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541774")]
[Fact]
public void MultipleFromClauseIdentifierInExprNotInContext()
{
string source = @"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q2 = /*<bind>*/from n1 in nums
from n2 in nums
select n1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from n1 in ... select n1')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'from n2 in nums')
Children(3):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'nums')
Children(0)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'nums')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'nums')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'nums')
ReturnedValue:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'nums')
Children(0)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'n1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'n1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'n1')
ReturnedValue:
IParameterReferenceOperation: n1 (OperationKind.ParameterReference, Type: ?) (Syntax: 'n1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'nums' does not exist in the current context
// var q2 = /*<bind>*/from n1 in nums
Diagnostic(ErrorCode.ERR_NameNotInContext, "nums").WithArguments("nums").WithLocation(8, 39),
// CS0103: The name 'nums' does not exist in the current context
// from n2 in nums
Diagnostic(ErrorCode.ERR_NameNotInContext, "nums").WithArguments("nums").WithLocation(9, 29)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(541906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541906")]
[Fact]
public void NullLiteralFollowingJoinInQuery()
{
string source = @"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var query = /*<bind>*/from int i in new int[] { 1 } join null on true equals true select i/*</bind>*/; //CS1031
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from int i ... ue select i')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'join null o ... equals true')
Children(5):
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int i ... int[] { 1 }')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'new int[] { 1 }')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'new int[] { 1 }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[] { 1 }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new int[] { 1 }')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1 }')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'join null o ... equals true')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null')
Children(1):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'true')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'true')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'true')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'true')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'true')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'true')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i')
ReturnedValue:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: ?) (Syntax: 'i')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1031: Type expected
// var query = /*<bind>*/from int i in new int[] { 1 } join null on true equals true select i/*</bind>*/; //CS1031
Diagnostic(ErrorCode.ERR_TypeExpected, "null").WithLocation(8, 66),
// CS1001: Identifier expected
// var query = /*<bind>*/from int i in new int[] { 1 } join null on true equals true select i/*</bind>*/; //CS1031
Diagnostic(ErrorCode.ERR_IdentifierExpected, "null").WithLocation(8, 66),
// CS1003: Syntax error, 'in' expected
// var query = /*<bind>*/from int i in new int[] { 1 } join null on true equals true select i/*</bind>*/; //CS1031
Diagnostic(ErrorCode.ERR_SyntaxError, "null").WithArguments("in", "null").WithLocation(8, 66)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(541779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541779")]
[Fact]
public void MultipleFromClauseQueryExpr()
{
var csSource = @"
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var nums = new int[] { 3, 4 };
var q2 = from int n1 in nums
from int n2 in nums
select n1;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}";
CompileAndVerify(csSource, expectedOutput: "3 3 4 4");
}
[WorkItem(541782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541782")]
[Fact]
public void FromSelectQueryExprOnArraysWithTypeImplicit()
{
var csSource = @"
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var nums = new int[] { 3, 4 };
var q2 = from n1 in nums select n1;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}";
CompileAndVerify(csSource, expectedOutput: "3 4");
}
[WorkItem(541788, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541788")]
[Fact]
public void JoinClauseTest()
{
var csSource = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var q2 =
from a in Enumerable.Range(1, 13)
join b in Enumerable.Range(1, 13) on 4 * a equals b
select a;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}";
CompileAndVerify(csSource, expectedOutput: "1 2 3");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void JoinClause_IOperation()
{
string source = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var q2 =
/*<bind>*/from a in Enumerable.Range(1, 13)
join b in Enumerable.Range(1, 13) on 4 * a equals b
select a/*</bind>*/;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from a in E ... select a')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Join<System.Int32, System.Int32, System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> outer, System.Collections.Generic.IEnumerable<System.Int32> inner, System.Func<System.Int32, System.Int32> outerKeySelector, System.Func<System.Int32, System.Int32> innerKeySelector, System.Func<System.Int32, System.Int32, System.Int32> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'join b in E ... a equals b')
Instance Receiver:
null
Arguments(5):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outer) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Enumerable.Range(1, 13)')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Range(System.Int32 start, System.Int32 count)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'Enumerable.Range(1, 13)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: start) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: count) (OperationKind.Argument, Type: null) (Syntax: '13')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 13) (Syntax: '13')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Enumerable.Range(1, 13)')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Range(System.Int32 start, System.Int32 count)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'Enumerable.Range(1, 13)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: start) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: count) (OperationKind.Argument, Type: null) (Syntax: '13')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 13) (Syntax: '13')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '4 * a')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: '4 * a')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '4 * a')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '4 * a')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '4 * a')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: '4 * a')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Right:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'b')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'b')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'b')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'b')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'b')
ReturnedValue:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'a')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, System.Int32>, IsImplicit) (Syntax: 'a')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'a')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'a')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'a')
ReturnedValue:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(541789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541789")]
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void WhereClauseTest()
{
var csSource = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
where (x > 2)
select x;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}";
CompileAndVerify(csSource, expectedOutput: "3 4");
}
[WorkItem(541942, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541942")]
[Fact]
public void WhereDefinedInType()
{
var csSource = @"
using System;
class Y
{
public int Where(Func<int, bool> predicate)
{
return 45;
}
}
class P
{
static void Main()
{
var src = new Y();
var query = from x in src
where x > 0
select x;
Console.Write(query);
}
}";
CompileAndVerify(csSource, expectedOutput: "45");
}
[Fact]
public void GetInfoForSelectExpression01()
{
string sourceCode = @"
using System;
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select x;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
SelectClauseSyntax selectClause = (SelectClauseSyntax)tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf("select", StringComparison.Ordinal)).Parent;
var info = semanticModel.GetSemanticInfoSummary(selectClause.Expression);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
Assert.Equal(SymbolKind.RangeVariable, info.Symbol.Kind);
var info2 = semanticModel.GetSemanticInfoSummary(selectClause);
var m = (MethodSymbol)info2.Symbol;
Assert.Equal("Select", m.ReducedFrom.Name);
}
[Fact]
public void GetInfoForSelectExpression02()
{
string sourceCode = @"
using System;
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select x into w
select w;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
SelectClauseSyntax selectClause = (SelectClauseSyntax)tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf("select w", StringComparison.Ordinal)).Parent;
var info = semanticModel.GetSemanticInfoSummary(selectClause.Expression);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
Assert.Equal(SymbolKind.RangeVariable, info.Symbol.Kind);
}
[Fact]
public void GetInfoForSelectExpression03()
{
string sourceCode = @"
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select x+1 into w
select w+1;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
compilation.VerifyDiagnostics();
var semanticModel = compilation.GetSemanticModel(tree);
var e = (IdentifierNameSyntax)tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf("x+1", StringComparison.Ordinal)).Parent;
var info = semanticModel.GetSemanticInfoSummary(e);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
Assert.Equal(SymbolKind.RangeVariable, info.Symbol.Kind);
Assert.Equal("x", info.Symbol.Name);
e = (IdentifierNameSyntax)tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf("w+1", StringComparison.Ordinal)).Parent;
info = semanticModel.GetSemanticInfoSummary(e);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
Assert.Equal(SymbolKind.RangeVariable, info.Symbol.Kind);
Assert.Equal("w", info.Symbol.Name);
var e2 = e.Parent as ExpressionSyntax; // w+1
var info2 = semanticModel.GetSemanticInfoSummary(e2);
Assert.Equal(SpecialType.System_Int32, info2.Type.SpecialType);
Assert.Equal("System.Int32 System.Int32.op_Addition(System.Int32 left, System.Int32 right)", info2.Symbol.ToTestDisplayString());
}
[WorkItem(541806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541806")]
[Fact]
public void GetDeclaredSymbolForQueryContinuation()
{
string sourceCode = @"
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select x into w
select w;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var queryContinuation = tree.GetRoot().FindToken(sourceCode.IndexOf("into w", StringComparison.Ordinal)).Parent;
var symbol = semanticModel.GetDeclaredSymbol(queryContinuation);
Assert.NotNull(symbol);
Assert.Equal("w", symbol.Name);
Assert.Equal(SymbolKind.RangeVariable, symbol.Kind);
}
[WorkItem(541899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541899")]
[Fact]
public void ComputeQueryVariableType()
{
string sourceCode = @"
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select 5;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var selectExpression = tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf('5'));
var info = semanticModel.GetSpeculativeTypeInfo(selectExpression.SpanStart, SyntaxFactory.ParseExpression("x"), SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
}
[WorkItem(541893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541893")]
[Fact]
public void GetDeclaredSymbolForJoinIntoClause()
{
string sourceCode = @"
using System;
using System.Linq;
static class Test
{
static void Main()
{
var qie = from x3 in new int[] { 0 }
join x7 in (new int[] { 0 }) on 5 equals 5 into x8
select x8;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var joinInto = tree.GetRoot().FindToken(sourceCode.IndexOf("into x8", StringComparison.Ordinal)).Parent;
var symbol = semanticModel.GetDeclaredSymbol(joinInto);
Assert.NotNull(symbol);
Assert.Equal("x8", symbol.Name);
Assert.Equal(SymbolKind.RangeVariable, symbol.Kind);
Assert.Equal("? x8", symbol.ToTestDisplayString());
}
[WorkItem(541982, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541982")]
[WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")]
[Fact()]
public void GetDeclaredSymbolAddAccessorDeclIncompleteQuery()
{
string sourceCode = @"
using System;
using System.Linq;
public class QueryExpressionTest
{
public static void Main()
{
var expr1 = new[] { 1, 2, 3, 4, 5 };
var query1 = from event in expr1 select event;
var query2 = from int
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var unknownAccessorDecls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>();
var symbols = unknownAccessorDecls.Select(decl => semanticModel.GetDeclaredSymbol(decl));
Assert.True(symbols.All(s => ReferenceEquals(s, null)));
}
[WorkItem(542235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542235")]
[Fact]
public void TwoFromClauseFollowedBySelectClause()
{
string sourceCode = @"
using System.Linq;
class Test
{
public static void Main()
{
var q2 = from num1 in new int[] { 4, 5 }
from num2 in new int[] { 4, 5 }
select num1;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var selectClause = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SelectClause)).Single() as SelectClauseSyntax;
var fromClause1 = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => (n.IsKind(SyntaxKind.FromClause)) && (n.ToString().Contains("num1"))).Single() as FromClauseSyntax;
var fromClause2 = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => (n.IsKind(SyntaxKind.FromClause)) && (n.ToString().Contains("num2"))).Single() as FromClauseSyntax;
var symbolInfoForSelect = semanticModel.GetSemanticInfoSummary(selectClause);
var queryInfoForFrom1 = semanticModel.GetQueryClauseInfo(fromClause1);
var queryInfoForFrom2 = semanticModel.GetQueryClauseInfo(fromClause2);
Assert.Null(queryInfoForFrom1.CastInfo.Symbol);
Assert.Null(queryInfoForFrom1.OperationInfo.Symbol);
Assert.Null(queryInfoForFrom2.CastInfo.Symbol);
Assert.Equal("SelectMany", queryInfoForFrom2.OperationInfo.Symbol.Name);
Assert.Null(symbolInfoForSelect.Symbol);
Assert.Empty(symbolInfoForSelect.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfoForSelect.CandidateReason);
}
[WorkItem(528747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528747")]
[Fact]
public void SemanticInfoForOrderingClauses()
{
string sourceCode = @"
using System;
using System.Linq;
public class QueryExpressionTest
{
public static void Main()
{
var q1 =
from x in new int[] { 4, 5 }
orderby
x descending,
x.ToString() ascending,
x descending
select x;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
int count = 0;
string[] names = { "OrderByDescending", "ThenBy", "ThenByDescending" };
foreach (var ordering in tree.GetCompilationUnitRoot().DescendantNodes().OfType<OrderingSyntax>())
{
var symbolInfo = model.GetSemanticInfoSummary(ordering);
Assert.Equal(names[count++], symbolInfo.Symbol.Name);
}
Assert.Equal(3, count);
}
[WorkItem(542266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542266")]
[Fact]
public void FromOrderBySelectQueryTranslation()
{
string sourceCode = @"
using System;
using System.Collections;
using System.Collections.Generic;
public interface IOrderedEnumerable<TElement> : IEnumerable<TElement>,
IEnumerable
{
}
public static class Extensions
{
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
return null;
}
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TResult> selector)
{
return null;
}
}
class Program
{
static void Main(string[] args)
{
var q1 = from num in new int[] { 4, 5 }
orderby num
select num;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var selectClause = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SelectClause)).Single() as SelectClauseSyntax;
var symbolInfoForSelect = semanticModel.GetSemanticInfoSummary(selectClause);
Assert.Null(symbolInfoForSelect.Symbol);
}
[WorkItem(528756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528756")]
[Fact]
public void FromWhereSelectTranslation()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
public static class Extensions
{
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
return null;
}
}
class Program
{
static void Main(string[] args)
{
var q1 = from num in System.Linq.Enumerable.Range(4, 5).Where(n => n > 10)
select num;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
semanticModel.GetDiagnostics().Verify(
// (21,30): error CS1935: Could not find an implementation of the query pattern for source type 'System.Collections.Generic.IEnumerable<int>'. 'Select' not found. Are you missing a reference to 'System.Core.dll' or a using directive for 'System.Linq'?
// var q1 = from num in System.Linq.Enumerable.Range(4, 5).Where(n => n > 10)
Diagnostic(ErrorCode.ERR_QueryNoProviderStandard, "System.Linq.Enumerable.Range(4, 5).Where(n => n > 10)").WithArguments("System.Collections.Generic.IEnumerable<int>", "Select"));
}
[WorkItem(528760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528760")]
[Fact]
public void FromJoinSelectTranslation()
{
string sourceCode = @"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q1 = from num in new int[] { 4, 5 }
join x1 in new int[] { 4, 5 } on num equals x1
select x1 + 5;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var selectClause = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SelectClause)).Single() as SelectClauseSyntax;
var symbolInfoForSelect = semanticModel.GetSemanticInfoSummary(selectClause);
Assert.Null(symbolInfoForSelect.Symbol);
}
[WorkItem(528761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528761")]
[WorkItem(544585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544585")]
[Fact]
public void OrderingSyntaxWithOverloadResolutionFailure()
{
string sourceCode = @"
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[] { 4, 5 };
var q1 = from num in numbers.Single()
orderby (x1) => x1.ToString()
select num;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (10,30): error CS1936: Could not find an implementation of the query pattern for source type 'int'. 'OrderBy' not found.
// var q1 = from num in numbers.Single()
Diagnostic(ErrorCode.ERR_QueryNoProvider, "numbers.Single()").WithArguments("int", "OrderBy")
);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var orderingClause = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.AscendingOrdering)).Single() as OrderingSyntax;
var symbolInfoForOrdering = semanticModel.GetSemanticInfoSummary(orderingClause);
Assert.Null(symbolInfoForOrdering.Symbol);
}
[WorkItem(542292, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542292")]
[Fact]
public void EmitIncompleteQueryWithSyntaxErrors()
{
string sourceCode = @"
using System.Linq;
class Program
{
static int Main()
{
int [] goo = new int [] {1};
var q = from x in goo
select x + 1 into z
select z.T
";
using (var output = new MemoryStream())
{
Assert.False(CreateCompilationWithMscorlib40AndSystemCore(sourceCode).Emit(output).Success);
}
}
[WorkItem(542294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542294")]
[Fact]
public void EmitQueryWithBindErrors()
{
string sourceCode = @"
using System.Linq;
class Program
{
static void Main()
{
int[] nums = { 0, 1, 2, 3, 4, 5 };
var query = from num in nums
let num = 3 // CS1930
select num;
}
}";
using (var output = new MemoryStream())
{
Assert.False(CreateCompilationWithMscorlib40AndSystemCore(sourceCode).Emit(output).Success);
}
}
[WorkItem(542372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542372")]
[Fact]
public void BindToIncompleteSelectManyDecl()
{
string sourceCode = @"
class P
{
static C<X> M2<X>(X x)
{
return new C<X>(x);
}
static void Main()
{
C<int> e1 = new C<int>(1);
var q = from x1 in M2<int>(x1)
from x2 in e1
select x1;
}
}
class C<T>
{
public C<V> SelectMany";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var diags = semanticModel.GetDiagnostics();
Assert.NotEmpty(diags);
}
[WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")]
[Fact]
public void BindIdentifierInWhereErrorTolerance()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var r = args.Where(b => b < > );
var q = from a in args
where a <>
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var diags = semanticModel.GetDiagnostics();
Assert.NotEmpty(diags);
}
[WorkItem(542460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542460")]
[Fact]
public void QueryWithMultipleParseErrorsAndScriptParseOption()
{
string sourceCode = @"
using System;
using System.Linq;
public class QueryExpressionTest
{
public static void Main()
{
var expr1 = new int[] { 1, 2, 3, 4, 5 };
var query2 = from int namespace in expr1 select namespace;
var query25 = from i in expr1 let namespace = expr1 select i;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode, parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var queryExpr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<QueryExpressionSyntax>().Where(x => x.ToFullString() == "from i in expr1 let ").Single();
var symbolInfo = semanticModel.GetSemanticInfoSummary(queryExpr);
Assert.Null(symbolInfo.Symbol);
}
[WorkItem(542496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542496")]
[Fact]
public void QueryExpressionInFieldInitReferencingAnotherFieldWithScriptParseOption()
{
string sourceCode = @"
using System.Linq;
using System.Collections;
class P
{
double one = 1;
public IEnumerable e =
from x in new int[] { 1, 2, 3 }
select x + one;
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode, parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var queryExpr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<QueryExpressionSyntax>().Single();
var symbolInfo = semanticModel.GetSemanticInfoSummary(queryExpr);
Assert.Null(symbolInfo.Symbol);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(542559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542559")]
[ConditionalFact(typeof(DesktopOnly))]
public void StaticTypeInFromClause()
{
string source = @"
using System;
using System.Linq;
class C
{
static void Main()
{
var q2 = string.Empty.Cast<GC>().Select(x => x);
var q1 = /*<bind>*/from GC x in string.Empty select x/*</bind>*/;
}
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0718: 'GC': static types cannot be used as type arguments
// var q2 = string.Empty.Cast<GC>().Select(x => x);
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "string.Empty.Cast<GC>").WithArguments("System.GC").WithLocation(9, 18),
// CS0718: 'GC': static types cannot be used as type arguments
// var q1 = /*<bind>*/from GC x in string.Empty select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "from GC x in string.Empty").WithArguments("System.GC").WithLocation(10, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from GC x i ... ty select x')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select x')
Children(2):
IInvocationOperation (System.Collections.Generic.IEnumerable<System.GC> System.Linq.Enumerable.Cast<System.GC>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.GC>, IsInvalid, IsImplicit) (Syntax: 'from GC x i ... tring.Empty')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'string.Empty')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsInvalid, IsImplicit) (Syntax: 'string.Empty')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty')
Instance Receiver:
null
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x')
ReturnedValue:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.GC) (Syntax: 'x')
", new DiagnosticDescription[] {
// CS0718: 'GC': static types cannot be used as type arguments
// var q2 = string.Empty.Cast<GC>().Select(x => x);
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "string.Empty.Cast<GC>").WithArguments("System.GC").WithLocation(9, 18),
// CS0718: 'GC': static types cannot be used as type arguments
// var q1 = /*<bind>*/from GC x in string.Empty select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "from GC x in string.Empty").WithArguments("System.GC").WithLocation(10, 28)
}, parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from GC x i ... ty select x')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select x')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'from GC x i ... tring.Empty')
Children(1):
IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty')
Instance Receiver:
null
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x')
ReturnedValue:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ?) (Syntax: 'x')
", new DiagnosticDescription[] {
// file.cs(9,31): error CS0718: 'GC': static types cannot be used as type arguments
// var q2 = string.Empty.Cast<GC>().Select(x => x);
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "Cast<GC>").WithArguments("System.GC").WithLocation(9, 31),
// file.cs(10,28): error CS0718: 'GC': static types cannot be used as type arguments
// var q1 = /*<bind>*/from GC x in string.Empty select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "from GC x in string.Empty").WithArguments("System.GC").WithLocation(10, 28)
});
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(542560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542560")]
[Fact]
public void MethodGroupInFromClause()
{
string source = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var q1 = /*<bind>*/from y in Main select y/*</bind>*/;
var q2 = Main.Select(y => y);
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from y in Main select y')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select y')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'from y in Main')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Main')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Main')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y')
ReturnedValue:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: ?) (Syntax: 'y')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0119: 'Program.Main()' is a method, which is not valid in the given context
// var q1 = /*<bind>*/from y in Main select y/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("Program.Main()", "method").WithLocation(9, 38),
// CS0119: 'Program.Main()' is a method, which is not valid in the given context
// var q2 = Main.Select(y => y);
Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("Program.Main()", "method").WithLocation(10, 18)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(542558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542558")]
[Fact]
public void SelectFromType01()
{
string sourceCode = @"using System;
using System.Collections.Generic;
class C
{
static void Main()
{
var q = from x in C select x;
}
static IEnumerable<T> Select<T>(Func<int, T> f) { return null; }
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "C").Single();
dynamic main = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = main.Body.Statements[0].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
var x = model.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
Assert.Equal(null, info0.CastInfo.Symbol);
Assert.Null(info0.OperationInfo.Symbol);
var infoSelect = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
Assert.Equal("Select", infoSelect.Symbol.Name);
}
[WorkItem(542558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542558")]
[Fact]
public void SelectFromType02()
{
string sourceCode = @"using System;
using System.Collections.Generic;
class C
{
static void Main()
{
var q = from x in C select x;
}
static Func<Func<int, object>, IEnumerable<object>> Select = null;
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "C").Single();
dynamic main = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = main.Body.Statements[0].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
var x = model.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
Assert.Equal(null, info0.CastInfo.Symbol);
Assert.Null(info0.OperationInfo.Symbol);
var infoSelect = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
Assert.Equal("Select", infoSelect.Symbol.Name);
}
[WorkItem(542624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542624")]
[Fact]
public void QueryColorColor()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
class Color
{
public static IEnumerable<T> Select<T>(Func<int, T> f) { return null; }
}
class Flavor
{
public IEnumerable<T> Select<T>(Func<int, T> f) { return null; }
}
class Program
{
Color Color;
static Flavor Flavor;
static void Main()
{
var q1 = from x in Color select x;
var q2 = from x in Flavor select x;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (17,11): warning CS0169: The field 'Program.Color' is never used
// Color Color;
Diagnostic(ErrorCode.WRN_UnreferencedField, "Color").WithArguments("Program.Color"),
// (18,19): warning CS0649: Field 'Program.Flavor' is never assigned to, and will always have its default value null
// static Flavor Flavor;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Flavor").WithArguments("Program.Flavor", "null")
);
}
[WorkItem(542704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542704")]
[Fact]
public void QueryOnSourceWithGroupByMethod()
{
string source = @"
delegate T Func<A, T>(A a);
class Y<U>
{
public U u;
public Y(U u)
{
this.u = u;
}
public string GroupBy(Func<U, string> keySelector)
{
return null;
}
}
class Test
{
static int Main()
{
Y<int> src = new Y<int>(2);
string q1 = src.GroupBy(x => x.GetType().Name); // ok
string q2 = from x in src group x by x.GetType().Name; // Roslyn CS1501
return 0;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics();
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void RangeTypeAlreadySpecified()
{
string source = @"
using System.Linq;
using System.Collections;
static class Test
{
public static void Main2()
{
var list = new CastableToArrayList();
var q = /*<bind>*/from int x in list
select x + 1/*</bind>*/;
}
}
class CastableToArrayList
{
public ArrayList Cast<T>() { return null; }
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from int x ... elect x + 1')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select x + 1')
Children(2):
IInvocationOperation ( System.Collections.ArrayList CastableToArrayList.Cast<System.Int32>()) (OperationKind.Invocation, Type: System.Collections.ArrayList, IsInvalid, IsImplicit) (Syntax: 'from int x in list')
Instance Receiver:
ILocalReferenceOperation: list (OperationKind.LocalReference, Type: CastableToArrayList, IsInvalid) (Syntax: 'list')
Arguments(0)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?) (Syntax: 'x + 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ?) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1936: Could not find an implementation of the query pattern for source type 'ArrayList'. 'Select' not found.
// var q = /*<bind>*/from int x in list
Diagnostic(ErrorCode.ERR_QueryNoProvider, "list").WithArguments("System.Collections.ArrayList", "Select").WithLocation(10, 41)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(11414, "DevDiv_Projects/Roslyn")]
[Fact]
public void InvalidQueryWithAnonTypesAndKeywords()
{
string source = @"
public class QueryExpressionTest
{
public static void Main()
{
var query7 = from i in expr1 join const in expr2 on i equals const select new { i, const };
var query8 = from int i in expr1 select new { i, const };
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
Assert.NotEmpty(compilation.GetDiagnostics());
}
[WorkItem(543787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543787")]
[ClrOnlyFact]
public void GetSymbolInfoOfSelectNodeWhenTypeOfRangeVariableIsErrorType()
{
string source = @"
using System.Linq;
class Test
{
static void V()
{
}
public static int Main()
{
var e1 = from i in V() select i;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees.First();
var index = source.IndexOf("select i", StringComparison.Ordinal);
var selectNode = tree.GetCompilationUnitRoot().FindToken(index).Parent as SelectClauseSyntax;
var model = compilation.GetSemanticModel(tree);
var symbolInfo = model.GetSymbolInfo(selectNode);
Assert.NotNull(symbolInfo);
Assert.Null(symbolInfo.Symbol); // there is no select method to call because the receiver is bad
var typeInfo = model.GetTypeInfo(selectNode);
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
}
[WorkItem(543790, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543790")]
[Fact]
public void GetQueryClauseInfoForQueryWithSyntaxErrors()
{
string source = @"
using System.Linq;
class Test
{
public static void Main ()
{
var query8 = from int i in expr1 join int delegate in expr2 on i equals delegate select new { i, delegate };
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees.First();
var index = source.IndexOf("join int delegate in expr2 on i equals delegate", StringComparison.Ordinal);
var joinNode = tree.GetCompilationUnitRoot().FindToken(index).Parent as JoinClauseSyntax;
var model = compilation.GetSemanticModel(tree);
var queryInfo = model.GetQueryClauseInfo(joinNode);
Assert.NotNull(queryInfo);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(545797, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545797")]
[Fact]
public void QueryOnNull()
{
string source = @"
using System;
static class C
{
static void Main()
{
var q = /*<bind>*/from x in null select x/*</bind>*/;
}
static object Select(this object x, Func<int, int> y)
{
return null;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Object, IsInvalid) (Syntax: 'from x in null select x')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'select x')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'from x in null')
Children(1):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
ReturnedValue:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ?, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0186: Use of null is not valid in this context
// var q = /*<bind>*/from x in null select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_NullNotValid, "select x").WithLocation(7, 42)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(545797, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545797")]
[Fact]
public void QueryOnLambda()
{
string source = @"
using System;
static class C
{
static void Main()
{
var q = /*<bind>*/from x in y => y select x/*</bind>*/;
}
static object Select(this object x, Func<int, int> y)
{
return null;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Object, IsInvalid) (Syntax: 'from x in y ... y select x')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'select x')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'from x in y => y')
Children(1):
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'y => y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y')
ReturnedValue:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: ?) (Syntax: 'y')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
ReturnedValue:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ?, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1936: Could not find an implementation of the query pattern for source type 'anonymous method'. 'Select' not found.
// var q = /*<bind>*/from x in y => y select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "select x").WithArguments("anonymous method", "Select").WithLocation(7, 44)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(545444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545444")]
[Fact]
public void RefOmittedOnComCall()
{
string source = @"using System;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
[ComImport]
[Guid(""A88A175D-2448-447A-B786-64682CBEF156"")]
public interface IRef1
{
int M(ref int x, int y);
}
public class Ref1Impl : IRef1
{
public int M(ref int x, int y) { return x + y; }
}
class Test
{
public static void Main()
{
IRef1 ref1 = new Ref1Impl();
Expression<Func<int, int, int>> F = (x, y) => ref1.M(x, y);
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (22,54): error CS2037: An expression tree lambda may not contain a COM call with ref omitted on arguments
// Expression<Func<int, int, int>> F = (x, y) => ref1.M(x, y);
Diagnostic(ErrorCode.ERR_ComRefCallInExpressionTree, "ref1.M(x, y)")
);
}
[Fact, WorkItem(5728, "https://github.com/dotnet/roslyn/issues/5728")]
public void RefOmittedOnComCallErr()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
[ComImport]
[Guid(""A88A175D-2448-447A-B786-64682CBEF156"")]
public interface IRef1
{
long M(uint y, ref int x, int z);
long M(uint y, ref int x, int z, int q);
}
public class Ref1Impl : IRef1
{
public long M(uint y, ref int x, int z) { return x + y; }
public long M(uint y, ref int x, int z, int q) { return x + y; }
}
class Test1
{
static void Test(Expression<Action<IRef1>> e)
{
}
static void Test<U>(Expression<Func<IRef1, U>> e)
{
}
public static void Main()
{
Test(ref1 => ref1.M(1, ));
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (34,32): error CS1525: Invalid expression term ')'
// Test(ref1 => ref1.M(1, ));
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(34, 32)
);
}
[WorkItem(529350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529350")]
[Fact]
public void BindLambdaBodyWhenError()
{
string source =
@"using System.Linq;
class A
{
static void Main()
{
}
static void M(System.Reflection.Assembly[] a)
{
var q2 = a.SelectMany(assem2 => assem2.UNDEFINED, (assem2, t) => t);
var q1 = from assem1 in a
from t in assem1.UNDEFINED
select t;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (10,48): error CS1061: 'System.Reflection.Assembly' does not contain a definition for 'UNDEFINED' and no extension method 'UNDEFINED' accepting a first argument of type 'System.Reflection.Assembly' could be found (are you missing a using directive or an assembly reference?)
// var q2 = a.SelectMany(assem2 => assem2.UNDEFINED, (assem2, t) => t);
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "UNDEFINED").WithArguments("System.Reflection.Assembly", "UNDEFINED"),
// (13,35): error CS1061: 'System.Reflection.Assembly' does not contain a definition for 'UNDEFINED' and no extension method 'UNDEFINED' accepting a first argument of type 'System.Reflection.Assembly' could be found (are you missing a using directive or an assembly reference?)
// from t in assem1.UNDEFINED
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "UNDEFINED").WithArguments("System.Reflection.Assembly", "UNDEFINED")
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var assem2 =
tree.GetCompilationUnitRoot().DescendantNodes(n => n.ToString().Contains("assem2"))
.Where(e => e.ToString() == "assem2")
.OfType<ExpressionSyntax>()
.Single();
var typeInfo2 = model.GetTypeInfo(assem2);
Assert.NotEqual(TypeKind.Error, typeInfo2.Type.TypeKind);
Assert.Equal("Assembly", typeInfo2.Type.Name);
var assem1 =
tree.GetCompilationUnitRoot().DescendantNodes(n => n.ToString().Contains("assem1"))
.Where(e => e.ToString() == "assem1")
.OfType<ExpressionSyntax>()
.Single();
var typeInfo1 = model.GetTypeInfo(assem1);
Assert.NotEqual(TypeKind.Error, typeInfo1.Type.TypeKind);
Assert.Equal("Assembly", typeInfo1.Type.Name);
}
[Fact]
public void TestSpeculativeSemanticModel_GetQueryClauseInfo()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
}
}";
var speculatedSource = @"
C r1 =
from int x in c1
from int y in c2
select x + y;
";
var queryStatement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.Statements[1].Span.End, queryStatement, out speculativeModel);
Assert.True(success);
var q = (QueryExpressionSyntax)queryStatement.Declaration.Variables[0].Initializer.Value;
var info0 = speculativeModel.GetQueryClauseInfo(q.FromClause);
Assert.Equal("Cast", info0.CastInfo.Symbol.Name);
Assert.Null(info0.OperationInfo.Symbol);
Assert.Equal("x", speculativeModel.GetDeclaredSymbol(q.FromClause).Name);
var info1 = speculativeModel.GetQueryClauseInfo(q.Body.Clauses[0]);
Assert.Equal("Cast", info1.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info1.OperationInfo.Symbol.Name);
Assert.Equal("y", speculativeModel.GetDeclaredSymbol(q.Body.Clauses[0]).Name);
}
[Fact]
public void TestSpeculativeSemanticModel_GetSemanticInfoForSelectClause()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
}
}";
var speculatedSource = @"
C r1 =
from int x in c1
select x;
";
var queryStatement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.Statements[1].Span.End, queryStatement, out speculativeModel);
Assert.True(success);
var q = (QueryExpressionSyntax)queryStatement.Declaration.Variables[0].Initializer.Value;
var x = speculativeModel.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
var selectExpression = (q.Body.SelectOrGroup as SelectClauseSyntax).Expression;
Assert.Equal(x, speculativeModel.GetSemanticInfoSummary(selectExpression).Symbol);
var selectClauseSymbolInfo = speculativeModel.GetSymbolInfo(q.Body.SelectOrGroup);
Assert.NotNull(selectClauseSymbolInfo.Symbol);
Assert.Equal("Select", selectClauseSymbolInfo.Symbol.Name);
var selectClauseTypeInfo = speculativeModel.GetTypeInfo(q.Body.SelectOrGroup);
Assert.NotNull(selectClauseTypeInfo.Type);
Assert.Equal("List1", selectClauseTypeInfo.Type.Name);
}
[Fact]
public void TestSpeculativeSemanticModel_GetDeclaredSymbolForJoinIntoClause()
{
string sourceCode = @"
public class Test
{
public static void Main()
{
}
}";
var speculatedSource = @"
var qie = from x3 in new int[] { 0 }
join x7 in (new int[] { 1 }) on 5 equals 5 into x8
select x8;
";
var queryStatement = SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Test").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.SpanStart, queryStatement, out speculativeModel);
var queryExpression = (QueryExpressionSyntax)((LocalDeclarationStatementSyntax)queryStatement).Declaration.Variables[0].Initializer.Value;
JoinIntoClauseSyntax joinInto = ((JoinClauseSyntax)queryExpression.Body.Clauses[0]).Into;
var symbol = speculativeModel.GetDeclaredSymbol(joinInto);
Assert.NotNull(symbol);
Assert.Equal("x8", symbol.Name);
Assert.Equal(SymbolKind.RangeVariable, symbol.Kind);
Assert.Equal("? x8", symbol.ToTestDisplayString());
}
[Fact]
public void TestSpeculativeSemanticModel_GetDeclaredSymbolForQueryContinuation()
{
string sourceCode = @"
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
}
}";
var speculatedSource = @"
var q2 = from x in nums
select x into w
select w;
";
var queryStatement = SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Test2").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.Statements[0].Span.End, queryStatement, out speculativeModel);
Assert.True(success);
var queryExpression = (QueryExpressionSyntax)((LocalDeclarationStatementSyntax)queryStatement).Declaration.Variables[0].Initializer.Value;
var queryContinuation = queryExpression.Body.Continuation;
var symbol = speculativeModel.GetDeclaredSymbol(queryContinuation);
Assert.NotNull(symbol);
Assert.Equal("w", symbol.Name);
Assert.Equal(SymbolKind.RangeVariable, symbol.Kind);
}
[Fact]
public void TestSpeculativeSemanticModel_GetSymbolInfoForOrderingClauses()
{
string sourceCode = @"
using System.Linq; // Needed for speculative code.
public class QueryExpressionTest
{
public static void Main()
{
}
}";
var speculatedSource = @"
var q1 =
from x in new int[] { 4, 5 }
orderby
x descending,
x.ToString() ascending,
x descending
select x;
";
var queryStatement = SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System.Linq; // Needed for speculative code.
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Linq;"));
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "QueryExpressionTest").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.SpanStart, queryStatement, out speculativeModel);
Assert.True(success);
int count = 0;
string[] names = { "OrderByDescending", "ThenBy", "ThenByDescending" };
foreach (var ordering in queryStatement.DescendantNodes().OfType<OrderingSyntax>())
{
var symbolInfo = speculativeModel.GetSemanticInfoSummary(ordering);
Assert.Equal(names[count++], symbolInfo.Symbol.Name);
}
Assert.Equal(3, count);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void BrokenQueryPattern()
{
string source = @"
using System;
class Q<T>
{
public Q<V> SelectMany<U, V>(Func<T, U> f1, Func<T, U, V> f2) { return null; }
public Q<U> Select<U>(Func<T, U> f1) { return null; }
//public Q<T> Where(Func<T, bool> f1) { return null; }
public X Where(Func<T, bool> f1) { return null; }
}
class X
{
public X Select<U>(Func<int, U> f1) { return null; }
}
class Program
{
static void Main(string[] args)
{
Q<int> q = null;
var r =
/*<bind>*/from x in q
from y in q
where x.ToString() == y.ToString()
select x.ToString()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: X, IsInvalid) (Syntax: 'from x in q ... .ToString()')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: X, IsInvalid, IsImplicit) (Syntax: 'select x.ToString()')
Children(2):
IInvocationOperation ( X Q<<anonymous type: System.Int32 x, Q<System.Int32> y>>.Where(System.Func<<anonymous type: System.Int32 x, Q<System.Int32> y>, System.Boolean> f1)) (OperationKind.Invocation, Type: X, IsImplicit) (Syntax: 'where x.ToS ... .ToString()')
Instance Receiver:
IInvocationOperation ( Q<<anonymous type: System.Int32 x, Q<System.Int32> y>> Q<System.Int32>.SelectMany<Q<System.Int32>, <anonymous type: System.Int32 x, Q<System.Int32> y>>(System.Func<System.Int32, Q<System.Int32>> f1, System.Func<System.Int32, Q<System.Int32>, <anonymous type: System.Int32 x, Q<System.Int32> y>> f2)) (OperationKind.Invocation, Type: Q<<anonymous type: System.Int32 x, Q<System.Int32> y>>, IsImplicit) (Syntax: 'from y in q')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: Q<System.Int32>) (Syntax: 'q')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f1) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'q')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, Q<System.Int32>>, IsImplicit) (Syntax: 'q')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'q')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'q')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'q')
ReturnedValue:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: Q<System.Int32>) (Syntax: 'q')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from y in q')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, Q<System.Int32>, <anonymous type: System.Int32 x, Q<System.Int32> y>>, IsImplicit) (Syntax: 'from y in q')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'from y in q')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'from y in q')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'from y in q')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'from y in q')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'from y in q ... .ToString()')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, Q<System.Int32> y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from y in q')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'from y in q')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from y in q')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: Q<System.Int32>, IsInvalid, IsImplicit) (Syntax: 'from y in q ... .ToString()')
Left:
IPropertyReferenceOperation: Q<System.Int32> <anonymous type: System.Int32 x, Q<System.Int32> y>.y { get; } (OperationKind.PropertyReference, Type: Q<System.Int32>, IsImplicit) (Syntax: 'from y in q')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'from y in q')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: Q<System.Int32>, IsImplicit) (Syntax: 'from y in q')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f1) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, Q<System.Int32> y>, System.Boolean>, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x.ToString( ... .ToString()')
Left:
IInvocationOperation (virtual System.String System.Int32.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x.ToString()')
Instance Receiver:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, Q<System.Int32> y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'x')
Arguments(0)
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'y.ToString()')
Instance Receiver:
IPropertyReferenceOperation: Q<System.Int32> <anonymous type: System.Int32 x, Q<System.Int32> y>.y { get; } (OperationKind.PropertyReference, Type: Q<System.Int32>) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'y')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'x.ToString()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'x.ToString()')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'x.ToString()')
ReturnedValue:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x.ToString()')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'x.ToString')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'x')
Children(1):
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8016: Transparent identifier member access failed for field 'x' of 'int'. Does the data being queried implement the query pattern?
// select x.ToString()/*</bind>*/;
Diagnostic(ErrorCode.ERR_UnsupportedTransparentIdentifierAccess, "x").WithArguments("x", "int").WithLocation(27, 20)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
[WorkItem(204561, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=204561&_a=edit")]
public void Bug204561_01()
{
string sourceCode =
@"
class C
{
public static void Main()
{
var x01 = from a in Test select a + 1;
}
}
public class Test
{
}
public static class TestExtensions
{
public static Test Select<T>(this Test x, System.Func<int, T> selector)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (6,34): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Select' not found.
// var x01 = from a in Test select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "select a + 1").WithArguments("Test", "Select").WithLocation(6, 34)
);
}
[Fact]
[WorkItem(204561, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=204561&_a=edit")]
public void Bug204561_02()
{
string sourceCode =
@"
class C
{
public static void Main()
{
var y02 = from a in Test select a + 1;
var x02 = from a in Test where a > 0 select a + 1;
}
}
class Test
{
public static Test Select<T>(System.Func<int, T> selector)
{
return null;
}
}
static class TestExtensions
{
public static Test Where(this Test x, System.Func<int, bool> filter)
{
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (7,34): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Where' not found.
// var x02 = from a in Test where a > 0 select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "where a > 0").WithArguments("Test", "Where").WithLocation(7, 34),
// (7,46): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Select' not found.
// var x02 = from a in Test where a > 0 select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "select a + 1").WithArguments("Test", "Select").WithLocation(7, 46)
);
}
[Fact]
[WorkItem(204561, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=204561&_a=edit")]
public void Bug204561_03()
{
string sourceCode =
@"
class C
{
public static void Main()
{
var y03 = from a in Test select a + 1;
var x03 = from a in Test where a > 0 select a + 1;
}
}
class Test
{
}
static class TestExtensions
{
public static Test Select<T>(this Test x, System.Func<int, T> selector)
{
return null;
}
public static Test Where(this Test x, System.Func<int, bool> filter)
{
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (6,34): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Select' not found.
// var y03 = from a in Test select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "select a + 1").WithArguments("Test", "Select").WithLocation(6, 34),
// (7,34): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Where' not found.
// var x03 = from a in Test where a > 0 select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "where a > 0").WithArguments("Test", "Where").WithLocation(7, 34)
);
}
[Fact]
[WorkItem(204561, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=204561&_a=edit")]
public void Bug204561_04()
{
string sourceCode =
@"
class C
{
public static void Main()
{
var x04 = from a in Test select a + 1;
}
}
class Test
{
public static Test Select<T>(System.Func<int, T> selector)
{
System.Console.WriteLine(""Select"");
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput: "Select");
}
[WorkItem(15910, "https://github.com/dotnet/roslyn/issues/15910")]
[Fact]
public void ExpressionVariablesInQueryClause_01()
{
var csSource = @"
using System.Linq;
class Program
{
public static void Main(string[] args)
{
var a = new[] { 1, 2, 3, 4 };
var za = from x in M(a, out var q1) select x; // ok
var zc = from x in a from y in M(a, out var z) select x; // error 1
var zd = from x in a from int y in M(a, out var z) select x; // error 2
var ze = from x in a from y in M(a, out var z) where true select x; // error 3
var zf = from x in a from int y in M(a, out var z) where true select x; // error 4
var zg = from x in a let y = M(a, out var z) select x; // error 5
var zh = from x in a where M(x, out var z) == 1 select x; // error 6
var zi = from x in a join y in M(a, out var q2) on x equals y select x; // ok
var zj = from x in a join y in a on M(x, out var z) equals y select x; // error 7
var zk = from x in a join y in a on x equals M(y, out var z) select x; // error 8
var zl = from x in a orderby M(x, out var z) select x; // error 9
var zm = from x in a orderby x, M(x, out var z) select x; // error 10
var zn = from x in a group M(x, out var z) by x; // error 11
var zo = from x in a group x by M(x, out var z); // error 12
}
public static T M<T>(T x, out T z) => z = x;
}";
CreateCompilationWithMscorlib40AndSystemCore(csSource, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (10,53): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zc = from x in a from y in M(a, out var z) select x; // error 1
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(10, 53),
// (11,57): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zd = from x in a from int y in M(a, out var z) select x; // error 2
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(11, 57),
// (12,53): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var ze = from x in a from y in M(a, out var z) where true select x; // error 3
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(12, 53),
// (13,57): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zf = from x in a from int y in M(a, out var z) where true select x; // error 4
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(13, 57),
// (14,51): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zg = from x in a let y = M(a, out var z) select x; // error 5
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(14, 51),
// (15,49): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zh = from x in a where M(x, out var z) == 1 select x; // error 6
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(15, 49),
// (17,58): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zj = from x in a join y in a on M(x, out var z) equals y select x; // error 7
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(17, 58),
// (18,67): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zk = from x in a join y in a on x equals M(y, out var z) select x; // error 8
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(18, 67),
// (19,51): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zl = from x in a orderby M(x, out var z) select x; // error 9
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(19, 51),
// (20,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zm = from x in a orderby x, M(x, out var z) select x; // error 10
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(20, 54),
// (21,49): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zn = from x in a group M(x, out var z) by x; // error 11
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(21, 49),
// (22,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zo = from x in a group x by M(x, out var z); // error 12
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(22, 54)
);
CreateCompilationWithMscorlib40AndSystemCore(csSource).VerifyDiagnostics();
}
[WorkItem(15910, "https://github.com/dotnet/roslyn/issues/15910")]
[Fact]
public void ExpressionVariablesInQueryClause_02()
{
var csSource = @"
using System.Linq;
class Program
{
public static void Main(string[] args)
{
var a = new[] { 1, 2, 3, 4 };
var za = from x in M(a, a is var q1) select x; // ok
var zc = from x in a from y in M(a, a is var z) select x; // error 1
var zd = from x in a from int y in M(a, a is var z) select x; // error 2
var ze = from x in a from y in M(a, a is var z) where true select x; // error 3
var zf = from x in a from int y in M(a, a is var z) where true select x; // error 4
var zg = from x in a let y = M(a, a is var z) select x; // error 5
var zh = from x in a where M(x, x is var z) == 1 select x; // error 6
var zi = from x in a join y in M(a, a is var q2) on x equals y select x; // ok
var zj = from x in a join y in a on M(x, x is var z) equals y select x; // error 7
var zk = from x in a join y in a on x equals M(y, y is var z) select x; // error 8
var zl = from x in a orderby M(x, x is var z) select x; // error 9
var zm = from x in a orderby x, M(x, x is var z) select x; // error 10
var zn = from x in a group M(x, x is var z) by x; // error 11
var zo = from x in a group x by M(x, x is var z); // error 12
}
public static T M<T>(T x, bool b) => x;
}";
CreateCompilationWithMscorlib40AndSystemCore(csSource, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (10,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zc = from x in a from y in M(a, a is var z) select x; // error 1
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(10, 54),
// (11,58): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zd = from x in a from int y in M(a, a is var z) select x; // error 2
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(11, 58),
// (12,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var ze = from x in a from y in M(a, a is var z) where true select x; // error 3
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(12, 54),
// (13,58): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zf = from x in a from int y in M(a, a is var z) where true select x; // error 4
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(13, 58),
// (14,52): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zg = from x in a let y = M(a, a is var z) select x; // error 5
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(14, 52),
// (15,50): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zh = from x in a where M(x, x is var z) == 1 select x; // error 6
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(15, 50),
// (17,59): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zj = from x in a join y in a on M(x, x is var z) equals y select x; // error 7
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(17, 59),
// (18,68): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zk = from x in a join y in a on x equals M(y, y is var z) select x; // error 8
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(18, 68),
// (19,52): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zl = from x in a orderby M(x, x is var z) select x; // error 9
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(19, 52),
// (20,55): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zm = from x in a orderby x, M(x, x is var z) select x; // error 10
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(20, 55),
// (21,50): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zn = from x in a group M(x, x is var z) by x; // error 11
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(21, 50),
// (22,55): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zo = from x in a group x by M(x, x is var z); // error 12
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(22, 55)
);
CreateCompilationWithMscorlib40AndSystemCore(csSource).VerifyDiagnostics();
}
[WorkItem(15910, "https://github.com/dotnet/roslyn/issues/15910")]
[Fact]
public void ExpressionVariablesInQueryClause_03()
{
var csSource = @"
using System.Linq;
class Program
{
public static void Main(string[] args)
{
var a = new[] { (1, 2), (3, 4) };
var za = from x in M(a, (int qa, int wa) = a[0]) select x; // scoping ok
var zc = from x in a from y in M(a, (int z, int w) = x) select x; // error 1
var zd = from x in a from int y in M(a, (int z, int w) = x) select x; // error 2
var ze = from x in a from y in M(a, (int z, int w) = x) where true select x; // error 3
var zf = from x in a from int y in M(a, (int z, int w) = x) where true select x; // error 4
var zg = from x in a let y = M(x, (int z, int w) = x) select x; // error 5
var zh = from x in a where M(x, (int z, int w) = x).Item1 == 1 select x; // error 6
var zi = from x in a join y in M(a, (int qi, int wi) = a[0]) on x equals y select x; // scoping ok
var zj = from x in a join y in a on M(x, (int z, int w) = x) equals y select x; // error 7
var zk = from x in a join y in a on x equals M(y, (int z, int w) = y) select x; // error 8
var zl = from x in a orderby M(x, (int z, int w) = x) select x; // error 9
var zm = from x in a orderby x, M(x, (int z, int w) = x) select x; // error 10
var zn = from x in a group M(x, (int z, int w) = x) by x; // error 11
var zo = from x in a group x by M(x, (int z, int w) = x); // error 12
}
public static T M<T>(T x, (int, int) z) => x;
}
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(csSource, parseOptions: TestOptions.Regular7_2)
.GetDiagnostics()
.Where(d => d.Code != (int)ErrorCode.ERR_DeclarationExpressionNotPermitted)
.Verify(
// (10,50): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zc = from x in a from y in M(a, (int z, int w) = x) select x; // error 1
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(10, 50),
// (11,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zd = from x in a from int y in M(a, (int z, int w) = x) select x; // error 2
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(11, 54),
// (12,50): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var ze = from x in a from y in M(a, (int z, int w) = x) where true select x; // error 3
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(12, 50),
// (13,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zf = from x in a from int y in M(a, (int z, int w) = x) where true select x; // error 4
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(13, 54),
// (14,48): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zg = from x in a let y = M(x, (int z, int w) = x) select x; // error 5
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(14, 48),
// (15,46): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zh = from x in a where M(x, (int z, int w) = x).Item1 == 1 select x; // error 6
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(15, 46),
// (17,55): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zj = from x in a join y in a on M(x, (int z, int w) = x) equals y select x; // error 7
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(17, 55),
// (18,64): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zk = from x in a join y in a on x equals M(y, (int z, int w) = y) select x; // error 8
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(18, 64),
// (19,48): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zl = from x in a orderby M(x, (int z, int w) = x) select x; // error 9
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(19, 48),
// (20,51): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zm = from x in a orderby x, M(x, (int z, int w) = x) select x; // error 10
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(20, 51),
// (21,46): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zn = from x in a group M(x, (int z, int w) = x) by x; // error 11
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(21, 46),
// (22,51): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zo = from x in a group x by M(x, (int z, int w) = x); // error 12
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(22, 51)
);
CreateCompilationWithMscorlib40AndSystemCore(csSource)
.GetDiagnostics()
.Where(d => d.Code != (int)ErrorCode.ERR_DeclarationExpressionNotPermitted)
.Verify();
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(14689, "https://github.com/dotnet/roslyn/issues/14689")]
public void SelectFromNamespaceShouldGiveAnError()
{
string source = @"
using System.Linq;
using NSAlias = ParentNamespace.ConsoleApp;
namespace ParentNamespace
{
namespace ConsoleApp
{
class Program
{
static void Main()
{
var x = from c in ConsoleApp select 3;
var y = from c in ParentNamespace.ConsoleApp select 3;
var z = /*<bind>*/from c in NSAlias select 3/*</bind>*/;
}
}
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from c in N ... as select 3')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select 3')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'from c in NSAlias')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'NSAlias')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '3')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0119: 'ConsoleApp' is a namespace, which is not valid in the given context
// var x = from c in ConsoleApp select 3;
Diagnostic(ErrorCode.ERR_BadSKunknown, "ConsoleApp").WithArguments("ConsoleApp", "namespace").WithLocation(13, 35),
// CS0119: 'ParentNamespace.ConsoleApp' is a namespace, which is not valid in the given context
// var y = from c in ParentNamespace.ConsoleApp select 3;
Diagnostic(ErrorCode.ERR_BadSKunknown, "ParentNamespace.ConsoleApp").WithArguments("ParentNamespace.ConsoleApp", "namespace").WithLocation(14, 35),
// CS0119: 'NSAlias' is a namespace, which is not valid in the given context
// var z = /*<bind>*/from c in NSAlias select 3/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadSKunknown, "NSAlias").WithArguments("NSAlias", "namespace").WithLocation(15, 45)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")]
public void LambdaParameterConflictsWithRangeVariable_01()
{
string source = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var res = /*<bind>*/from a in new[] { 1 }
select (Func<int, int>)(a => 1)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Func<System.Int32, System.Int32>>, IsInvalid) (Syntax: 'from a in n ... t>)(a => 1)')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Func<System.Int32, System.Int32>> System.Linq.Enumerable.Select<System.Int32, System.Func<System.Int32, System.Int32>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Func<System.Int32, System.Int32>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Func<System.Int32, System.Int32>>, IsInvalid, IsImplicit) (Syntax: 'select (Fun ... t>)(a => 1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from a in new[] { 1 }')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from a in new[] { 1 }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new[] { 1 }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[] { 1 }')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1 }')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Func<System.Int32, System.Int32>>, IsInvalid, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
ReturnedValue:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsInvalid) (Syntax: '(Func<int, int>)(a => 1)')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid) (Syntax: 'a => 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0136: A local or parameter named 'a' cannot be declared in this scope because that name is used in an enclosing local scope to define a local or parameter
// select (Func<int, int>)(a => 1)/*</bind>*/;
Diagnostic(ErrorCode.ERR_LocalIllegallyOverrides, "a").WithArguments("a").WithLocation(10, 43)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics, parseOptions: TestOptions.Regular7_3);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")]
public void LambdaParameterConflictsWithRangeVariable_02()
{
string source = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var res = /*<bind>*/from a in new[] { 1 }
select (Func<int, int>)(a => 1)/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Func<System.Int32, System.Int32>>) (Syntax: 'from a in n ... t>)(a => 1)')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Func<System.Int32, System.Int32>> System.Linq.Enumerable.Select<System.Int32, System.Func<System.Int32, System.Int32>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Func<System.Int32, System.Int32>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Func<System.Int32, System.Int32>>, IsImplicit) (Syntax: 'select (Fun ... t>)(a => 1)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from a in new[] { 1 }')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from a in new[] { 1 }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new[] { 1 }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new[] { 1 }')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1 }')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Func<System.Int32, System.Int32>>, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '(Func<int, int>)(a => 1)')
ReturnedValue:
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>) (Syntax: '(Func<int, int>)(a => 1)')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'a => 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '1')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void IOperationForQueryClause()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
var r = /*<bind>*/from i in c select i + 1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from i in c select i + 1')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i + 1')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i + 1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void IOperationForRangeVariableDefinition()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
var r = /*<bind>*/from i in c select i + 1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from i in c select i + 1')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i + 1')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i + 1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i + 1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i + 1')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void IOperationForRangeVariableReference()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() { 1, 2, 3, 4, 5, 6, 7 };
var r = from i in c select /*<bind>*/i/*</bind>*/ + 1;
}
}
";
string expectedOperationTree = @"
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<IdentifierNameSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact, WorkItem(21484, "https://github.com/dotnet/roslyn/issues/21484")]
public void QueryOnTypeExpression()
{
var code = @"
using System.Collections;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void M<T>() where T : IEnumerable
{
var query1 = from object a in IEnumerable select 1;
var query2 = from b in IEnumerable select 2;
var query3 = from int c in IEnumerable<int> select 3;
var query4 = from d in IEnumerable<int> select 4;
var query5 = from object d in T select 5;
var query6 = from d in T select 6;
}
}
";
var comp = CreateCompilationWithMscorlib40AndSystemCore(code);
comp.VerifyDiagnostics(
// (10,22): error CS0120: An object reference is required for the non-static field, method, or property 'Enumerable.Cast<object>(IEnumerable)'
// var query1 = from object a in IEnumerable select 1;
Diagnostic(ErrorCode.ERR_ObjectRequired, "from object a in IEnumerable").WithArguments("System.Linq.Enumerable.Cast<object>(System.Collections.IEnumerable)").WithLocation(10, 22),
// (11,32): error CS1934: Could not find an implementation of the query pattern for source type 'IEnumerable'. 'Select' not found. Consider explicitly specifying the type of the range variable 'b'.
// var query2 = from b in IEnumerable select 2;
Diagnostic(ErrorCode.ERR_QueryNoProviderCastable, "IEnumerable").WithArguments("System.Collections.IEnumerable", "Select", "b").WithLocation(11, 32),
// (13,22): error CS0120: An object reference is required for the non-static field, method, or property 'Enumerable.Cast<int>(IEnumerable)'
// var query3 = from int c in IEnumerable<int> select 3;
Diagnostic(ErrorCode.ERR_ObjectRequired, "from int c in IEnumerable<int>").WithArguments("System.Linq.Enumerable.Cast<int>(System.Collections.IEnumerable)").WithLocation(13, 22),
// (14,49): error CS1936: Could not find an implementation of the query pattern for source type 'IEnumerable<int>'. 'Select' not found.
// var query4 = from d in IEnumerable<int> select 4;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "select 4").WithArguments("System.Collections.Generic.IEnumerable<int>", "Select").WithLocation(14, 49),
// (16,22): error CS0120: An object reference is required for the non-static field, method, or property 'Enumerable.Cast<object>(IEnumerable)'
// var query5 = from object d in T select 5;
Diagnostic(ErrorCode.ERR_ObjectRequired, "from object d in T").WithArguments("System.Linq.Enumerable.Cast<object>(System.Collections.IEnumerable)").WithLocation(16, 22),
// (17,32): error CS1936: Could not find an implementation of the query pattern for source type 'T'. 'Select' not found.
// var query6 = from d in T select 6;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "T").WithArguments("T", "Select").WithLocation(17, 32)
);
}
}
}
| 66.911056 | 1,332 | 0.631747 | [
"Apache-2.0"
] | IEvangelist/roslyn | src/Compilers/CSharp/Test/Semantic/Semantics/QueryTests.cs | 297,154 | C# |
using Microsoft.AspNetCore.Mvc;
using System;
using System.ComponentModel.DataAnnotations;
namespace API_BET.Services.Contract
{
public class OfferRequest
{
public long? OfferId { get; set; }
public double? Odd { get; set; }
}
}
| 19.142857 | 44 | 0.660448 | [
"MIT"
] | benvonwyl/bet-net-core | API-BET/Services/Contract/Request/OfferRequest.cs | 270 | C# |
// Copyright (c) 2020, Phoenix Contact GmbH & Co. KG
// Licensed under the Apache License, Version 2.0
using System;
namespace Moryx.AbstractionLayer.Identity
{
/// <summary>
/// Base interface for identities (e.g. SerialNumber)
/// </summary>
public interface IIdentity : IEquatable<IIdentity>
{
/// <summary>
/// Main and unique string identifier
/// </summary>
string Identifier { get; }
/// <summary>
/// Set the identifier for this identity
/// </summary>
/// <param name="identifier"></param>
/// <exception cref="InvalidOperationException">Identifiers of some identities must not be overriden</exception>
void SetIdentifier(string identifier);
}
}
| 29.307692 | 120 | 0.624672 | [
"Apache-2.0"
] | 1nf0rmagician/MORYX-AbstractionLayer | src/Moryx.AbstractionLayer/Identity/IIdentity.cs | 762 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Security.Cryptography;
using System.Text;
using FluentAssertions;
using NUnit.Framework;
namespace Workshell.PE.Tests
{
[TestFixture]
public sealed class UtilsTests
{
[Test]
public void SizeOf_Returns_Correct_Size()
{
var output = Utils.SizeOf<uint>();
output.Should().Be(sizeof(uint));
}
[Test]
public void Read_Returns_Correct_Result()
{
var input = 0x1000U;
var bytes = BitConverter.GetBytes(input);
var output = Utils.Read<uint>(bytes);
output.Should().Be(input);
}
[Test]
public void ReadByte_Returns_Correct_Result()
{
byte input = 0x21;
var output = Utils.ReadByte(new byte[] {0x00, 0x01, 0x03, 0x07, 0x21, 0x15}, 4);
output.Should().Be(input);
}
[Test]
public void ReadInt16_Returns_Correct_Result()
{
short input = 32000;
var bytes = BitConverter.GetBytes(input);
var output = Utils.ReadInt16(bytes);
output.Should().Be(input);
}
[Test]
public void ReadInt32_Returns_Correct_Result()
{
int input = 32000;
var bytes = BitConverter.GetBytes(input);
var output = Utils.ReadInt32(bytes);
output.Should().Be(input);
}
[Test]
public void ReadInt64_Returns_Correct_Result()
{
long input = 32000;
var bytes = BitConverter.GetBytes(input);
var output = Utils.ReadInt64(bytes);
output.Should().Be(input);
}
[Test]
public void ReadUInt16_Returns_Correct_Result()
{
ushort input = 32000;
var bytes = BitConverter.GetBytes(input);
var output = Utils.ReadUInt16(bytes);
output.Should().Be(input);
}
[Test]
public void ReadUInt32_Returns_Correct_Result()
{
uint input = 32000;
var bytes = BitConverter.GetBytes(input);
var output = Utils.ReadUInt32(bytes);
output.Should().Be(input);
}
[Test]
public void ReadUInt64_Returns_Correct_Result()
{
ulong input = 32000;
var bytes = BitConverter.GetBytes(input);
var output = Utils.ReadUInt64(bytes);
output.Should().Be(input);
}
[Test]
public void Write_To_Stream_Succeeds()
{
using (var mem = new MemoryStream())
{
var buffer = new byte[ushort.MaxValue];
using (var rng = new RNGCryptoServiceProvider())
{
rng.GetBytes(buffer);
}
mem.Write(buffer, 0, buffer.Length);
mem.Length.Should().Be(ushort.MaxValue);
}
}
[Test]
public void Write_Structure_To_Buffer_Succeeds()
{
uint input = 0x1000;
var buffer = new byte[sizeof(uint)];
Utils.Write<uint>(input, buffer, 0, sizeof(uint));
var output = BitConverter.ToUInt32(buffer, 0);
output.Should().Be(input);
}
[Test]
public void Write_Structure_To_Stream_Succeeds()
{
using (var mem = new MemoryStream())
{
uint input = 0x1000;
Utils.Write<uint>(input, mem, sizeof(uint));
var output = BitConverter.ToUInt32(mem.ToArray(), 0);
output.Should().Be(input);
}
}
[TestCase(0U, "1970-01-01T00:00:00")]
[TestCase(1573219373U, "2019-11-08T13:22:53")]
public void ConvertTimeDateStamp_Returns_Correct_DateTime(uint input, string expectedValue)
{
var parsedExpectedValue = DateTime.ParseExact(expectedValue, "yyyy-MM-ddTHH:mm:ss", null);
var output = Utils.ConvertTimeDateStamp(input);
output.Should().Be(parsedExpectedValue);
}
[TestCase((byte)7, true)]
[TestCase((sbyte)-21, true)]
[TestCase((ushort)7, true)]
[TestCase((short)-21, true)]
[TestCase((uint)7, true)]
[TestCase((int)-21, true)]
[TestCase((ulong)7, true)]
[TestCase((long)-21, true)]
[TestCase((float)7.21, true)]
[TestCase((double)-21.7, true)]
[TestCase("Not numeric", false)]
[TestCase(true, false)]
public void IsNumeric_Returns_Correct_For_Given_Value(object input, bool expectedOutput)
{
var output = Utils.IsNumeric(input);
output.Should().Be(expectedOutput);
}
[TestCase((byte)7, "0x07")]
[TestCase((sbyte)-21, "0xEB")]
[TestCase((ushort)7, "0x0007")]
[TestCase((short)-21, "0xFFEB")]
[TestCase((uint)7, "0x00000007")]
[TestCase((int)-21, "0xFFFFFFEB")]
[TestCase((ulong)7, "0x0000000000000007")]
[TestCase((long)-21, "0xFFFFFFFFFFFFFFEB")]
public void IntToHex_Returns_Correct_For_Given_Value(object input, string expectedOutput)
{
var output = Utils.IntToHex(input);
output.Should().Be(expectedOutput);
}
[TestCase((float)7.21)]
[TestCase((double)-21.7)]
[TestCase("Not numeric")]
[TestCase(true)]
public void IntToHex_Throws_Exception_For_Invalid_Value(object input)
{
Assert.Throws<FormatException>(() => Utils.IntToHex(input));
}
[Test]
public void HiByte_Returns_Correct_Value()
{
ushort input = 0x8664;
var output = Utils.HiByte(input);
output.Should().Be(0x86);
}
[Test]
public void LoByte_Returns_Correct_Value()
{
ushort input = 0x8664;
var output = Utils.LoByte(input);
output.Should().Be(0x64);
}
[Test]
public void HiWord_Returns_Correct_Value()
{
uint input = 0x12344321;
var output = Utils.HiWord(input);
output.Should().Be(0x1234);
}
[Test]
public void LoWord_Returns_Correct_Value()
{
uint input = 0x12344321;
var output = Utils.LoWord(input);
output.Should().Be(0x4321);
}
[Test]
public void HiDWord_Returns_Correct_Value()
{
ulong input = 0x1234432156788765;
var output = Utils.HiDWord(input);
output.Should().Be(0x12344321);
}
[Test]
public void LoDWord_Returns_Correct_Value()
{
ulong input = 0x1234432156788765;
var output = Utils.LoDWord(input);
output.Should().Be(0x56788765);
}
[Test]
public void MakeUInt64_Returns_Correct_Value()
{
var inputMS = 0x12344321U;
var inputLS = 0x56788765U;
var output = Utils.MakeUInt64(inputMS, inputLS);
output.Should().Be(0x1234432156788765);
}
}
}
| 28.37218 | 103 | 0.521002 | [
"MIT"
] | Workshell/pe | tests/Workshell.PE.Tests/UtilsTests.cs | 7,549 | C# |
using Abstraction.Models;
using System.Threading.Tasks;
namespace Abstraction.Repositories
{
public interface ISignInRepository
{
public Task<ApplicationUser?> SignIn(string credential, string password);
public Task SignOut();
}
}
| 21.75 | 81 | 0.724138 | [
"CC0-1.0"
] | Gubbsy/MusicMatch-Server | Abstraction/Repositories/ISignInRepository.cs | 263 | C# |
using System;
using System.Linq;
namespace SQLEngine
{
public static class AbstractSqlColumnExtensions
{
public static AbstractSqlCondition In(this AbstractSqlColumn column,params string[] stringArray)
{
AbstractSqlLiteral[] expressions = stringArray.Select(x => (AbstractSqlLiteral)x).ToArray();
return column.In(expressions);
}
}
#pragma warning disable 660, 661
public abstract class AbstractSqlColumn : ISqlExpression
#pragma warning restore 660,661
{
public string Name { get; set; }
public abstract string ToSqlString();
public abstract AbstractSqlCondition Like(string expression, bool isUnicode = true);
public abstract AbstractSqlCondition IsNull();
public abstract AbstractSqlCondition IsNotNull();
public abstract AbstractSqlCondition Between(AbstractSqlLiteral from, AbstractSqlLiteral to);
public abstract AbstractSqlCondition Between(ISqlExpression from, ISqlExpression to);
public abstract AbstractSqlCondition In(Action<ISelectQueryBuilder> builderFunc);
public abstract AbstractSqlCondition In(params AbstractSqlLiteral[] expressions);
public abstract AbstractSqlCondition NotIn(params AbstractSqlLiteral[] expressions);
public abstract AbstractSqlCondition NotIn(Action<ISelectQueryBuilder> builderFunc);
protected abstract AbstractSqlExpression Subtract(AbstractSqlLiteral right);
protected abstract AbstractSqlExpression Subtract(AbstractSqlExpression right);
protected abstract AbstractSqlExpression Subtract(AbstractSqlColumn right);
protected abstract AbstractSqlExpression Divide(AbstractSqlLiteral right);
protected abstract AbstractSqlExpression Divide(AbstractSqlExpression right);
protected abstract AbstractSqlExpression Divide(AbstractSqlColumn right);
protected abstract AbstractSqlExpression Add(AbstractSqlExpression right);
protected abstract AbstractSqlExpression Add(AbstractSqlColumn right);
protected abstract AbstractSqlExpression Add(AbstractSqlLiteral right);
protected abstract AbstractSqlExpression Multiply(AbstractSqlColumn right);
protected abstract AbstractSqlExpression Multiply(AbstractSqlExpression right);
protected abstract AbstractSqlExpression Multiply(AbstractSqlLiteral right);
#region EqualTo
protected abstract AbstractSqlCondition EqualTo(AbstractSqlExpression expression);
protected abstract AbstractSqlCondition EqualTo(AbstractSqlColumn otherColumn);
protected abstract AbstractSqlCondition EqualTo(AbstractSqlLiteral value);
protected abstract AbstractSqlCondition EqualTo(int value);
protected abstract AbstractSqlCondition EqualTo(bool value);
protected abstract AbstractSqlCondition EqualTo(byte value);
protected abstract AbstractSqlCondition EqualTo(byte[] value);
protected abstract AbstractSqlCondition EqualTo(DateTime value);
protected abstract AbstractSqlCondition EqualTo(string value);
protected abstract AbstractSqlCondition EqualTo(Guid value);
protected abstract AbstractSqlCondition EqualTo(long value);
protected abstract AbstractSqlCondition EqualTo(decimal value);
protected abstract AbstractSqlCondition EqualTo(double value);
protected abstract AbstractSqlCondition EqualTo(float value);
protected abstract AbstractSqlCondition EqualTo(AbstractSqlVariable variable);
#endregion
#region NotEqualTo
protected abstract AbstractSqlCondition NotEqualTo(AbstractSqlExpression expression);
protected abstract AbstractSqlCondition NotEqualTo(AbstractSqlColumn otherColumn);
protected abstract AbstractSqlCondition NotEqualTo(AbstractSqlVariable variable);
protected abstract AbstractSqlCondition NotEqualTo(AbstractSqlLiteral value);
protected abstract AbstractSqlCondition NotEqualTo(int value);
protected abstract AbstractSqlCondition NotEqualTo(byte value);
protected abstract AbstractSqlCondition NotEqualTo(byte[] value);
protected abstract AbstractSqlCondition NotEqualTo(DateTime value);
protected abstract AbstractSqlCondition NotEqualTo(bool value);
protected abstract AbstractSqlCondition NotEqualTo(string value);
protected abstract AbstractSqlCondition NotEqualTo(Guid value);
protected abstract AbstractSqlCondition NotEqualTo(long value);
protected abstract AbstractSqlCondition NotEqualTo(decimal value);
protected abstract AbstractSqlCondition NotEqualTo(double value);
protected abstract AbstractSqlCondition NotEqualTo(float value);
#endregion
#region Greater
protected abstract AbstractSqlCondition Greater(AbstractSqlColumn otherColumn);
protected abstract AbstractSqlCondition Greater(AbstractSqlLiteral value);
protected abstract AbstractSqlCondition Greater(byte value);
protected abstract AbstractSqlCondition Greater(AbstractSqlVariable variable);
protected abstract AbstractSqlCondition Greater(DateTime value);
protected abstract AbstractSqlCondition Greater(double value);
protected abstract AbstractSqlCondition Greater(long value);
protected abstract AbstractSqlCondition Greater(int value);
#endregion
#region GreaterEqual
protected abstract AbstractSqlCondition GreaterEqual(AbstractSqlColumn otherColumn);
protected abstract AbstractSqlCondition GreaterEqual(AbstractSqlLiteral value);
protected abstract AbstractSqlCondition GreaterEqual(AbstractSqlVariable variable);
protected abstract AbstractSqlCondition GreaterEqual(byte value);
protected abstract AbstractSqlCondition GreaterEqual(DateTime value);
protected abstract AbstractSqlCondition GreaterEqual(double value);
protected abstract AbstractSqlCondition GreaterEqual(long value);
protected abstract AbstractSqlCondition GreaterEqual(int value);
#endregion
#region Less
protected abstract AbstractSqlCondition Less(AbstractSqlColumn otherColumn);
protected abstract AbstractSqlCondition Less(AbstractSqlLiteral value);
protected abstract AbstractSqlCondition Less(AbstractSqlVariable variable);
protected abstract AbstractSqlCondition Less(byte value);
protected abstract AbstractSqlCondition Less(double value);
protected abstract AbstractSqlCondition Less(int value);
protected abstract AbstractSqlCondition Less(long value);
protected abstract AbstractSqlCondition Less(DateTime value);
#endregion
#region LessEqual
protected abstract AbstractSqlCondition LessEqual(AbstractSqlColumn otherColumn);
protected abstract AbstractSqlCondition LessEqual(AbstractSqlLiteral value);
protected abstract AbstractSqlCondition LessEqual(AbstractSqlVariable variable);
protected abstract AbstractSqlCondition LessEqual(byte value);
protected abstract AbstractSqlCondition LessEqual(double value);
protected abstract AbstractSqlCondition LessEqual(long value);
protected abstract AbstractSqlCondition LessEqual(DateTime value);
protected abstract AbstractSqlCondition LessEqual(int value);
#endregion
#region <
public static AbstractSqlCondition operator <(AbstractSqlColumn x, AbstractSqlColumn y)
{
return x.Less(y);
}
public static AbstractSqlCondition operator <(AbstractSqlColumn x, AbstractSqlLiteral y)
{
return x.Less(y);
}
public static AbstractSqlCondition operator <(AbstractSqlColumn x, AbstractSqlVariable y)
{
return x.Less(y);
}
public static AbstractSqlCondition operator <(AbstractSqlColumn x, int y)
{
return x.Less(y);
}
public static AbstractSqlCondition operator <(AbstractSqlColumn x, long y)
{
return x.Less(y);
}
public static AbstractSqlCondition operator <(AbstractSqlColumn x, byte y)
{
return x.Less(y);
}
public static AbstractSqlCondition operator <(AbstractSqlColumn x, short y)
{
return x.Less(y);
}
public static AbstractSqlCondition operator <(AbstractSqlColumn x, DateTime y)
{
return x.Less(y);
}
public static AbstractSqlCondition operator <(AbstractSqlColumn x, double y)
{
return x.Less(y);
}
#endregion
#region >
public static AbstractSqlCondition operator >(AbstractSqlColumn x, AbstractSqlColumn y)
{
return x.Greater(y);
}
public static AbstractSqlCondition operator >(AbstractSqlColumn x, AbstractSqlLiteral y)
{
return x.Greater(y);
}
public static AbstractSqlCondition operator >(AbstractSqlColumn x, AbstractSqlVariable y)
{
return x.Greater(y);
}
public static AbstractSqlCondition operator >(AbstractSqlColumn x, int y)
{
return x.Greater(y);
}
public static AbstractSqlCondition operator >(AbstractSqlColumn x, long y)
{
return x.Greater(y);
}
public static AbstractSqlCondition operator >(AbstractSqlColumn x, byte y)
{
return x.Greater(y);
}
public static AbstractSqlCondition operator >(AbstractSqlColumn x, short y)
{
return x.Greater(y);
}
public static AbstractSqlCondition operator >(AbstractSqlColumn x, DateTime y)
{
return x.Greater(y);
}
public static AbstractSqlCondition operator >(AbstractSqlColumn x, double y)
{
return x.Greater(y);
}
#endregion
#region <=
public static AbstractSqlCondition operator <=(AbstractSqlColumn x, AbstractSqlColumn y)
{
return x.LessEqual(y);
}
public static AbstractSqlCondition operator <=(AbstractSqlColumn x, AbstractSqlLiteral y)
{
return x.LessEqual(y);
}
public static AbstractSqlCondition operator <=(AbstractSqlColumn x, AbstractSqlVariable y)
{
return x.LessEqual(y);
}
public static AbstractSqlCondition operator <=(AbstractSqlColumn x, int y)
{
return x.LessEqual(y);
}
public static AbstractSqlCondition operator <=(AbstractSqlColumn x, long y)
{
return x.LessEqual(y);
}
public static AbstractSqlCondition operator <=(AbstractSqlColumn x, byte y)
{
return x.LessEqual(y);
}
public static AbstractSqlCondition operator <=(AbstractSqlColumn x, short y)
{
return x.LessEqual(y);
}
public static AbstractSqlCondition operator <=(AbstractSqlColumn x, double y)
{
return x.LessEqual(y);
}
public static AbstractSqlCondition operator <=(AbstractSqlColumn x, DateTime y)
{
return x.LessEqual(y);
}
#endregion
#region >=
public static AbstractSqlCondition operator >=(AbstractSqlColumn x, AbstractSqlLiteral y)
{
return x.GreaterEqual(y);
}
public static AbstractSqlCondition operator >=(AbstractSqlColumn x, AbstractSqlColumn y)
{
return x.GreaterEqual(y);
}
public static AbstractSqlCondition operator >=(AbstractSqlColumn x, AbstractSqlVariable y)
{
return x.GreaterEqual(y);
}
public static AbstractSqlCondition operator >=(AbstractSqlColumn x, int y)
{
return x.GreaterEqual(y);
}
public static AbstractSqlCondition operator >=(AbstractSqlColumn x, long y)
{
return x.GreaterEqual(y);
}
public static AbstractSqlCondition operator >=(AbstractSqlColumn x, byte y)
{
return x.GreaterEqual(y);
}
public static AbstractSqlCondition operator >=(AbstractSqlColumn x, DateTime y)
{
return x.GreaterEqual(y);
}
public static AbstractSqlCondition operator >=(AbstractSqlColumn x, short y)
{
return x.GreaterEqual(y);
}
public static AbstractSqlCondition operator >=(AbstractSqlColumn x, double y)
{
return x.GreaterEqual(y);
}
#endregion
#region ==
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, AbstractSqlLiteral literal)
{
return column?.EqualTo(literal);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, AbstractSqlExpression expression)
{
return column?.EqualTo(expression);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, AbstractSqlColumn otherColumn)
{
return column?.EqualTo(otherColumn);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, AbstractSqlVariable otherColumn)
{
return column?.EqualTo(otherColumn);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, DateTime value)
{
return column?.EqualTo(value);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, int value)
{
return column?.EqualTo(value);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, bool value)
{
return column?.EqualTo(value);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, long value)
{
return column?.EqualTo(value);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, decimal value)
{
return column?.EqualTo(value);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, double value)
{
return column?.EqualTo(value);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, float value)
{
return column?.EqualTo(value);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, short value)
{
return column?.EqualTo(value);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, byte value)
{
return column?.EqualTo(value);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, Guid value)
{
return column?.EqualTo(value);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, byte[] value)
{
return column?.EqualTo(value);
}
public static AbstractSqlCondition operator ==(AbstractSqlColumn column, string value)
{
return column?.EqualTo(value);
}
#endregion
#region !=
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, AbstractSqlColumn otherColumn)
{
return column?.NotEqualTo(otherColumn);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, AbstractSqlExpression expression)
{
return column?.NotEqualTo(expression);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, AbstractSqlVariable otherColumn)
{
return column?.NotEqualTo(otherColumn);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, AbstractSqlLiteral literal)
{
return column?.NotEqualTo(literal);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, DateTime value)
{
return column?.NotEqualTo(value);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, bool value)
{
return column?.NotEqualTo(value);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, int value)
{
return column?.NotEqualTo(value);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, long value)
{
return column?.NotEqualTo(value);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, decimal value)
{
return column?.NotEqualTo(value);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, double value)
{
return column?.NotEqualTo(value);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, float value)
{
return column?.NotEqualTo(value);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, short value)
{
return column?.NotEqualTo(value);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, byte[] value)
{
return column?.NotEqualTo(value);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, byte value)
{
return column?.NotEqualTo(value);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, Guid value)
{
return column?.NotEqualTo(value);
}
public static AbstractSqlCondition operator !=(AbstractSqlColumn column, string value)
{
return column?.NotEqualTo(value);
}
#endregion
#region +
public static AbstractSqlExpression operator +(AbstractSqlColumn left, AbstractSqlColumn right)
{
return left.Add(right);
}
public static AbstractSqlExpression operator +(AbstractSqlColumn left, AbstractSqlLiteral right)
{
return left.Add(right);
}
public static AbstractSqlExpression operator +(AbstractSqlColumn left, AbstractSqlExpression right)
{
return left.Add(right);
}
#endregion
#region -
public static AbstractSqlExpression operator -(AbstractSqlColumn left, AbstractSqlColumn right)
{
return left.Subtract(right);
}
public static AbstractSqlExpression operator -(AbstractSqlColumn left, AbstractSqlLiteral right)
{
return left.Subtract(right);
}
public static AbstractSqlExpression operator -(AbstractSqlColumn left, AbstractSqlExpression right)
{
return left.Subtract(right);
}
#endregion
#region /
public static AbstractSqlExpression operator /(AbstractSqlColumn left, AbstractSqlColumn right)
{
return left.Divide(right);
}
public static AbstractSqlExpression operator /(AbstractSqlColumn left, AbstractSqlLiteral right)
{
return left.Divide(right);
}
public static AbstractSqlExpression operator /(AbstractSqlColumn left, AbstractSqlExpression right)
{
return left.Divide(right);
}
#endregion
#region *
public static AbstractSqlExpression operator *(AbstractSqlColumn left, AbstractSqlColumn right)
{
return left.Multiply(right);
}
public static AbstractSqlExpression operator *(AbstractSqlColumn left, AbstractSqlLiteral right)
{
return left.Multiply(right);
}
public static AbstractSqlExpression operator *(AbstractSqlColumn left, AbstractSqlExpression right)
{
return left.Multiply(right);
}
#endregion
}
} | 33.989967 | 114 | 0.666388 | [
"Apache-2.0"
] | raminrahimzada/SQLEngine | SQLEngine/Other/AbstractSqlColumn.cs | 20,328 | 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: ComplexType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.Json.Serialization;
/// <summary>
/// The type WindowsNetworkIsolationPolicy.
/// </summary>
[JsonConverter(typeof(DerivedTypeConverter<WindowsNetworkIsolationPolicy>))]
public partial class WindowsNetworkIsolationPolicy
{
/// <summary>
/// Gets or sets enterpriseCloudResources.
/// Contains a list of enterprise resource domains hosted in the cloud that need to be protected. Connections to these resources are considered enterprise data. If a proxy is paired with a cloud resource, traffic to the cloud resource will be routed through the enterprise network via the denoted proxy server (on Port 80). A proxy server used for this purpose must also be configured using the EnterpriseInternalProxyServers policy. This collection can contain a maximum of 500 elements.
/// </summary>
[JsonPropertyName("enterpriseCloudResources")]
public IEnumerable<ProxiedDomain> EnterpriseCloudResources { get; set; }
/// <summary>
/// Gets or sets enterpriseInternalProxyServers.
/// This is the comma-separated list of internal proxy servers. For example, '157.54.14.28, 157.54.11.118, 10.202.14.167, 157.53.14.163, 157.69.210.59'. These proxies have been configured by the admin to connect to specific resources on the Internet. They are considered to be enterprise network locations. The proxies are only leveraged in configuring the EnterpriseCloudResources policy to force traffic to the matched cloud resources through these proxies.
/// </summary>
[JsonPropertyName("enterpriseInternalProxyServers")]
public IEnumerable<string> EnterpriseInternalProxyServers { get; set; }
/// <summary>
/// Gets or sets enterpriseIPRanges.
/// Sets the enterprise IP ranges that define the computers in the enterprise network. Data that comes from those computers will be considered part of the enterprise and protected. These locations will be considered a safe destination for enterprise data to be shared to. This collection can contain a maximum of 500 elements.
/// </summary>
[JsonPropertyName("enterpriseIPRanges")]
public IEnumerable<IpRange> EnterpriseIPRanges { get; set; }
/// <summary>
/// Gets or sets enterpriseIPRangesAreAuthoritative.
/// Boolean value that tells the client to accept the configured list and not to use heuristics to attempt to find other subnets. Default is false.
/// </summary>
[JsonPropertyName("enterpriseIPRangesAreAuthoritative")]
public bool? EnterpriseIPRangesAreAuthoritative { get; set; }
/// <summary>
/// Gets or sets enterpriseNetworkDomainNames.
/// This is the list of domains that comprise the boundaries of the enterprise. Data from one of these domains that is sent to a device will be considered enterprise data and protected. These locations will be considered a safe destination for enterprise data to be shared to.
/// </summary>
[JsonPropertyName("enterpriseNetworkDomainNames")]
public IEnumerable<string> EnterpriseNetworkDomainNames { get; set; }
/// <summary>
/// Gets or sets enterpriseProxyServers.
/// This is a list of proxy servers. Any server not on this list is considered non-enterprise.
/// </summary>
[JsonPropertyName("enterpriseProxyServers")]
public IEnumerable<string> EnterpriseProxyServers { get; set; }
/// <summary>
/// Gets or sets enterpriseProxyServersAreAuthoritative.
/// Boolean value that tells the client to accept the configured list of proxies and not try to detect other work proxies. Default is false
/// </summary>
[JsonPropertyName("enterpriseProxyServersAreAuthoritative")]
public bool? EnterpriseProxyServersAreAuthoritative { get; set; }
/// <summary>
/// Gets or sets neutralDomainResources.
/// List of domain names that can used for work or personal resource.
/// </summary>
[JsonPropertyName("neutralDomainResources")]
public IEnumerable<string> NeutralDomainResources { get; set; }
/// <summary>
/// Gets or sets additional data.
/// </summary>
[JsonExtensionData]
public IDictionary<string, object> AdditionalData { get; set; }
/// <summary>
/// Gets or sets @odata.type.
/// </summary>
[JsonPropertyName("@odata.type")]
public string ODataType { get; set; }
}
}
| 55.031915 | 496 | 0.672144 | [
"MIT"
] | ScriptBox99/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Generated/model/WindowsNetworkIsolationPolicy.cs | 5,173 | C# |
/*
* FastStats API
*
* An API to allow access to FastStats resources
*
* OpenAPI spec version: v2
* Contact: support@apteco.com
* Generated by: https://github.com/swagger-api/swagger-codegen.git
*/
using System;
using System.Linq;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Runtime.Serialization;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using System.ComponentModel.DataAnnotations;
using SwaggerDateConverter = Apteco.OrbitSlackBot.ApiClient.Client.SwaggerDateConverter;
namespace Apteco.OrbitSlackBot.ApiClient.Model
{
/// <summary>
/// Details for how a collection is shared
/// </summary>
[DataContract]
public partial class CollectionShareDetail : IEquatable<CollectionShareDetail>, IValidatableObject
{
/// <summary>
/// Initializes a new instance of the <see cref="CollectionShareDetail" /> class.
/// </summary>
[JsonConstructorAttribute]
protected CollectionShareDetail() { }
/// <summary>
/// Initializes a new instance of the <see cref="CollectionShareDetail" /> class.
/// </summary>
/// <param name="Id">The id of the share (required).</param>
/// <param name="CollectionId">The id of the collection being shared (required).</param>
/// <param name="CollectionTitle">The title of the collection being shared (required).</param>
/// <param name="NumberOfUsersSharedWith">The number of people the collection has been shared with (required).</param>
/// <param name="ViewCollectionUrl">The URL of a page that will allow users to view the collection. (required).</param>
public CollectionShareDetail(int? Id = default(int?), int? CollectionId = default(int?), string CollectionTitle = default(string), int? NumberOfUsersSharedWith = default(int?), string ViewCollectionUrl = default(string))
{
// to ensure "Id" is required (not null)
if (Id == null)
{
throw new InvalidDataException("Id is a required property for CollectionShareDetail and cannot be null");
}
else
{
this.Id = Id;
}
// to ensure "CollectionId" is required (not null)
if (CollectionId == null)
{
throw new InvalidDataException("CollectionId is a required property for CollectionShareDetail and cannot be null");
}
else
{
this.CollectionId = CollectionId;
}
// to ensure "CollectionTitle" is required (not null)
if (CollectionTitle == null)
{
throw new InvalidDataException("CollectionTitle is a required property for CollectionShareDetail and cannot be null");
}
else
{
this.CollectionTitle = CollectionTitle;
}
// to ensure "NumberOfUsersSharedWith" is required (not null)
if (NumberOfUsersSharedWith == null)
{
throw new InvalidDataException("NumberOfUsersSharedWith is a required property for CollectionShareDetail and cannot be null");
}
else
{
this.NumberOfUsersSharedWith = NumberOfUsersSharedWith;
}
// to ensure "ViewCollectionUrl" is required (not null)
if (ViewCollectionUrl == null)
{
throw new InvalidDataException("ViewCollectionUrl is a required property for CollectionShareDetail and cannot be null");
}
else
{
this.ViewCollectionUrl = ViewCollectionUrl;
}
}
/// <summary>
/// The id of the share
/// </summary>
/// <value>The id of the share</value>
[DataMember(Name="id", EmitDefaultValue=false)]
public int? Id { get; set; }
/// <summary>
/// The id of the collection being shared
/// </summary>
/// <value>The id of the collection being shared</value>
[DataMember(Name="collectionId", EmitDefaultValue=false)]
public int? CollectionId { get; set; }
/// <summary>
/// The title of the collection being shared
/// </summary>
/// <value>The title of the collection being shared</value>
[DataMember(Name="collectionTitle", EmitDefaultValue=false)]
public string CollectionTitle { get; set; }
/// <summary>
/// The number of people the collection has been shared with
/// </summary>
/// <value>The number of people the collection has been shared with</value>
[DataMember(Name="numberOfUsersSharedWith", EmitDefaultValue=false)]
public int? NumberOfUsersSharedWith { get; set; }
/// <summary>
/// The URL of a page that will allow users to view the collection.
/// </summary>
/// <value>The URL of a page that will allow users to view the collection.</value>
[DataMember(Name="viewCollectionUrl", EmitDefaultValue=false)]
public string ViewCollectionUrl { get; set; }
/// <summary>
/// Returns the string presentation of the object
/// </summary>
/// <returns>String presentation of the object</returns>
public override string ToString()
{
var sb = new StringBuilder();
sb.Append("class CollectionShareDetail {\n");
sb.Append(" Id: ").Append(Id).Append("\n");
sb.Append(" CollectionId: ").Append(CollectionId).Append("\n");
sb.Append(" CollectionTitle: ").Append(CollectionTitle).Append("\n");
sb.Append(" NumberOfUsersSharedWith: ").Append(NumberOfUsersSharedWith).Append("\n");
sb.Append(" ViewCollectionUrl: ").Append(ViewCollectionUrl).Append("\n");
sb.Append("}\n");
return sb.ToString();
}
/// <summary>
/// Returns the JSON string presentation of the object
/// </summary>
/// <returns>JSON string presentation of the object</returns>
public string ToJson()
{
return JsonConvert.SerializeObject(this, Formatting.Indented);
}
/// <summary>
/// Returns true if objects are equal
/// </summary>
/// <param name="input">Object to be compared</param>
/// <returns>Boolean</returns>
public override bool Equals(object input)
{
return this.Equals(input as CollectionShareDetail);
}
/// <summary>
/// Returns true if CollectionShareDetail instances are equal
/// </summary>
/// <param name="input">Instance of CollectionShareDetail to be compared</param>
/// <returns>Boolean</returns>
public bool Equals(CollectionShareDetail input)
{
if (input == null)
return false;
return
(
this.Id == input.Id ||
(this.Id != null &&
this.Id.Equals(input.Id))
) &&
(
this.CollectionId == input.CollectionId ||
(this.CollectionId != null &&
this.CollectionId.Equals(input.CollectionId))
) &&
(
this.CollectionTitle == input.CollectionTitle ||
(this.CollectionTitle != null &&
this.CollectionTitle.Equals(input.CollectionTitle))
) &&
(
this.NumberOfUsersSharedWith == input.NumberOfUsersSharedWith ||
(this.NumberOfUsersSharedWith != null &&
this.NumberOfUsersSharedWith.Equals(input.NumberOfUsersSharedWith))
) &&
(
this.ViewCollectionUrl == input.ViewCollectionUrl ||
(this.ViewCollectionUrl != null &&
this.ViewCollectionUrl.Equals(input.ViewCollectionUrl))
);
}
/// <summary>
/// Gets the hash code
/// </summary>
/// <returns>Hash code</returns>
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
int hashCode = 41;
if (this.Id != null)
hashCode = hashCode * 59 + this.Id.GetHashCode();
if (this.CollectionId != null)
hashCode = hashCode * 59 + this.CollectionId.GetHashCode();
if (this.CollectionTitle != null)
hashCode = hashCode * 59 + this.CollectionTitle.GetHashCode();
if (this.NumberOfUsersSharedWith != null)
hashCode = hashCode * 59 + this.NumberOfUsersSharedWith.GetHashCode();
if (this.ViewCollectionUrl != null)
hashCode = hashCode * 59 + this.ViewCollectionUrl.GetHashCode();
return hashCode;
}
}
/// <summary>
/// To validate all properties of the instance
/// </summary>
/// <param name="validationContext">Validation context</param>
/// <returns>Validation Result</returns>
IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext)
{
yield break;
}
}
}
| 40.506276 | 228 | 0.573185 | [
"Apache-2.0"
] | Apteco/OrbitSlackBot | Apteco.OrbitSlackBot.ApiClient/Model/CollectionShareDetail.cs | 9,681 | C# |
using B32.src.assembler;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using System.Windows.Forms;
namespace B32
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new GUI());
}
}
} | 22.782609 | 65 | 0.614504 | [
"MIT"
] | L1b3r4t0r/B32 | src/assembler/Program.cs | 526 | 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/MsHTML.h in the Windows SDK for Windows 10.0.22000.0
// Original source is Copyright © Microsoft. All rights reserved.
using NUnit.Framework;
using System;
using System.Runtime.InteropServices;
using static TerraFX.Interop.Windows.IID;
namespace TerraFX.Interop.Windows.UnitTests;
/// <summary>Provides validation of the <see cref="HTMLDocumentCompatibleInfoCollection" /> struct.</summary>
public static unsafe partial class HTMLDocumentCompatibleInfoCollectionTests
{
/// <summary>Validates that the <see cref="Guid" /> of the <see cref="HTMLDocumentCompatibleInfoCollection" /> struct is correct.</summary>
[Test]
public static void GuidOfTest()
{
Assert.That(typeof(HTMLDocumentCompatibleInfoCollection).GUID, Is.EqualTo(IID_HTMLDocumentCompatibleInfoCollection));
}
/// <summary>Validates that the <see cref="HTMLDocumentCompatibleInfoCollection" /> struct is blittable.</summary>
[Test]
public static void IsBlittableTest()
{
Assert.That(Marshal.SizeOf<HTMLDocumentCompatibleInfoCollection>(), Is.EqualTo(sizeof(HTMLDocumentCompatibleInfoCollection)));
}
/// <summary>Validates that the <see cref="HTMLDocumentCompatibleInfoCollection" /> struct has the right <see cref="LayoutKind" />.</summary>
[Test]
public static void IsLayoutSequentialTest()
{
Assert.That(typeof(HTMLDocumentCompatibleInfoCollection).IsLayoutSequential, Is.True);
}
/// <summary>Validates that the <see cref="HTMLDocumentCompatibleInfoCollection" /> struct has the correct size.</summary>
[Test]
public static void SizeOfTest()
{
Assert.That(sizeof(HTMLDocumentCompatibleInfoCollection), Is.EqualTo(1));
}
}
| 42.5 | 145 | 0.748663 | [
"MIT"
] | reflectronic/terrafx.interop.windows | tests/Interop/Windows/Windows/um/MsHTML/HTMLDocumentCompatibleInfoCollectionTests.cs | 1,872 | C# |
/**
* The MIT License
* Copyright (c) 2016 Population Register Centre (VRK)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
using System;
namespace PTV.Domain.Model.Models.V2.Common
{
/// <summary>
/// View model of default area informations for organization
/// </summary>
/// <seealso cref="PTV.Domain.Model.Models.Interfaces.IVmAreaInformation" />
public class VmOrganizationAreaInformation : VmAreaInformation
{
/// <summary>
/// Gets or sets the organization identifier.
/// </summary>
/// <value>
/// The area information type identifier.
/// </value>
public Guid OrganizationId { get; set; }
}
} | 41.97561 | 80 | 0.713539 | [
"MIT"
] | MikkoVirenius/ptv-1.7 | src/PTV.Domain.Model/Models/V2/Common/VmOrganizationAreaInformation.cs | 1,723 | C# |
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
namespace BenchmarkDotNet.Disassembler
{
public class Code
{
public string TextRepresentation { get; set; }
public string Comment { get; set; }
}
public class Sharp : Code
{
public string FilePath { get; set; }
public int LineNumber { get; set; }
}
public class IL : Code
{
public int Offset { get; set; }
}
public class Asm : Code
{
/// <summary>
/// The native start offset of this ASM representation
/// </summary>
public ulong StartAddress { get; set; }
/// <summary>
/// The native end offset of this ASM representation
/// </summary>
public ulong EndAddress { get; set; }
}
public class Map
{
[XmlArray("Instructions")]
[XmlArrayItem(nameof(Code), typeof(Code))]
[XmlArrayItem(nameof(Sharp), typeof(Sharp))]
[XmlArrayItem(nameof(IL), typeof(IL))]
[XmlArrayItem(nameof(Asm), typeof(Asm))]
public List<Code> Instructions { get; set; }
}
public class DisassembledMethod
{
public string Name { get; set; }
public ulong NativeCode { get; set; }
public string Problem { get; set; }
public Map[] Maps { get; set; }
public string CommandLine { get; set; }
public static DisassembledMethod Empty(string fullSignature, ulong nativeCode, string problem)
=> new DisassembledMethod
{
Name = fullSignature,
NativeCode = nativeCode,
Maps = Array.Empty<Map>(),
Problem = problem
};
}
public class DisassemblyResult
{
public DisassembledMethod[] Methods { get; set; }
public string[] Errors { get; set; }
public DisassemblyResult()
{
Methods = new DisassembledMethod[0];
Errors = new string[0];
}
}
public static class DisassemblerConstants
{
public const string NotManagedMethod = "not managed method";
public const string DiassemblerEntryMethodName = "__ForDisassemblyDiagnoser__";
}
} | 25.942529 | 102 | 0.575986 | [
"MIT"
] | IanKemp/BenchmarkDotNet | src/BenchmarkDotNet.Disassembler.x64/DataContracts.cs | 2,259 | C# |
// <auto-generated />
using System;
using AdminUI.Data;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Infrastructure;
using Microsoft.EntityFrameworkCore.Metadata;
using Microsoft.EntityFrameworkCore.Migrations;
using Microsoft.EntityFrameworkCore.Storage.ValueConversion;
namespace AdminUI.Migrations.AdminUIUser
{
[DbContext(typeof(AdminUIUserContext))]
[Migration("20200520044603_AddFormType")]
partial class AddFormType
{
protected override void BuildTargetModel(ModelBuilder modelBuilder)
{
#pragma warning disable 612, 618
modelBuilder
.HasAnnotation("ProductVersion", "3.1.3")
.HasAnnotation("Relational:MaxIdentifierLength", 128)
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
modelBuilder.Entity("AdminUI.Areas.Identity.Data.AdminUIUser", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<int>("AccessFailedCount")
.HasColumnType("int");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Email")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<bool>("EmailConfirmed")
.HasColumnType("bit");
b.Property<bool>("LockoutEnabled")
.HasColumnType("bit");
b.Property<DateTimeOffset?>("LockoutEnd")
.HasColumnType("datetimeoffset");
b.Property<string>("Name")
.HasColumnType("nvarchar(max)");
b.Property<string>("NormalizedEmail")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedUserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("PasswordHash")
.HasColumnType("nvarchar(max)");
b.Property<string>("PhoneNumber")
.HasColumnType("nvarchar(max)");
b.Property<bool>("PhoneNumberConfirmed")
.HasColumnType("bit");
b.Property<string>("SecurityStamp")
.HasColumnType("nvarchar(max)");
b.Property<bool>("TwoFactorEnabled")
.HasColumnType("bit");
b.Property<string>("UserName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedEmail")
.HasName("EmailIndex");
b.HasIndex("NormalizedUserName")
.IsUnique()
.HasName("UserNameIndex")
.HasFilter("[NormalizedUserName] IS NOT NULL");
b.ToTable("AspNetUsers");
});
modelBuilder.Entity("AdminUI.Areas.Identity.Data.Filter", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("AdminUIUserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("ClientName")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClientPrime")
.HasColumnType("nvarchar(max)");
b.Property<DateTime>("DateFrom")
.HasColumnType("datetime2");
b.Property<DateTime>("DateTo")
.HasColumnType("datetime2");
b.Property<string>("FilterName")
.HasColumnType("nvarchar(max)");
b.Property<string>("FormType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ProviderId")
.HasColumnType("nvarchar(max)");
b.Property<string>("ProviderName")
.HasColumnType("nvarchar(max)");
b.Property<string>("Status")
.HasColumnType("nvarchar(max)");
b.HasKey("Id");
b.HasIndex("AdminUIUserId");
b.ToTable("Filter");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRole", b =>
{
b.Property<string>("Id")
.HasColumnType("nvarchar(450)");
b.Property<string>("ConcurrencyStamp")
.IsConcurrencyToken()
.HasColumnType("nvarchar(max)");
b.Property<string>("Name")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.Property<string>("NormalizedName")
.HasColumnType("nvarchar(256)")
.HasMaxLength(256);
b.HasKey("Id");
b.HasIndex("NormalizedName")
.IsUnique()
.HasName("RoleNameIndex")
.HasFilter("[NormalizedName] IS NOT NULL");
b.ToTable("AspNetRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("RoleId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("RoleId");
b.ToTable("AspNetRoleClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<string>", b =>
{
b.Property<int>("Id")
.ValueGeneratedOnAdd()
.HasColumnType("int")
.HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn);
b.Property<string>("ClaimType")
.HasColumnType("nvarchar(max)");
b.Property<string>("ClaimValue")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("Id");
b.HasIndex("UserId");
b.ToTable("AspNetUserClaims");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderKey")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("ProviderDisplayName")
.HasColumnType("nvarchar(max)");
b.Property<string>("UserId")
.IsRequired()
.HasColumnType("nvarchar(450)");
b.HasKey("LoginProvider", "ProviderKey");
b.HasIndex("UserId");
b.ToTable("AspNetUserLogins");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("RoleId")
.HasColumnType("nvarchar(450)");
b.HasKey("UserId", "RoleId");
b.HasIndex("RoleId");
b.ToTable("AspNetUserRoles");
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.Property<string>("UserId")
.HasColumnType("nvarchar(450)");
b.Property<string>("LoginProvider")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Name")
.HasColumnType("nvarchar(128)")
.HasMaxLength(128);
b.Property<string>("Value")
.HasColumnType("nvarchar(max)");
b.HasKey("UserId", "LoginProvider", "Name");
b.ToTable("AspNetUserTokens");
});
modelBuilder.Entity("AdminUI.Areas.Identity.Data.Filter", b =>
{
b.HasOne("AdminUI.Areas.Identity.Data.AdminUIUser", null)
.WithMany("Filters")
.HasForeignKey("AdminUIUserId");
});
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("AdminUI.Areas.Identity.Data.AdminUIUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<string>", b =>
{
b.HasOne("AdminUI.Areas.Identity.Data.AdminUIUser", 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("AdminUI.Areas.Identity.Data.AdminUIUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<string>", b =>
{
b.HasOne("AdminUI.Areas.Identity.Data.AdminUIUser", null)
.WithMany()
.HasForeignKey("UserId")
.OnDelete(DeleteBehavior.Cascade)
.IsRequired();
});
#pragma warning restore 612, 618
}
}
}
| 37.475904 | 125 | 0.465359 | [
"MIT"
] | Capstone-Team-C/IDD | AdminUI/Migrations/AdminUIUser/20200520044603_AddFormType.Designer.cs | 12,444 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Linq;
using Newtonsoft.Json.Serialization;
namespace Handlebars
{
public static class HandlebarsUtilities
{
/// <summary>
/// Returns the index of the start of the contents in a StringBuilder
/// </summary>
/// <param name="value">The string to find</param>
/// <param name="startIndex">The starting index.</param>
/// <param name="ignoreCase">if set to <c>true</c> it will ignore case</param>
/// <see cref="http://stackoverflow.com/questions/1359948/why-doesnt-stringbuilder-have-indexof-method"/>
/// <returns></returns>
public static int IndexOf(this StringBuilder sb, string value, int startIndex, bool ignoreCase)
{
int index;
int length = value.Length;
int maxSearchLength = (sb.Length - length) + 1;
if (ignoreCase)
{
for (int i = startIndex; i < maxSearchLength; ++i)
{
if (Char.ToLower(sb[i]) == Char.ToLower(value[0]))
{
index = 1;
while ((index < length) && (Char.ToLower(sb[i + index]) == Char.ToLower(value[index])))
++index;
if (index == length)
return i;
}
}
return -1;
}
for (int i = startIndex; i < maxSearchLength; ++i)
{
if (sb[i] == value[0])
{
index = 1;
while ((index < length) && (sb[i + index] == value[index]))
++index;
if (index == length)
return i;
}
}
return -1;
}
// public static string ToJavaScriptString(String instr)
// {
// return instr.Replace("'", @"\'")
// .Replace(@"""", @"\""");
// }
public static string ToJavaScriptString(string value)
{
return ToJavaScriptString(value, false);
}
public static string ToJavaScriptString(string value, bool addDoubleQuotes)
{
if (String.IsNullOrEmpty(value))
return addDoubleQuotes ? "\"\"" : String.Empty;
int len = value.Length;
bool needEncode = false;
char c;
for (int i = 0; i < len; i++)
{
c = value[i];
if (c >= 0 && c <= 31 || c == 34 || c == 39 || c == 60 || c == 62 || c == 92)
{
needEncode = true;
break;
}
}
if (!needEncode)
return addDoubleQuotes ? "\"" + value + "\"" : value;
var sb = new StringBuilder();
if (addDoubleQuotes)
sb.Append('"');
for (int i = 0; i < len; i++)
{
c = value[i];
if (c >= 0 && c <= 7 || c == 11 || c >= 14 && c <= 31 || c == 39 || c == 60 || c == 62)
sb.AppendFormat("\\u{0:x4}", (int)c);
else switch ((int)c)
{
case 8:
sb.Append("\\b");
break;
case 9:
sb.Append("\\t");
break;
case 10:
sb.Append("\\n");
break;
case 12:
sb.Append("\\f");
break;
case 13:
sb.Append("\\r");
break;
case 34:
sb.Append("\\\"");
break;
case 92:
sb.Append("\\\\");
break;
default:
sb.Append(c);
break;
}
}
if (addDoubleQuotes)
sb.Append('"');
return sb.ToString();
}
public static string ToJson(object context)
{
return JsonConvert.SerializeObject(context, Formatting, GetSettings());
}
private static JsonSerializerSettings _Settings;
private static JsonSerializerSettings GetSettings()
{
if (_Settings != null)
return _Settings;
var settings = new JsonSerializerSettings
{
ContractResolver = new ModelMappingResolver()
};
settings.Converters.Add(new StringEnumConverter
{
CamelCaseText = false
});
_Settings = settings;
return settings;
}
private static Formatting Formatting = Formatting.Indented;
private class ModelMappingResolver : DefaultContractResolver
{
public ModelMappingResolver()
: base(true)
{
this.DefaultMembersSearchFlags = BindingFlags.Public | BindingFlags.Instance;
}
private static readonly System.Text.RegularExpressions.Regex UnderscoreReplacement = new System.Text.RegularExpressions.Regex(@"([A-Z])([A-Z][a-z])|([a-z0-9])([A-Z])", System.Text.RegularExpressions.RegexOptions.Compiled);
protected override string ResolvePropertyName(string propertyName)
{
return UnderscoreReplacement.Replace(propertyName, "$1$3_$2$4").ToLower();
// return System.Text.RegularExpressions.Regex.Replace(propertyName, @"([A-Z])([A-Z][a-z])|([a-z0-9])([A-Z])", "$1$3_$2$4").ToLower();
}
}
}
}
| 32.380711 | 235 | 0.419815 | [
"Apache-2.0"
] | james-andrewsmith/handlebars-net | src/Handlebars/HandlebarsUtilities.cs | 6,381 | C# |
using System.Collections.Generic;
using BuildingBlocks.Core.Types;
namespace OnlineStore.Modules.Identity.Application.Users.Dtos.GatewayResponses
{
public class GeneratePasswordResetTokenResponse : GatewayResponse<string>
{
public string Token { get; }
public GeneratePasswordResetTokenResponse(string token, bool isSuccess = true,
IEnumerable<Error> errors = default) : base(token, isSuccess, errors)
{
Token = token;
}
public GeneratePasswordResetTokenResponse(IEnumerable<Error> errors) : base(errors)
{
}
}
} | 30.35 | 91 | 0.686985 | [
"MIT"
] | mehdihadeli/Modular-Monolith-Template | src/Modules/Identity/src/OnlineStore.Modules.Identity.Application/Users/Dtos/GatewayResponses/GeneratePasswordResetTokenResponse.cs | 607 | C# |
using System;
using SharpBrick.PoweredUp.Protocol.Messages;
namespace SharpBrick.PoweredUp.Protocol.Formatter
{
public class PortInputFormatSetupCombinedModeEncoder : IMessageContentEncoder
{
public ushort CalculateContentLength(LegoWirelessMessage message)
=> (ushort)(message is PortInputFormatSetupCombinedModeForSetModeDataSetMessage setMessage ? 3 + setMessage.ModeDataSets.Length : 2);
public LegoWirelessMessage Decode(byte hubId, in Span<byte> data)
=> throw new NotImplementedException();
public void Encode(LegoWirelessMessage message, in Span<byte> data)
=> Encode(message as PortInputFormatSetupCombinedModeMessage ?? throw new ArgumentException("Message not provided", nameof(message)), data);
public void Encode(PortInputFormatSetupCombinedModeMessage message, in Span<byte> data)
{
data[0] = message.PortId;
data[1] = (byte)message.SubCommand;
if (message is PortInputFormatSetupCombinedModeForSetModeDataSetMessage setMessage)
{
data[2] = setMessage.CombinationIndex;
for (int idx = 0; idx < setMessage.ModeDataSets.Length; idx++)
{
byte flag = (byte)(
((setMessage.ModeDataSets[idx].Mode & 0b0000_1111) << 4) +
(setMessage.ModeDataSets[idx].DataSet & 0b0000_1111)
);
data[3 + idx] = flag;
}
}
}
}
} | 43.027778 | 152 | 0.628793 | [
"MIT"
] | dkurok/powered-up | src/SharpBrick.PoweredUp/Protocol/Formatter/PortInputFormatSetupCombinedModeEncoder.cs | 1,551 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.ServiceModel;
namespace WCFServerLib
{
public interface IClientCallback
{
[OperationContract(IsOneWay = true)]
void SendMessageToClient(string message);
}
}
| 19.588235 | 50 | 0.702703 | [
"MIT"
] | jacking75/semina_MobileServer_WCF | Code_WCFTCPServer/WCFServerLib/IClientCallback.cs | 335 | C# |
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using TelegramBotASPnetCore.Services;
namespace TelegramBotASPnetCore
{
public class Startup
{
public Startup(IHostingEnvironment env)
{
var builder = new ConfigurationBuilder()
.SetBasePath(env.ContentRootPath)
.AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true)
.AddEnvironmentVariables();
Configuration = builder.Build();
}
public IConfiguration Configuration { get; }
// This method gets called by the runtime. Use this method to add services to the container.
public void ConfigureServices(IServiceCollection services)
{
services.AddOptions();
services.AddMvc();
services.AddSingleton<IBotService, BotService>();
services.AddSingleton(Configuration.GetSection("BotConfiguration").Get<BotConfiguration>());
}
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
app.UseMvc();
}
}
}
| 36.435897 | 106 | 0.664321 | [
"MIT"
] | ijat/TelegramBot-ASP.NETCore | TelegramBotASPnetCore/Startup.cs | 1,423 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Data.OleDb;
using System.Diagnostics.CodeAnalysis;
using Tortuga.Chain.Metadata;
namespace Tortuga.Chain.SqlServer
{
/// <summary>
/// Class OleDbSqlServerMetadataCache.
/// </summary>
/// <seealso cref="DatabaseMetadataCache{SqlServerObjectName, OleDbType}" />
public sealed partial class OleDbSqlServerMetadataCache
{
/// <summary>
/// Initializes a new instance of the <see cref="OleDbSqlServerMetadataCache"/> class.
/// </summary>
/// <param name="connectionBuilder">The connection builder.</param>
public OleDbSqlServerMetadataCache(OleDbConnectionStringBuilder connectionBuilder)
{
m_ConnectionBuilder = connectionBuilder;
}
/// <summary>
/// Returns the current database.
/// </summary>
/// <returns></returns>
public string DatabaseName
{
get
{
if (m_DatabaseName == null)
{
using (var con = new OleDbConnection(m_ConnectionBuilder.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand("SELECT DB_NAME () AS DatabaseName", con))
{
m_DatabaseName = (string)cmd.ExecuteScalar();
}
}
}
return m_DatabaseName;
}
}
/// <summary>
/// Returns the user's default schema.
/// </summary>
/// <returns></returns>
public string DefaultSchema
{
get
{
if (m_DefaultSchema == null)
{
using (var con = new OleDbConnection(m_ConnectionBuilder.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand("SELECT SCHEMA_NAME () AS DefaultSchema", con))
{
m_DefaultSchema = (string)cmd.ExecuteScalar();
}
}
}
return m_DefaultSchema;
}
}
/// <summary>
/// Gets a list of known, unsupported SQL type names that cannot be mapped to a OleDbType.
/// </summary>
/// <value>Case-insensitive list of database-specific type names</value>
/// <remarks>This list is based on driver limitations.</remarks>
public override ImmutableHashSet<string> UnsupportedSqlTypeNames { get; } = ImmutableHashSet.Create(StringComparer.OrdinalIgnoreCase, new[] { "datetimeoffset", "geography", "geometry", "hierarchyid", "image", "sql_variant", "sysname", "xml" });
/// <summary>
/// Gets the detailed metadata for a table or view.
/// </summary>
/// <param name="tableName">Name of the table.</param>
/// <returns>SqlServerTableOrViewMetadata<TDbType>.</returns>
public new SqlServerTableOrViewMetadata<OleDbType> GetTableOrView(SqlServerObjectName tableName)
{
return m_Tables.GetOrAdd(tableName, GetTableOrViewInternal);
}
/// <summary>
/// Preloads the scalar functions.
/// </summary>
public void PreloadScalarFunctions()
{
const string TvfSql =
@"SELECT
s.name AS SchemaName,
o.name AS Name,
o.object_id AS ObjectId
FROM sys.objects o
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE o.type in ('FN')";
using (var con = new OleDbConnection(m_ConnectionBuilder.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand(TvfSql, con))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var schema = reader.GetString("SchemaName");
var name = reader.GetString("Name");
GetScalarFunction(new SqlServerObjectName(schema, name));
}
}
}
}
}
/// <summary>
/// Preloads the stored procedures.
/// </summary>
public void PreloadStoredProcedures()
{
const string StoredProcedureSql =
@"SELECT
s.name AS SchemaName,
sp.name AS Name
FROM SYS.procedures sp
INNER JOIN sys.schemas s ON sp.schema_id = s.schema_id;";
using (var con = new OleDbConnection(m_ConnectionBuilder.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand(StoredProcedureSql, con))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var schema = reader.GetString("SchemaName");
var name = reader.GetString("Name");
GetStoredProcedure(new SqlServerObjectName(schema, name));
}
}
}
}
}
/// <summary>
/// Preloads the table value functions.
/// </summary>
public void PreloadTableFunctions()
{
const string TvfSql =
@"SELECT
s.name AS SchemaName,
o.name AS Name,
o.object_id AS ObjectId
FROM sys.objects o
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE o.type in ('TF', 'IF', 'FT')";
using (var con = new OleDbConnection(m_ConnectionBuilder.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand(TvfSql, con))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var schema = reader.GetString("SchemaName");
var name = reader.GetString("Name");
GetTableFunction(new SqlServerObjectName(schema, name));
}
}
}
}
}
/// <summary>
/// Preloads metadata for all tables.
/// </summary>
/// <remarks>This is normally used only for testing. By default, metadata is loaded as needed.</remarks>
public void PreloadTables()
{
const string tableList = "SELECT t.name AS Name, s.name AS SchemaName FROM sys.tables t INNER JOIN sys.schemas s ON t.schema_id=s.schema_id ORDER BY s.name, t.name";
using (var con = new OleDbConnection(m_ConnectionBuilder.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand(tableList, con))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var schema = reader.GetString("SchemaName");
var name = reader.GetString("Name");
GetTableOrView(new SqlServerObjectName(schema, name));
}
}
}
}
}
/// <summary>
/// Preloads the user defined types.
/// </summary>
/// <remarks>This is normally used only for testing. By default, metadata is loaded as needed.</remarks>
public void PreloadUserDefinedTableTypes()
{
const string tableList = @"SELECT s.name AS SchemaName, t.name AS Name FROM sys.types t INNER JOIN sys.schemas s ON t.schema_id = s.schema_id WHERE t.is_user_defined = 1;";
using (var con = new OleDbConnection(m_ConnectionBuilder.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand(tableList, con))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var schema = reader.GetString("SchemaName");
var name = reader.GetString("Name");
GetUserDefinedTableType(new SqlServerObjectName(schema, name));
}
}
}
}
}
/// <summary>
/// Preloads metadata for all views.
/// </summary>
/// <remarks>This is normally used only for testing. By default, metadata is loaded as needed.</remarks>
public void PreloadViews()
{
const string tableList = "SELECT t.name AS Name, s.name AS SchemaName FROM sys.views t INNER JOIN sys.schemas s ON t.schema_id=s.schema_id ORDER BY s.name, t.name";
using (var con = new OleDbConnection(m_ConnectionBuilder.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand(tableList, con))
{
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var schema = reader.GetString("SchemaName");
var name = reader.GetString("Name");
GetTableOrView(new SqlServerObjectName(schema, name));
}
}
}
}
}
/// <summary>
/// Converts a value to a string suitable for use in a SQL statement.
/// </summary>
/// <param name="value">The value.</param>
/// <param name="dbType">Optional database column type.</param>
/// <returns></returns>
public override string ValueToSqlValue(object value, OleDbType? dbType)
{
switch (value)
{
case string s:
{
switch (dbType)
{
case OleDbType.Char:
case OleDbType.LongVarChar:
case OleDbType.VarChar:
return "'" + s.Replace("'", "''", StringComparison.OrdinalIgnoreCase) + "'";
case OleDbType.WChar:
case OleDbType.BSTR:
case OleDbType.VarWChar:
case OleDbType.LongVarWChar:
return "N'" + s.Replace("'", "''", StringComparison.OrdinalIgnoreCase) + "'";
default: //Assume Unicode
return "N'" + s.Replace("'", "''", StringComparison.OrdinalIgnoreCase) + "'";
}
}
default:
return base.ValueToSqlValue(value, dbType);
}
}
internal ScalarFunctionMetadata<SqlServerObjectName, OleDbType> GetScalarFunctionInternal(SqlServerObjectName tableFunctionName)
{
const string sql =
@"SELECT s.name AS SchemaName,
o.name AS Name,
o.object_id AS ObjectId,
COALESCE(t.name, t2.name) AS TypeName,
p.is_nullable,
CONVERT(INT, COALESCE(p.max_length, t.max_length, t2.max_length)) AS max_length,
CONVERT(INT, COALESCE(p.precision, t.precision, t2.precision)) AS precision,
CONVERT(INT, COALESCE(p.scale, t.scale, t2.scale)) AS scale
FROM sys.objects o
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
INNER JOIN sys.parameters p ON p.object_id = o.object_id AND p.parameter_id = 0
LEFT JOIN sys.types t on p.system_type_id = t.user_type_id
LEFT JOIN sys.types t2 ON p.user_type_id = t2.user_type_id
WHERE o.type IN ('FN')
AND s.name = ?
AND o.name = ?;";
string actualSchema;
string actualName;
int objectId;
string fullTypeName;
string typeName;
bool isNullable;
int? maxLength;
int? precision;
int? scale;
using (var con = new OleDbConnection(m_ConnectionBuilder.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand(sql, con))
{
cmd.Parameters.AddWithValue("@Schema", tableFunctionName.Schema ?? DefaultSchema);
cmd.Parameters.AddWithValue("@Name", tableFunctionName.Name);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
throw new MissingObjectException($"Could not find scalar function {tableFunctionName}");
actualSchema = reader.GetString("SchemaName");
actualName = reader.GetString("Name");
objectId = reader.GetInt32("ObjectId");
typeName = reader.GetString("TypeName");
isNullable = reader.GetBoolean("is_nullable");
maxLength = reader.GetInt32OrNull("max_length");
precision = reader.GetInt32OrNull("precision");
scale = reader.GetInt32OrNull("scale");
AdjustTypeDetails(typeName, ref maxLength, ref precision, ref scale, out fullTypeName);
}
}
}
var objectName = new SqlServerObjectName(actualSchema, actualName);
var parameters = GetParameters(objectName.ToString(), objectId);
return new ScalarFunctionMetadata<SqlServerObjectName, OleDbType>(objectName, parameters, typeName, SqlTypeNameToDbType(typeName), isNullable, maxLength, precision, scale, fullTypeName);
}
internal StoredProcedureMetadata<SqlServerObjectName, OleDbType> GetStoredProcedureInternal(SqlServerObjectName procedureName)
{
const string StoredProcedureSql =
@"SELECT
s.name AS SchemaName,
sp.name AS Name,
sp.object_id AS ObjectId
FROM SYS.procedures sp
INNER JOIN sys.schemas s ON sp.schema_id = s.schema_id
WHERE s.name = ? AND sp.Name = ?";
string actualSchema;
string actualName;
int objectId;
using (var con = new OleDbConnection(m_ConnectionBuilder.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand(StoredProcedureSql, con))
{
cmd.Parameters.AddWithValue("@Schema", procedureName.Schema ?? DefaultSchema);
cmd.Parameters.AddWithValue("@Name", procedureName.Name);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
throw new MissingObjectException($"Could not find stored procedure {procedureName}");
actualSchema = reader.GetString("SchemaName");
actualName = reader.GetString("Name");
objectId = reader.GetInt32("ObjectId");
}
}
}
var objectName = new SqlServerObjectName(actualSchema, actualName);
var parameters = GetParameters(objectName.ToString(), objectId);
return new StoredProcedureMetadata<SqlServerObjectName, OleDbType>(objectName, parameters);
}
internal TableFunctionMetadata<SqlServerObjectName, OleDbType> GetTableFunctionInternal(SqlServerObjectName tableFunctionName)
{
const string TvfSql =
@"SELECT
s.name AS SchemaName,
o.name AS Name,
o.object_id AS ObjectId
FROM sys.objects o
INNER JOIN sys.schemas s ON o.schema_id = s.schema_id
WHERE o.type in ('TF', 'IF', 'FT') AND s.name = ? AND o.Name = ?";
/*
* TF = SQL table-valued-function
* IF = SQL inline table-valued function
* FT = Assembly (CLR) table-valued function
*/
string actualSchema;
string actualName;
int objectId;
using (var con = new OleDbConnection(m_ConnectionBuilder.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand(TvfSql, con))
{
cmd.Parameters.AddWithValue("@Schema", tableFunctionName.Schema ?? DefaultSchema);
cmd.Parameters.AddWithValue("@Name", tableFunctionName.Name);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
throw new MissingObjectException($"Could not find table valued function {tableFunctionName}");
actualSchema = reader.GetString("SchemaName");
actualName = reader.GetString("Name");
objectId = reader.GetInt32("ObjectId");
}
}
}
var objectName = new SqlServerObjectName(actualSchema, actualName);
var columns = GetColumns(tableFunctionName.ToString(), objectId);
var parameters = GetParameters(objectName.ToString(), objectId);
return new TableFunctionMetadata<SqlServerObjectName, OleDbType>(objectName, parameters, columns);
}
internal SqlServerTableOrViewMetadata<OleDbType> GetTableOrViewInternal(SqlServerObjectName tableName)
{
const string TableSql =
@"SELECT
s.name AS SchemaName,
t.name AS Name,
t.object_id AS ObjectId,
CONVERT(BIT, 1) AS IsTable,
(SELECT COUNT(*) FROM sys.triggers t2 WHERE t2.parent_id = t.object_id) AS Triggers
FROM SYS.tables t
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE s.name = ? AND t.Name = ?
UNION ALL
SELECT
s.name AS SchemaName,
t.name AS Name,
t.object_id AS ObjectId,
CONVERT(BIT, 0) AS IsTable,
(SELECT COUNT(*) FROM sys.triggers t2 WHERE t2.parent_id = t.object_id) AS Triggers
FROM SYS.views t
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
WHERE s.name = ? AND t.Name = ?";
string actualSchema;
string actualName;
int objectId;
bool isTable;
bool hasTriggers;
using (var con = new OleDbConnection(m_ConnectionBuilder!.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand(TableSql, con))
{
cmd.Parameters.AddWithValue("@Schema1", tableName.Schema ?? DefaultSchema);
cmd.Parameters.AddWithValue("@Name1", tableName.Name);
cmd.Parameters.AddWithValue("@Schema2", tableName.Schema ?? DefaultSchema);
cmd.Parameters.AddWithValue("@Name2", tableName.Name);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
throw new MissingObjectException($"Could not find table or view {tableName}");
actualSchema = reader.GetString("SchemaName");
actualName = reader.GetString("Name");
objectId = reader.GetInt32("ObjectId");
isTable = reader.GetBoolean("IsTable");
hasTriggers = reader.GetInt32("Triggers") > 0;
}
}
}
var columns = GetColumns(tableName.ToString(), objectId);
return new SqlServerTableOrViewMetadata<OleDbType>(this, new SqlServerObjectName(actualSchema, actualName), isTable, columns, hasTriggers);
}
internal UserDefinedTableTypeMetadata<SqlServerObjectName, OleDbType>
GetUserDefinedTableTypeInternal(SqlServerObjectName typeName)
{
const string sql =
@"SELECT s.name AS SchemaName,
t.name AS Name,
tt.type_table_object_id AS ObjectId
FROM sys.types t
INNER JOIN sys.schemas s ON t.schema_id = s.schema_id
LEFT JOIN sys.table_types tt ON tt.user_type_id = t.user_type_id
LEFT JOIN sys.types t2 ON t.system_type_id = t2.user_type_id
WHERE s.name = ? AND t.name = ? AND t.is_table_type = 1;";
string actualSchema;
string actualName;
int objectId;
using (var con = new OleDbConnection(m_ConnectionBuilder.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand(sql, con))
{
cmd.Parameters.AddWithValue("@Schema", typeName.Schema ?? DefaultSchema);
cmd.Parameters.AddWithValue("@Name", typeName.Name);
using (var reader = cmd.ExecuteReader())
{
if (!reader.Read())
throw new MissingObjectException($"Could not find user defined type {typeName}");
actualSchema = reader.GetString("SchemaName");
actualName = reader.GetString("Name");
objectId = reader.GetInt32("ObjectId");
}
}
}
var columns = GetColumns(typeName.ToString(), objectId);
return new UserDefinedTableTypeMetadata<SqlServerObjectName, OleDbType>(new SqlServerObjectName(actualSchema, actualName), columns);
}
/// <summary>
/// Determines the database column type from the column type name.
/// </summary>
/// <param name="typeName">Name of the database column type.</param>
/// <param name="isUnsigned">NOT USED</param>
/// <returns></returns>
/// <remarks>This does not honor registered types. This is only used for the database's hard-coded list of native types.</remarks>
[SuppressMessage("Microsoft.Maintainability", "CA1502:AvoidExcessiveComplexity")]
protected override OleDbType? SqlTypeNameToDbType(string typeName, bool? isUnsigned = null)
{
switch (typeName)
{
case "bigint": return OleDbType.BigInt;
case "binary": return OleDbType.Binary;
case "bit": return OleDbType.Boolean;
case "char": return OleDbType.Char;
case "date": return OleDbType.DBDate;
case "datetime": return OleDbType.DBTimeStamp;
case "datetime2": return OleDbType.DBTimeStamp;
//case "datetimeoffset": return OleDbType;
case "decimal": return OleDbType.Decimal;
case "float": return OleDbType.Single;
//case "geography": m_SqlDbType = OleDbType.;
//case "geometry": m_SqlDbType = OleDbType;
//case "hierarchyid": m_SqlDbType = OleDbType.;
//case "image": return OleDbType.Image;
case "int": return OleDbType.Integer;
case "money": return OleDbType.Currency;
case "nchar": return OleDbType.WChar;
case "ntext": return OleDbType.LongVarWChar;
case "numeric": return OleDbType.Numeric;
case "nvarchar": return OleDbType.VarWChar;
case "real": return OleDbType.Single;
case "smalldatetime": return OleDbType.DBTimeStamp;
case "smallint": return OleDbType.SmallInt;
case "smallmoney": return OleDbType.Currency;
//case "sql_variant": m_SqlDbType = OleDbType;
//case "sysname": m_SqlDbType = OleDbType;
case "text": return OleDbType.LongVarWChar;
case "time": return OleDbType.DBTime;
case "timestamp": return OleDbType.DBTimeStamp;
case "tinyint": return OleDbType.TinyInt;
case "uniqueidentifier": return OleDbType.Guid;
case "varbinary": return OleDbType.VarBinary;
case "varchar": return OleDbType.VarChar;
//case "xml": return OleDbType;
}
return null;
}
ColumnMetadataCollection<OleDbType> GetColumns(string ownerName, int objectId)
{
const string ColumnSql =
@"WITH PKS
AS ( SELECT c.name ,
1 AS is_primary_key
FROM sys.indexes i
INNER JOIN sys.index_columns ic ON i.index_id = ic.index_id
AND ic.object_id = ?
INNER JOIN sys.columns c ON ic.column_id = c.column_id
AND c.object_id = ?
WHERE i.is_primary_key = 1
AND ic.is_included_column = 0
AND i.object_id = ?
)
SELECT c.name AS ColumnName ,
c.is_computed ,
c.is_identity ,
c.column_id ,
Convert(bit, ISNULL(PKS.is_primary_key, 0)) AS is_primary_key,
COALESCE(t.name, t2.name) AS TypeName,
c.is_nullable,
CONVERT(INT, COALESCE(c.max_length, t.max_length, t2.max_length)) AS max_length,
CONVERT(INT, COALESCE(c.precision, t.precision, t2.precision)) AS precision,
CONVERT(INT, COALESCE(c.scale, t.scale, t2.scale)) AS scale
FROM sys.columns c
LEFT JOIN PKS ON c.name = PKS.name
LEFT JOIN sys.types t on c.system_type_id = t.user_type_id
LEFT JOIN sys.types t2 ON c.user_type_id = t2.user_type_id
WHERE object_id = ?;";
var columns = new List<ColumnMetadata<OleDbType>>();
using (var con = new OleDbConnection(m_ConnectionBuilder.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand(ColumnSql, con))
{
cmd.Parameters.AddWithValue("@ObjectId1", objectId);
cmd.Parameters.AddWithValue("@ObjectId2", objectId);
cmd.Parameters.AddWithValue("@ObjectId3", objectId);
cmd.Parameters.AddWithValue("@ObjectId4", objectId);
using (var reader = cmd.ExecuteReader(/*CommandBehavior.SequentialAccess*/))
{
while (reader.Read())
{
var name = reader.GetString("ColumnName");
var computed = reader.GetBoolean("is_computed");
var primary = reader.GetBoolean("is_primary_key");
var isIdentity = reader.GetBoolean("is_identity");
var typeName = reader.GetString("TypeName");
var isNullable = reader.GetBoolean("is_nullable");
int? maxLength = reader.GetInt32OrNull("max_length");
int? precision = reader.GetInt32OrNull("precision");
int? scale = reader.GetInt32OrNull("scale");
string fullTypeName;
AdjustTypeDetails(typeName, ref maxLength, ref precision, ref scale, out fullTypeName);
columns.Add(new ColumnMetadata<OleDbType>(name, computed, primary, isIdentity, typeName, SqlTypeNameToDbType(typeName), "[" + name + "]", isNullable, maxLength, precision, scale, fullTypeName, ToClrType(typeName, isNullable, maxLength)));
}
}
}
}
return new ColumnMetadataCollection<OleDbType>(ownerName, columns);
}
ParameterMetadataCollection<OleDbType> GetParameters(string procedureName, int objectId)
{
try
{
const string ParameterSql =
@"SELECT p.name AS ParameterName ,
COALESCE(t.name, t2.name) AS TypeName,
COALESCE(t.is_nullable, t2.is_nullable) as is_nullable,
CONVERT(INT, t.max_length) AS max_length,
CONVERT(INT, t.precision) AS precision,
CONVERT(INT, t.scale) AS scale
FROM sys.parameters p
LEFT JOIN sys.types t ON p.system_type_id = t.user_type_id
LEFT JOIN sys.types t2 ON p.user_type_id = t2.user_type_id
WHERE p.object_id = ? AND p.parameter_id <> 0
ORDER BY p.parameter_id;";
//we exclude parameter_id 0 because it is the return type of scalar functions.
var parameters = new List<ParameterMetadata<OleDbType>>();
using (var con = new OleDbConnection(m_ConnectionBuilder.ConnectionString))
{
con.Open();
using (var cmd = new OleDbCommand(ParameterSql, con))
{
cmd.Parameters.AddWithValue("@ObjectId", objectId);
using (var reader = cmd.ExecuteReader())
{
while (reader.Read())
{
var name = reader.GetString("ParameterName");
var typeName = reader.GetString("TypeName");
bool isNullable = true;
int? maxLength = reader.GetInt32OrNull("max_length");
int? precision = reader.GetInt32OrNull("precision");
int? scale = reader.GetInt32OrNull("scale");
string fullTypeName;
AdjustTypeDetails(typeName, ref maxLength, ref precision, ref scale, out fullTypeName);
parameters.Add(new ParameterMetadata<OleDbType>(name, name, typeName, SqlTypeNameToDbType(typeName), isNullable, maxLength, precision, scale, fullTypeName));
}
}
}
}
return new ParameterMetadataCollection<OleDbType>(procedureName, parameters);
}
catch (Exception ex)
{
throw new MetadataException($"Error getting parameters for {procedureName}", ex);
}
}
}
}
| 43.109244 | 266 | 0.529857 | [
"MIT"
] | hellfirehd/Chain | Tortuga.Chain/Tortuga.Chain.SqlServer.OleDb/SqlServer/OleDbSqlServerMetadataCache.cs | 30,780 | C# |
using ARMeilleure.Decoders;
using ARMeilleure.IntermediateRepresentation;
using ARMeilleure.State;
using ARMeilleure.Translation;
using System;
using System.Diagnostics;
using static ARMeilleure.Instructions.InstEmitHelper;
using static ARMeilleure.Instructions.InstEmitSimdHelper;
using static ARMeilleure.IntermediateRepresentation.OperandHelper;
namespace ARMeilleure.Instructions
{
using Func1I = Func<Operand, Operand>;
static partial class InstEmit
{
public static void Fcvt_S(ArmEmitterContext context)
{
OpCodeSimd op = (OpCodeSimd)context.CurrOp;
if (op.Size == 0 && op.Opc == 1) // Single -> Double.
{
if (Optimizations.UseSse2)
{
Operand n = GetVec(op.Rn);
Operand res = context.AddIntrinsic(Intrinsic.X86Cvtss2sd, context.VectorZero(), n);
context.Copy(GetVec(op.Rd), res);
}
else
{
Operand ne = context.VectorExtract(OperandType.FP32, GetVec(op.Rn), 0);
Operand res = context.ConvertToFP(OperandType.FP64, ne);
context.Copy(GetVec(op.Rd), context.VectorInsert(context.VectorZero(), res, 0));
}
}
else if (op.Size == 1 && op.Opc == 0) // Double -> Single.
{
if (Optimizations.UseSse2)
{
Operand n = GetVec(op.Rn);
Operand res = context.AddIntrinsic(Intrinsic.X86Cvtsd2ss, context.VectorZero(), n);
context.Copy(GetVec(op.Rd), res);
}
else
{
Operand ne = context.VectorExtract(OperandType.FP64, GetVec(op.Rn), 0);
Operand res = context.ConvertToFP(OperandType.FP32, ne);
context.Copy(GetVec(op.Rd), context.VectorInsert(context.VectorZero(), res, 0));
}
}
else if (op.Size == 0 && op.Opc == 3) // Single -> Half.
{
Operand ne = context.VectorExtract(OperandType.FP32, GetVec(op.Rn), 0);
Delegate dlg = new _U16_F32(SoftFloat32_16.FPConvert);
Operand res = context.Call(dlg, ne);
res = context.ZeroExtend16(OperandType.I64, res);
context.Copy(GetVec(op.Rd), EmitVectorInsert(context, context.VectorZero(), res, 0, 1));
}
else if (op.Size == 3 && op.Opc == 0) // Half -> Single.
{
Operand ne = EmitVectorExtractZx(context, op.Rn, 0, 1);
Delegate dlg = new _F32_U16(SoftFloat16_32.FPConvert);
Operand res = context.Call(dlg, ne);
context.Copy(GetVec(op.Rd), context.VectorInsert(context.VectorZero(), res, 0));
}
else if (op.Size == 1 && op.Opc == 3) // Double -> Half.
{
throw new NotImplementedException("Double-precision to half-precision.");
}
else if (op.Size == 3 && op.Opc == 1) // Double -> Half.
{
throw new NotImplementedException("Half-precision to double-precision.");
}
else // Invalid encoding.
{
Debug.Assert(false, $"type == {op.Size} && opc == {op.Opc}");
}
}
public static void Fcvtas_Gp(ArmEmitterContext context)
{
EmitFcvt_s_Gp(context, (op1) => EmitRoundMathCall(context, MidpointRounding.AwayFromZero, op1));
}
public static void Fcvtas_S(ArmEmitterContext context)
{
EmitFcvt(context, (op1) => EmitRoundMathCall(context, MidpointRounding.AwayFromZero, op1), signed: true, scalar: true);
}
public static void Fcvtas_V(ArmEmitterContext context)
{
EmitFcvt(context, (op1) => EmitRoundMathCall(context, MidpointRounding.AwayFromZero, op1), signed: true, scalar: false);
}
public static void Fcvtau_Gp(ArmEmitterContext context)
{
EmitFcvt_u_Gp(context, (op1) => EmitRoundMathCall(context, MidpointRounding.AwayFromZero, op1));
}
public static void Fcvtau_S(ArmEmitterContext context)
{
EmitFcvt(context, (op1) => EmitRoundMathCall(context, MidpointRounding.AwayFromZero, op1), signed: false, scalar: true);
}
public static void Fcvtau_V(ArmEmitterContext context)
{
EmitFcvt(context, (op1) => EmitRoundMathCall(context, MidpointRounding.AwayFromZero, op1), signed: false, scalar: false);
}
public static void Fcvtl_V(ArmEmitterContext context)
{
OpCodeSimd op = (OpCodeSimd)context.CurrOp;
int sizeF = op.Size & 1;
if (Optimizations.UseSse2 && sizeF == 1)
{
Operand n = GetVec(op.Rn);
Operand res;
if (op.RegisterSize == RegisterSize.Simd128)
{
res = context.AddIntrinsic(Intrinsic.X86Movhlps, n, n);
}
else
{
res = n;
}
res = context.AddIntrinsic(Intrinsic.X86Cvtps2pd, res);
context.Copy(GetVec(op.Rd), res);
}
else
{
Operand res = context.VectorZero();
int elems = 4 >> sizeF;
int part = op.RegisterSize == RegisterSize.Simd128 ? elems : 0;
for (int index = 0; index < elems; index++)
{
if (sizeF == 0)
{
Operand ne = EmitVectorExtractZx(context, op.Rn, part + index, 1);
Delegate dlg = new _F32_U16(SoftFloat16_32.FPConvert);
Operand e = context.Call(dlg, ne);
res = context.VectorInsert(res, e, index);
}
else /* if (sizeF == 1) */
{
Operand ne = context.VectorExtract(OperandType.FP32, GetVec(op.Rn), part + index);
Operand e = context.ConvertToFP(OperandType.FP64, ne);
res = context.VectorInsert(res, e, index);
}
}
context.Copy(GetVec(op.Rd), res);
}
}
public static void Fcvtms_Gp(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvts_Gp(context, FPRoundingMode.TowardsMinusInfinity, isFixed: false);
}
else
{
EmitFcvt_s_Gp(context, (op1) => EmitUnaryMathCall(context, MathF.Floor, Math.Floor, op1));
}
}
public static void Fcvtmu_Gp(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvtu_Gp(context, FPRoundingMode.TowardsMinusInfinity, isFixed: false);
}
else
{
EmitFcvt_u_Gp(context, (op1) => EmitUnaryMathCall(context, MathF.Floor, Math.Floor, op1));
}
}
public static void Fcvtn_V(ArmEmitterContext context)
{
OpCodeSimd op = (OpCodeSimd)context.CurrOp;
int sizeF = op.Size & 1;
if (Optimizations.UseSse2 && sizeF == 1)
{
Operand d = GetVec(op.Rd);
Operand res = context.VectorZeroUpper64(d);
Operand nInt = context.AddIntrinsic(Intrinsic.X86Cvtpd2ps, GetVec(op.Rn));
nInt = context.AddIntrinsic(Intrinsic.X86Movlhps, nInt, nInt);
Intrinsic movInst = op.RegisterSize == RegisterSize.Simd128
? Intrinsic.X86Movlhps
: Intrinsic.X86Movhlps;
res = context.AddIntrinsic(movInst, res, nInt);
context.Copy(d, res);
}
else
{
OperandType type = sizeF == 0 ? OperandType.FP32 : OperandType.FP64;
int elems = 4 >> sizeF;
int part = op.RegisterSize == RegisterSize.Simd128 ? elems : 0;
Operand d = GetVec(op.Rd);
Operand res = part == 0 ? context.VectorZero() : context.Copy(d);
for (int index = 0; index < elems; index++)
{
Operand ne = context.VectorExtract(type, GetVec(op.Rn), 0);
if (sizeF == 0)
{
Delegate dlg = new _U16_F32(SoftFloat32_16.FPConvert);
Operand e = context.Call(dlg, ne);
e = context.ZeroExtend16(OperandType.I64, e);
res = EmitVectorInsert(context, res, e, part + index, 1);
}
else /* if (sizeF == 1) */
{
Operand e = context.ConvertToFP(OperandType.FP32, ne);
res = context.VectorInsert(res, e, part + index);
}
}
context.Copy(d, res);
}
}
public static void Fcvtns_S(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvts(context, FPRoundingMode.ToNearest, scalar: true);
}
else
{
EmitFcvt(context, (op1) => EmitRoundMathCall(context, MidpointRounding.ToEven, op1), signed: true, scalar: true);
}
}
public static void Fcvtns_V(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvts(context, FPRoundingMode.ToNearest, scalar: false);
}
else
{
EmitFcvt(context, (op1) => EmitRoundMathCall(context, MidpointRounding.ToEven, op1), signed: true, scalar: false);
}
}
public static void Fcvtnu_S(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvtu(context, FPRoundingMode.ToNearest, scalar: true);
}
else
{
EmitFcvt(context, (op1) => EmitRoundMathCall(context, MidpointRounding.ToEven, op1), signed: false, scalar: true);
}
}
public static void Fcvtnu_V(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvtu(context, FPRoundingMode.ToNearest, scalar: false);
}
else
{
EmitFcvt(context, (op1) => EmitRoundMathCall(context, MidpointRounding.ToEven, op1), signed: false, scalar: false);
}
}
public static void Fcvtps_Gp(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvts_Gp(context, FPRoundingMode.TowardsPlusInfinity, isFixed: false);
}
else
{
EmitFcvt_s_Gp(context, (op1) => EmitUnaryMathCall(context, MathF.Ceiling, Math.Ceiling, op1));
}
}
public static void Fcvtpu_Gp(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvtu_Gp(context, FPRoundingMode.TowardsPlusInfinity, isFixed: false);
}
else
{
EmitFcvt_u_Gp(context, (op1) => EmitUnaryMathCall(context, MathF.Ceiling, Math.Ceiling, op1));
}
}
public static void Fcvtzs_Gp(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvts_Gp(context, FPRoundingMode.TowardsZero, isFixed: false);
}
else
{
EmitFcvt_s_Gp(context, (op1) => op1);
}
}
public static void Fcvtzs_Gp_Fixed(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvts_Gp(context, FPRoundingMode.TowardsZero, isFixed: true);
}
else
{
EmitFcvtzs_Gp_Fixed(context);
}
}
public static void Fcvtzs_S(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvts(context, FPRoundingMode.TowardsZero, scalar: true);
}
else
{
EmitFcvtz(context, signed: true, scalar: true);
}
}
public static void Fcvtzs_V(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvts(context, FPRoundingMode.TowardsZero, scalar: false);
}
else
{
EmitFcvtz(context, signed: true, scalar: false);
}
}
public static void Fcvtzs_V_Fixed(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvts(context, FPRoundingMode.TowardsZero, scalar: false);
}
else
{
EmitFcvtz(context, signed: true, scalar: false);
}
}
public static void Fcvtzu_Gp(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvtu_Gp(context, FPRoundingMode.TowardsZero, isFixed: false);
}
else
{
EmitFcvt_u_Gp(context, (op1) => op1);
}
}
public static void Fcvtzu_Gp_Fixed(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvtu_Gp(context, FPRoundingMode.TowardsZero, isFixed: true);
}
else
{
EmitFcvtzu_Gp_Fixed(context);
}
}
public static void Fcvtzu_S(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvtu(context, FPRoundingMode.TowardsZero, scalar: true);
}
else
{
EmitFcvtz(context, signed: false, scalar: true);
}
}
public static void Fcvtzu_V(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvtu(context, FPRoundingMode.TowardsZero, scalar: false);
}
else
{
EmitFcvtz(context, signed: false, scalar: false);
}
}
public static void Fcvtzu_V_Fixed(ArmEmitterContext context)
{
if (Optimizations.UseSse41)
{
EmitSse41Fcvtu(context, FPRoundingMode.TowardsZero, scalar: false);
}
else
{
EmitFcvtz(context, signed: false, scalar: false);
}
}
public static void Scvtf_Gp(ArmEmitterContext context)
{
OpCodeSimdCvt op = (OpCodeSimdCvt)context.CurrOp;
Operand res = GetIntOrZR(context, op.Rn);
if (op.RegisterSize == RegisterSize.Int32)
{
res = context.SignExtend32(OperandType.I64, res);
}
res = EmitFPConvert(context, res, op.Size, signed: true);
context.Copy(GetVec(op.Rd), context.VectorInsert(context.VectorZero(), res, 0));
}
public static void Scvtf_Gp_Fixed(ArmEmitterContext context)
{
OpCodeSimdCvt op = (OpCodeSimdCvt)context.CurrOp;
Operand res = GetIntOrZR(context, op.Rn);
if (op.RegisterSize == RegisterSize.Int32)
{
res = context.SignExtend32(OperandType.I64, res);
}
res = EmitFPConvert(context, res, op.Size, signed: true);
res = EmitI2fFBitsMul(context, res, op.FBits);
context.Copy(GetVec(op.Rd), context.VectorInsert(context.VectorZero(), res, 0));
}
public static void Scvtf_S(ArmEmitterContext context)
{
if (Optimizations.UseSse2)
{
EmitSse2Scvtf(context, scalar: true);
}
else
{
OpCodeSimd op = (OpCodeSimd)context.CurrOp;
int sizeF = op.Size & 1;
Operand res = EmitVectorLongExtract(context, op.Rn, 0, sizeF + 2);
res = EmitFPConvert(context, res, op.Size, signed: true);
context.Copy(GetVec(op.Rd), context.VectorInsert(context.VectorZero(), res, 0));
}
}
public static void Scvtf_V(ArmEmitterContext context)
{
if (Optimizations.UseSse2)
{
EmitSse2Scvtf(context, scalar: false);
}
else
{
EmitVectorCvtf(context, signed: true);
}
}
public static void Scvtf_V_Fixed(ArmEmitterContext context)
{
if (Optimizations.UseSse2)
{
EmitSse2Scvtf(context, scalar: false);
}
else
{
EmitVectorCvtf(context, signed: true);
}
}
public static void Ucvtf_Gp(ArmEmitterContext context)
{
OpCodeSimdCvt op = (OpCodeSimdCvt)context.CurrOp;
Operand res = GetIntOrZR(context, op.Rn);
res = EmitFPConvert(context, res, op.Size, signed: false);
context.Copy(GetVec(op.Rd), context.VectorInsert(context.VectorZero(), res, 0));
}
public static void Ucvtf_Gp_Fixed(ArmEmitterContext context)
{
OpCodeSimdCvt op = (OpCodeSimdCvt)context.CurrOp;
Operand res = GetIntOrZR(context, op.Rn);
res = EmitFPConvert(context, res, op.Size, signed: false);
res = EmitI2fFBitsMul(context, res, op.FBits);
context.Copy(GetVec(op.Rd), context.VectorInsert(context.VectorZero(), res, 0));
}
public static void Ucvtf_S(ArmEmitterContext context)
{
if (Optimizations.UseSse2)
{
EmitSse2Ucvtf(context, scalar: true);
}
else
{
OpCodeSimd op = (OpCodeSimd)context.CurrOp;
int sizeF = op.Size & 1;
Operand ne = EmitVectorLongExtract(context, op.Rn, 0, sizeF + 2);
Operand res = EmitFPConvert(context, ne, sizeF, signed: false);
context.Copy(GetVec(op.Rd), context.VectorInsert(context.VectorZero(), res, 0));
}
}
public static void Ucvtf_V(ArmEmitterContext context)
{
if (Optimizations.UseSse2)
{
EmitSse2Ucvtf(context, scalar: false);
}
else
{
EmitVectorCvtf(context, signed: false);
}
}
public static void Ucvtf_V_Fixed(ArmEmitterContext context)
{
if (Optimizations.UseSse2)
{
EmitSse2Ucvtf(context, scalar: false);
}
else
{
EmitVectorCvtf(context, signed: false);
}
}
private static void EmitFcvt(ArmEmitterContext context, Func1I emit, bool signed, bool scalar)
{
OpCodeSimd op = (OpCodeSimd)context.CurrOp;
Operand res = context.VectorZero();
Operand n = GetVec(op.Rn);
int sizeF = op.Size & 1;
int sizeI = sizeF + 2;
OperandType type = sizeF == 0 ? OperandType.FP32 : OperandType.FP64;
int elems = !scalar ? op.GetBytesCount() >> sizeI : 1;
for (int index = 0; index < elems; index++)
{
Operand ne = context.VectorExtract(type, n, index);
Operand e = emit(ne);
if (sizeF == 0)
{
Delegate dlg = signed
? (Delegate)new _S32_F32(SoftFallback.SatF32ToS32)
: (Delegate)new _U32_F32(SoftFallback.SatF32ToU32);
e = context.Call(dlg, e);
e = context.ZeroExtend32(OperandType.I64, e);
}
else /* if (sizeF == 1) */
{
Delegate dlg = signed
? (Delegate)new _S64_F64(SoftFallback.SatF64ToS64)
: (Delegate)new _U64_F64(SoftFallback.SatF64ToU64);
e = context.Call(dlg, e);
}
res = EmitVectorInsert(context, res, e, index, sizeI);
}
context.Copy(GetVec(op.Rd), res);
}
private static void EmitFcvtz(ArmEmitterContext context, bool signed, bool scalar)
{
OpCodeSimd op = (OpCodeSimd)context.CurrOp;
Operand res = context.VectorZero();
Operand n = GetVec(op.Rn);
int sizeF = op.Size & 1;
int sizeI = sizeF + 2;
OperandType type = sizeF == 0 ? OperandType.FP32 : OperandType.FP64;
int fBits = GetFBits(context);
int elems = !scalar ? op.GetBytesCount() >> sizeI : 1;
for (int index = 0; index < elems; index++)
{
Operand ne = context.VectorExtract(type, n, index);
Operand e = EmitF2iFBitsMul(context, ne, fBits);
if (sizeF == 0)
{
Delegate dlg = signed
? (Delegate)new _S32_F32(SoftFallback.SatF32ToS32)
: (Delegate)new _U32_F32(SoftFallback.SatF32ToU32);
e = context.Call(dlg, e);
e = context.ZeroExtend32(OperandType.I64, e);
}
else /* if (sizeF == 1) */
{
Delegate dlg = signed
? (Delegate)new _S64_F64(SoftFallback.SatF64ToS64)
: (Delegate)new _U64_F64(SoftFallback.SatF64ToU64);
e = context.Call(dlg, e);
}
res = EmitVectorInsert(context, res, e, index, sizeI);
}
context.Copy(GetVec(op.Rd), res);
}
private static void EmitFcvt_s_Gp(ArmEmitterContext context, Func1I emit)
{
EmitFcvt___Gp(context, emit, signed: true);
}
private static void EmitFcvt_u_Gp(ArmEmitterContext context, Func1I emit)
{
EmitFcvt___Gp(context, emit, signed: false);
}
private static void EmitFcvt___Gp(ArmEmitterContext context, Func1I emit, bool signed)
{
OpCodeSimdCvt op = (OpCodeSimdCvt)context.CurrOp;
OperandType type = op.Size == 0 ? OperandType.FP32 : OperandType.FP64;
Operand ne = context.VectorExtract(type, GetVec(op.Rn), 0);
Operand res = signed
? EmitScalarFcvts(context, emit(ne), 0)
: EmitScalarFcvtu(context, emit(ne), 0);
SetIntOrZR(context, op.Rd, res);
}
private static void EmitFcvtzs_Gp_Fixed(ArmEmitterContext context)
{
EmitFcvtz__Gp_Fixed(context, signed: true);
}
private static void EmitFcvtzu_Gp_Fixed(ArmEmitterContext context)
{
EmitFcvtz__Gp_Fixed(context, signed: false);
}
private static void EmitFcvtz__Gp_Fixed(ArmEmitterContext context, bool signed)
{
OpCodeSimdCvt op = (OpCodeSimdCvt)context.CurrOp;
OperandType type = op.Size == 0 ? OperandType.FP32 : OperandType.FP64;
Operand ne = context.VectorExtract(type, GetVec(op.Rn), 0);
Operand res = signed
? EmitScalarFcvts(context, ne, op.FBits)
: EmitScalarFcvtu(context, ne, op.FBits);
SetIntOrZR(context, op.Rd, res);
}
private static void EmitVectorCvtf(ArmEmitterContext context, bool signed)
{
OpCodeSimd op = (OpCodeSimd)context.CurrOp;
Operand res = context.VectorZero();
int sizeF = op.Size & 1;
int sizeI = sizeF + 2;
int fBits = GetFBits(context);
int elems = op.GetBytesCount() >> sizeI;
for (int index = 0; index < elems; index++)
{
Operand ne = EmitVectorLongExtract(context, op.Rn, index, sizeI);
Operand e = EmitFPConvert(context, ne, sizeF, signed);
e = EmitI2fFBitsMul(context, e, fBits);
res = context.VectorInsert(res, e, index);
}
context.Copy(GetVec(op.Rd), res);
}
private static int GetFBits(ArmEmitterContext context)
{
if (context.CurrOp is OpCodeSimdShImm op)
{
return GetImmShr(op);
}
return 0;
}
private static Operand EmitFPConvert(ArmEmitterContext context, Operand value, int size, bool signed)
{
Debug.Assert(value.Type == OperandType.I32 || value.Type == OperandType.I64);
Debug.Assert((uint)size < 2);
OperandType type = size == 0 ? OperandType.FP32 : OperandType.FP64;
if (signed)
{
return context.ConvertToFP(type, value);
}
else
{
return context.ConvertToFPUI(type, value);
}
}
private static Operand EmitScalarFcvts(ArmEmitterContext context, Operand value, int fBits)
{
Debug.Assert(value.Type == OperandType.FP32 || value.Type == OperandType.FP64);
value = EmitF2iFBitsMul(context, value, fBits);
if (context.CurrOp.RegisterSize == RegisterSize.Int32)
{
Delegate dlg = value.Type == OperandType.FP32
? (Delegate)new _S32_F32(SoftFallback.SatF32ToS32)
: (Delegate)new _S32_F64(SoftFallback.SatF64ToS32);
return context.Call(dlg, value);
}
else
{
Delegate dlg = value.Type == OperandType.FP32
? (Delegate)new _S64_F32(SoftFallback.SatF32ToS64)
: (Delegate)new _S64_F64(SoftFallback.SatF64ToS64);
return context.Call(dlg, value);
}
}
private static Operand EmitScalarFcvtu(ArmEmitterContext context, Operand value, int fBits)
{
Debug.Assert(value.Type == OperandType.FP32 || value.Type == OperandType.FP64);
value = EmitF2iFBitsMul(context, value, fBits);
if (context.CurrOp.RegisterSize == RegisterSize.Int32)
{
Delegate dlg = value.Type == OperandType.FP32
? (Delegate)new _U32_F32(SoftFallback.SatF32ToU32)
: (Delegate)new _U32_F64(SoftFallback.SatF64ToU32);
return context.Call(dlg, value);
}
else
{
Delegate dlg = value.Type == OperandType.FP32
? (Delegate)new _U64_F32(SoftFallback.SatF32ToU64)
: (Delegate)new _U64_F64(SoftFallback.SatF64ToU64);
return context.Call(dlg, value);
}
}
private static Operand EmitF2iFBitsMul(ArmEmitterContext context, Operand value, int fBits)
{
Debug.Assert(value.Type == OperandType.FP32 || value.Type == OperandType.FP64);
if (fBits == 0)
{
return value;
}
if (value.Type == OperandType.FP32)
{
return context.Multiply(value, ConstF(MathF.Pow(2f, fBits)));
}
else /* if (value.Type == OperandType.FP64) */
{
return context.Multiply(value, ConstF(Math.Pow(2d, fBits)));
}
}
private static Operand EmitI2fFBitsMul(ArmEmitterContext context, Operand value, int fBits)
{
Debug.Assert(value.Type == OperandType.FP32 || value.Type == OperandType.FP64);
if (fBits == 0)
{
return value;
}
if (value.Type == OperandType.FP32)
{
return context.Multiply(value, ConstF(1f / MathF.Pow(2f, fBits)));
}
else /* if (value.Type == OperandType.FP64) */
{
return context.Multiply(value, ConstF(1d / Math.Pow(2d, fBits)));
}
}
public static Operand EmitSse2CvtDoubleToInt64OpF(ArmEmitterContext context, Operand opF, bool scalar)
{
Debug.Assert(opF.Type == OperandType.V128);
Operand longL = context.AddIntrinsicLong (Intrinsic.X86Cvtsd2si, opF); // opFL
Operand res = context.VectorCreateScalar(longL);
if (!scalar)
{
Operand opFH = context.AddIntrinsic (Intrinsic.X86Movhlps, res, opF); // res doesn't matter.
Operand longH = context.AddIntrinsicLong (Intrinsic.X86Cvtsd2si, opFH);
Operand resH = context.VectorCreateScalar(longH);
res = context.AddIntrinsic (Intrinsic.X86Movlhps, res, resH);
}
return res;
}
private static Operand EmitSse2CvtInt64ToDoubleOp(ArmEmitterContext context, Operand op, bool scalar)
{
Debug.Assert(op.Type == OperandType.V128);
Operand longL = context.AddIntrinsicLong(Intrinsic.X86Cvtsi2si, op); // opL
Operand res = context.AddIntrinsic (Intrinsic.X86Cvtsi2sd, context.VectorZero(), longL);
if (!scalar)
{
Operand opH = context.AddIntrinsic (Intrinsic.X86Movhlps, res, op); // res doesn't matter.
Operand longH = context.AddIntrinsicLong(Intrinsic.X86Cvtsi2si, opH);
Operand resH = context.AddIntrinsic (Intrinsic.X86Cvtsi2sd, res, longH); // res doesn't matter.
res = context.AddIntrinsic (Intrinsic.X86Movlhps, res, resH);
}
return res;
}
private static void EmitSse2Scvtf(ArmEmitterContext context, bool scalar)
{
OpCodeSimd op = (OpCodeSimd)context.CurrOp;
Operand n = GetVec(op.Rn);
// sizeF == ((OpCodeSimdShImm)op).Size - 2
int sizeF = op.Size & 1;
if (sizeF == 0)
{
Operand res = context.AddIntrinsic(Intrinsic.X86Cvtdq2ps, n);
if (op is OpCodeSimdShImm fixedOp)
{
int fBits = GetImmShr(fixedOp);
// BitConverter.Int32BitsToSingle(fpScaled) == 1f / MathF.Pow(2f, fBits)
int fpScaled = 0x3F800000 - fBits * 0x800000;
Operand fpScaledMask = scalar
? X86GetScalar (context, fpScaled)
: X86GetAllElements(context, fpScaled);
res = context.AddIntrinsic(Intrinsic.X86Mulps, res, fpScaledMask);
}
if (scalar)
{
res = context.VectorZeroUpper96(res);
}
else if (op.RegisterSize == RegisterSize.Simd64)
{
res = context.VectorZeroUpper64(res);
}
context.Copy(GetVec(op.Rd), res);
}
else /* if (sizeF == 1) */
{
Operand res = EmitSse2CvtInt64ToDoubleOp(context, n, scalar);
if (op is OpCodeSimdShImm fixedOp)
{
int fBits = GetImmShr(fixedOp);
// BitConverter.Int64BitsToDouble(fpScaled) == 1d / Math.Pow(2d, fBits)
long fpScaled = 0x3FF0000000000000L - fBits * 0x10000000000000L;
Operand fpScaledMask = scalar
? X86GetScalar (context, fpScaled)
: X86GetAllElements(context, fpScaled);
res = context.AddIntrinsic(Intrinsic.X86Mulpd, res, fpScaledMask);
}
if (scalar)
{
res = context.VectorZeroUpper64(res);
}
context.Copy(GetVec(op.Rd), res);
}
}
private static void EmitSse2Ucvtf(ArmEmitterContext context, bool scalar)
{
OpCodeSimd op = (OpCodeSimd)context.CurrOp;
Operand n = GetVec(op.Rn);
// sizeF == ((OpCodeSimdShImm)op).Size - 2
int sizeF = op.Size & 1;
if (sizeF == 0)
{
Operand mask = scalar // 65536.000f (1 << 16)
? X86GetScalar (context, 0x47800000)
: X86GetAllElements(context, 0x47800000);
Operand res = context.AddIntrinsic(Intrinsic.X86Psrld, n, Const(16));
res = context.AddIntrinsic(Intrinsic.X86Cvtdq2ps, res);
res = context.AddIntrinsic(Intrinsic.X86Mulps, res, mask);
Operand res2 = context.AddIntrinsic(Intrinsic.X86Pslld, n, Const(16));
res2 = context.AddIntrinsic(Intrinsic.X86Psrld, res2, Const(16));
res2 = context.AddIntrinsic(Intrinsic.X86Cvtdq2ps, res2);
res = context.AddIntrinsic(Intrinsic.X86Addps, res, res2);
if (op is OpCodeSimdShImm fixedOp)
{
int fBits = GetImmShr(fixedOp);
// BitConverter.Int32BitsToSingle(fpScaled) == 1f / MathF.Pow(2f, fBits)
int fpScaled = 0x3F800000 - fBits * 0x800000;
Operand fpScaledMask = scalar
? X86GetScalar (context, fpScaled)
: X86GetAllElements(context, fpScaled);
res = context.AddIntrinsic(Intrinsic.X86Mulps, res, fpScaledMask);
}
if (scalar)
{
res = context.VectorZeroUpper96(res);
}
else if (op.RegisterSize == RegisterSize.Simd64)
{
res = context.VectorZeroUpper64(res);
}
context.Copy(GetVec(op.Rd), res);
}
else /* if (sizeF == 1) */
{
Operand mask = scalar // 4294967296.0000000d (1L << 32)
? X86GetScalar (context, 0x41F0000000000000L)
: X86GetAllElements(context, 0x41F0000000000000L);
Operand res = context.AddIntrinsic (Intrinsic.X86Psrlq, n, Const(32));
res = EmitSse2CvtInt64ToDoubleOp(context, res, scalar);
res = context.AddIntrinsic (Intrinsic.X86Mulpd, res, mask);
Operand res2 = context.AddIntrinsic (Intrinsic.X86Psllq, n, Const(32));
res2 = context.AddIntrinsic (Intrinsic.X86Psrlq, res2, Const(32));
res2 = EmitSse2CvtInt64ToDoubleOp(context, res2, scalar);
res = context.AddIntrinsic(Intrinsic.X86Addpd, res, res2);
if (op is OpCodeSimdShImm fixedOp)
{
int fBits = GetImmShr(fixedOp);
// BitConverter.Int64BitsToDouble(fpScaled) == 1d / Math.Pow(2d, fBits)
long fpScaled = 0x3FF0000000000000L - fBits * 0x10000000000000L;
Operand fpScaledMask = scalar
? X86GetScalar (context, fpScaled)
: X86GetAllElements(context, fpScaled);
res = context.AddIntrinsic(Intrinsic.X86Mulpd, res, fpScaledMask);
}
if (scalar)
{
res = context.VectorZeroUpper64(res);
}
context.Copy(GetVec(op.Rd), res);
}
}
private static void EmitSse41Fcvts(ArmEmitterContext context, FPRoundingMode roundMode, bool scalar)
{
OpCodeSimd op = (OpCodeSimd)context.CurrOp;
Operand n = GetVec(op.Rn);
// sizeF == ((OpCodeSimdShImm)op).Size - 2
int sizeF = op.Size & 1;
if (sizeF == 0)
{
Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmpps, n, n, Const((int)CmpCondition.OrderedQ));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n);
if (op is OpCodeSimdShImm fixedOp)
{
int fBits = GetImmShr(fixedOp);
// BitConverter.Int32BitsToSingle(fpScaled) == MathF.Pow(2f, fBits)
int fpScaled = 0x3F800000 + fBits * 0x800000;
Operand fpScaledMask = scalar
? X86GetScalar (context, fpScaled)
: X86GetAllElements(context, fpScaled);
nRes = context.AddIntrinsic(Intrinsic.X86Mulps, nRes, fpScaledMask);
}
nRes = context.AddIntrinsic(Intrinsic.X86Roundps, nRes, Const(X86GetRoundControl(roundMode)));
Operand nInt = context.AddIntrinsic(Intrinsic.X86Cvtps2dq, nRes);
Operand fpMaxValMask = scalar // 2.14748365E9f (2147483648)
? X86GetScalar (context, 0x4F000000)
: X86GetAllElements(context, 0x4F000000);
nRes = context.AddIntrinsic(Intrinsic.X86Cmpps, nRes, fpMaxValMask, Const((int)CmpCondition.NotLessThan));
Operand dRes = context.AddIntrinsic(Intrinsic.X86Pxor, nInt, nRes);
if (scalar)
{
dRes = context.VectorZeroUpper96(dRes);
}
else if (op.RegisterSize == RegisterSize.Simd64)
{
dRes = context.VectorZeroUpper64(dRes);
}
context.Copy(GetVec(op.Rd), dRes);
}
else /* if (sizeF == 1) */
{
Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmppd, n, n, Const((int)CmpCondition.OrderedQ));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n);
if (op is OpCodeSimdShImm fixedOp)
{
int fBits = GetImmShr(fixedOp);
// BitConverter.Int64BitsToDouble(fpScaled) == Math.Pow(2d, fBits)
long fpScaled = 0x3FF0000000000000L + fBits * 0x10000000000000L;
Operand fpScaledMask = scalar
? X86GetScalar (context, fpScaled)
: X86GetAllElements(context, fpScaled);
nRes = context.AddIntrinsic(Intrinsic.X86Mulpd, nRes, fpScaledMask);
}
nRes = context.AddIntrinsic(Intrinsic.X86Roundpd, nRes, Const(X86GetRoundControl(roundMode)));
Operand nLong = EmitSse2CvtDoubleToInt64OpF(context, nRes, scalar);
Operand fpMaxValMask = scalar // 9.2233720368547760E18d (9223372036854775808)
? X86GetScalar (context, 0x43E0000000000000L)
: X86GetAllElements(context, 0x43E0000000000000L);
nRes = context.AddIntrinsic(Intrinsic.X86Cmppd, nRes, fpMaxValMask, Const((int)CmpCondition.NotLessThan));
Operand dRes = context.AddIntrinsic(Intrinsic.X86Pxor, nLong, nRes);
if (scalar)
{
dRes = context.VectorZeroUpper64(dRes);
}
context.Copy(GetVec(op.Rd), dRes);
}
}
private static void EmitSse41Fcvtu(ArmEmitterContext context, FPRoundingMode roundMode, bool scalar)
{
OpCodeSimd op = (OpCodeSimd)context.CurrOp;
Operand n = GetVec(op.Rn);
// sizeF == ((OpCodeSimdShImm)op).Size - 2
int sizeF = op.Size & 1;
if (sizeF == 0)
{
Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmpps, n, n, Const((int)CmpCondition.OrderedQ));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n);
if (op is OpCodeSimdShImm fixedOp)
{
int fBits = GetImmShr(fixedOp);
// BitConverter.Int32BitsToSingle(fpScaled) == MathF.Pow(2f, fBits)
int fpScaled = 0x3F800000 + fBits * 0x800000;
Operand fpScaledMask = scalar
? X86GetScalar (context, fpScaled)
: X86GetAllElements(context, fpScaled);
nRes = context.AddIntrinsic(Intrinsic.X86Mulps, nRes, fpScaledMask);
}
nRes = context.AddIntrinsic(Intrinsic.X86Roundps, nRes, Const(X86GetRoundControl(roundMode)));
Operand zero = context.VectorZero();
Operand nCmp = context.AddIntrinsic(Intrinsic.X86Cmpps, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp);
Operand fpMaxValMask = scalar // 2.14748365E9f (2147483648)
? X86GetScalar (context, 0x4F000000)
: X86GetAllElements(context, 0x4F000000);
Operand nInt = context.AddIntrinsic(Intrinsic.X86Cvtps2dq, nRes);
nRes = context.AddIntrinsic(Intrinsic.X86Subps, nRes, fpMaxValMask);
nCmp = context.AddIntrinsic(Intrinsic.X86Cmpps, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp);
Operand nInt2 = context.AddIntrinsic(Intrinsic.X86Cvtps2dq, nRes);
nRes = context.AddIntrinsic(Intrinsic.X86Cmpps, nRes, fpMaxValMask, Const((int)CmpCondition.NotLessThan));
Operand dRes = context.AddIntrinsic(Intrinsic.X86Pxor, nInt2, nRes);
dRes = context.AddIntrinsic(Intrinsic.X86Paddd, dRes, nInt);
if (scalar)
{
dRes = context.VectorZeroUpper96(dRes);
}
else if (op.RegisterSize == RegisterSize.Simd64)
{
dRes = context.VectorZeroUpper64(dRes);
}
context.Copy(GetVec(op.Rd), dRes);
}
else /* if (sizeF == 1) */
{
Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmppd, n, n, Const((int)CmpCondition.OrderedQ));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n);
if (op is OpCodeSimdShImm fixedOp)
{
int fBits = GetImmShr(fixedOp);
// BitConverter.Int64BitsToDouble(fpScaled) == Math.Pow(2d, fBits)
long fpScaled = 0x3FF0000000000000L + fBits * 0x10000000000000L;
Operand fpScaledMask = scalar
? X86GetScalar (context, fpScaled)
: X86GetAllElements(context, fpScaled);
nRes = context.AddIntrinsic(Intrinsic.X86Mulpd, nRes, fpScaledMask);
}
nRes = context.AddIntrinsic(Intrinsic.X86Roundpd, nRes, Const(X86GetRoundControl(roundMode)));
Operand zero = context.VectorZero();
Operand nCmp = context.AddIntrinsic(Intrinsic.X86Cmppd, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp);
Operand fpMaxValMask = scalar // 9.2233720368547760E18d (9223372036854775808)
? X86GetScalar (context, 0x43E0000000000000L)
: X86GetAllElements(context, 0x43E0000000000000L);
Operand nLong = EmitSse2CvtDoubleToInt64OpF(context, nRes, scalar);
nRes = context.AddIntrinsic(Intrinsic.X86Subpd, nRes, fpMaxValMask);
nCmp = context.AddIntrinsic(Intrinsic.X86Cmppd, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp);
Operand nLong2 = EmitSse2CvtDoubleToInt64OpF(context, nRes, scalar);
nRes = context.AddIntrinsic(Intrinsic.X86Cmppd, nRes, fpMaxValMask, Const((int)CmpCondition.NotLessThan));
Operand dRes = context.AddIntrinsic(Intrinsic.X86Pxor, nLong2, nRes);
dRes = context.AddIntrinsic(Intrinsic.X86Paddq, dRes, nLong);
if (scalar)
{
dRes = context.VectorZeroUpper64(dRes);
}
context.Copy(GetVec(op.Rd), dRes);
}
}
private static void EmitSse41Fcvts_Gp(ArmEmitterContext context, FPRoundingMode roundMode, bool isFixed)
{
OpCodeSimdCvt op = (OpCodeSimdCvt)context.CurrOp;
Operand n = GetVec(op.Rn);
if (op.Size == 0)
{
Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmpss, n, n, Const((int)CmpCondition.OrderedQ));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n);
if (isFixed)
{
// BitConverter.Int32BitsToSingle(fpScaled) == MathF.Pow(2f, op.FBits)
int fpScaled = 0x3F800000 + op.FBits * 0x800000;
Operand fpScaledMask = X86GetScalar(context, fpScaled);
nRes = context.AddIntrinsic(Intrinsic.X86Mulss, nRes, fpScaledMask);
}
nRes = context.AddIntrinsic(Intrinsic.X86Roundss, nRes, Const(X86GetRoundControl(roundMode)));
Operand nIntOrLong = op.RegisterSize == RegisterSize.Int32
? context.AddIntrinsicInt (Intrinsic.X86Cvtss2si, nRes)
: context.AddIntrinsicLong(Intrinsic.X86Cvtss2si, nRes);
int fpMaxVal = op.RegisterSize == RegisterSize.Int32
? 0x4F000000 // 2.14748365E9f (2147483648)
: 0x5F000000; // 9.223372E18f (9223372036854775808)
Operand fpMaxValMask = X86GetScalar(context, fpMaxVal);
nRes = context.AddIntrinsic(Intrinsic.X86Cmpss, nRes, fpMaxValMask, Const((int)CmpCondition.NotLessThan));
Operand nInt = context.AddIntrinsicInt(Intrinsic.X86Cvtsi2si, nRes);
if (op.RegisterSize == RegisterSize.Int64)
{
nInt = context.SignExtend32(OperandType.I64, nInt);
}
Operand dRes = context.BitwiseExclusiveOr(nIntOrLong, nInt);
SetIntOrZR(context, op.Rd, dRes);
}
else /* if (op.Size == 1) */
{
Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmpsd, n, n, Const((int)CmpCondition.OrderedQ));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n);
if (isFixed)
{
// BitConverter.Int64BitsToDouble(fpScaled) == Math.Pow(2d, op.FBits)
long fpScaled = 0x3FF0000000000000L + op.FBits * 0x10000000000000L;
Operand fpScaledMask = X86GetScalar(context, fpScaled);
nRes = context.AddIntrinsic(Intrinsic.X86Mulsd, nRes, fpScaledMask);
}
nRes = context.AddIntrinsic(Intrinsic.X86Roundsd, nRes, Const(X86GetRoundControl(roundMode)));
Operand nIntOrLong = op.RegisterSize == RegisterSize.Int32
? context.AddIntrinsicInt (Intrinsic.X86Cvtsd2si, nRes)
: context.AddIntrinsicLong(Intrinsic.X86Cvtsd2si, nRes);
long fpMaxVal = op.RegisterSize == RegisterSize.Int32
? 0x41E0000000000000L // 2147483648.0000000d (2147483648)
: 0x43E0000000000000L; // 9.2233720368547760E18d (9223372036854775808)
Operand fpMaxValMask = X86GetScalar(context, fpMaxVal);
nRes = context.AddIntrinsic(Intrinsic.X86Cmpsd, nRes, fpMaxValMask, Const((int)CmpCondition.NotLessThan));
Operand nLong = context.AddIntrinsicLong(Intrinsic.X86Cvtsi2si, nRes);
if (op.RegisterSize == RegisterSize.Int32)
{
nLong = context.ConvertI64ToI32(nLong);
}
Operand dRes = context.BitwiseExclusiveOr(nIntOrLong, nLong);
SetIntOrZR(context, op.Rd, dRes);
}
}
private static void EmitSse41Fcvtu_Gp(ArmEmitterContext context, FPRoundingMode roundMode, bool isFixed)
{
OpCodeSimdCvt op = (OpCodeSimdCvt)context.CurrOp;
Operand n = GetVec(op.Rn);
if (op.Size == 0)
{
Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmpss, n, n, Const((int)CmpCondition.OrderedQ));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n);
if (isFixed)
{
// BitConverter.Int32BitsToSingle(fpScaled) == MathF.Pow(2f, op.FBits)
int fpScaled = 0x3F800000 + op.FBits * 0x800000;
Operand fpScaledMask = X86GetScalar(context, fpScaled);
nRes = context.AddIntrinsic(Intrinsic.X86Mulss, nRes, fpScaledMask);
}
nRes = context.AddIntrinsic(Intrinsic.X86Roundss, nRes, Const(X86GetRoundControl(roundMode)));
Operand zero = context.VectorZero();
Operand nCmp = context.AddIntrinsic(Intrinsic.X86Cmpss, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp);
int fpMaxVal = op.RegisterSize == RegisterSize.Int32
? 0x4F000000 // 2.14748365E9f (2147483648)
: 0x5F000000; // 9.223372E18f (9223372036854775808)
Operand fpMaxValMask = X86GetScalar(context, fpMaxVal);
Operand nIntOrLong = op.RegisterSize == RegisterSize.Int32
? context.AddIntrinsicInt (Intrinsic.X86Cvtss2si, nRes)
: context.AddIntrinsicLong(Intrinsic.X86Cvtss2si, nRes);
nRes = context.AddIntrinsic(Intrinsic.X86Subss, nRes, fpMaxValMask);
nCmp = context.AddIntrinsic(Intrinsic.X86Cmpss, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp);
Operand nIntOrLong2 = op.RegisterSize == RegisterSize.Int32
? context.AddIntrinsicInt (Intrinsic.X86Cvtss2si, nRes)
: context.AddIntrinsicLong(Intrinsic.X86Cvtss2si, nRes);
nRes = context.AddIntrinsic(Intrinsic.X86Cmpss, nRes, fpMaxValMask, Const((int)CmpCondition.NotLessThan));
Operand nInt = context.AddIntrinsicInt(Intrinsic.X86Cvtsi2si, nRes);
if (op.RegisterSize == RegisterSize.Int64)
{
nInt = context.SignExtend32(OperandType.I64, nInt);
}
Operand dRes = context.BitwiseExclusiveOr(nIntOrLong2, nInt);
dRes = context.Add(dRes, nIntOrLong);
SetIntOrZR(context, op.Rd, dRes);
}
else /* if (op.Size == 1) */
{
Operand nRes = context.AddIntrinsic(Intrinsic.X86Cmpsd, n, n, Const((int)CmpCondition.OrderedQ));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, n);
if (isFixed)
{
// BitConverter.Int64BitsToDouble(fpScaled) == Math.Pow(2d, op.FBits)
long fpScaled = 0x3FF0000000000000L + op.FBits * 0x10000000000000L;
Operand fpScaledMask = X86GetScalar(context, fpScaled);
nRes = context.AddIntrinsic(Intrinsic.X86Mulsd, nRes, fpScaledMask);
}
nRes = context.AddIntrinsic(Intrinsic.X86Roundsd, nRes, Const(X86GetRoundControl(roundMode)));
Operand zero = context.VectorZero();
Operand nCmp = context.AddIntrinsic(Intrinsic.X86Cmpsd, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp);
long fpMaxVal = op.RegisterSize == RegisterSize.Int32
? 0x41E0000000000000L // 2147483648.0000000d (2147483648)
: 0x43E0000000000000L; // 9.2233720368547760E18d (9223372036854775808)
Operand fpMaxValMask = X86GetScalar(context, fpMaxVal);
Operand nIntOrLong = op.RegisterSize == RegisterSize.Int32
? context.AddIntrinsicInt (Intrinsic.X86Cvtsd2si, nRes)
: context.AddIntrinsicLong(Intrinsic.X86Cvtsd2si, nRes);
nRes = context.AddIntrinsic(Intrinsic.X86Subsd, nRes, fpMaxValMask);
nCmp = context.AddIntrinsic(Intrinsic.X86Cmpsd, nRes, zero, Const((int)CmpCondition.NotLessThanOrEqual));
nRes = context.AddIntrinsic(Intrinsic.X86Pand, nRes, nCmp);
Operand nIntOrLong2 = op.RegisterSize == RegisterSize.Int32
? context.AddIntrinsicInt (Intrinsic.X86Cvtsd2si, nRes)
: context.AddIntrinsicLong(Intrinsic.X86Cvtsd2si, nRes);
nRes = context.AddIntrinsic(Intrinsic.X86Cmpsd, nRes, fpMaxValMask, Const((int)CmpCondition.NotLessThan));
Operand nLong = context.AddIntrinsicLong(Intrinsic.X86Cvtsi2si, nRes);
if (op.RegisterSize == RegisterSize.Int32)
{
nLong = context.ConvertI64ToI32(nLong);
}
Operand dRes = context.BitwiseExclusiveOr(nIntOrLong2, nLong);
dRes = context.Add(dRes, nIntOrLong);
SetIntOrZR(context, op.Rd, dRes);
}
}
private static Operand EmitVectorLongExtract(ArmEmitterContext context, int reg, int index, int size)
{
OperandType type = size == 3 ? OperandType.I64 : OperandType.I32;
return context.VectorExtract(type, GetVec(reg), index);
}
}
}
| 36.642952 | 133 | 0.53414 | [
"MIT"
] | AidanXu/Ryujinx | ARMeilleure/Instructions/InstEmitSimdCvt.cs | 55,111 | C# |
using System.Web.Http;
using AttributeRouting.Web.Http.WebHost;
[assembly: WebActivator.PreApplicationStartMethod(typeof(Radsurge.MVC.AttributeRoutingHttpConfig), "Start")]
namespace Radsurge.MVC
{
public static class AttributeRoutingHttpConfig
{
public static void RegisterRoutes(HttpRouteCollection routes)
{
// See http://github.com/mccalltd/AttributeRouting/wiki for more options.
// To debug routes locally using the built in ASP.NET development server, go to /routes.axd
routes.MapHttpAttributeRoutes();
}
public static void Start()
{
RegisterRoutes(GlobalConfiguration.Configuration.Routes);
}
}
}
| 28.291667 | 108 | 0.727541 | [
"Apache-2.0"
] | ctufaro/Radsurge | Radsurge.MVC/App_Start/AttributeRoutingHttpConfig.cs | 679 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZoDream.Shared.Models;
namespace ZoDream.Shared.Interfaces
{
public interface IStorageProvider<FolderT, FileT, FileStreamT>
{
/// <summary>
/// 文件备选保存目录
/// </summary>
public FolderT BaseFolder { get; set; }
/// <summary>
/// 根据项目文件设置保存目录
/// </summary>
public FileT EntranceFile { set; }
/// <summary>
/// 根据项目文件夹设置保存目录
/// </summary>
public FolderT? EntranceFolder { set; }
public Task CreateAsync(string fileName, byte[] data);
public Task CreateAsync(UriItem uri, byte[] data);
/// <summary>
/// 创造写入流
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public Task<FileStreamT> CreateStreamAsync(string fileName);
public Task<FileStreamT> CreateStreamAsync(UriItem uri);
public Task<FileStreamT?> OpenStreamAsync(string fileName);
public Task<FileStreamT?> OpenStreamAsync(UriItem uri);
public string GetAbsolutePath(string fileName);
public string GetRelativePath(string fileName);
}
}
| 26.583333 | 68 | 0.621473 | [
"MIT"
] | zx648383079/ZoDream.Spider | src/ZoDream.Shared/Interfaces/IStorageProvider.cs | 1,354 | C# |
using System.Collections.Generic;
using PostgresTraining.V1.Controllers;
using PostgresTraining.V1.Infrastructure;
using FluentAssertions;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Controllers;
using Microsoft.AspNetCore.Routing;
using NUnit.Framework;
using Xunit;
namespace PostgresTraining.Tests.V1.Controllers
{
public class BaseControllerTests
{
private BaseController _sut;
private ControllerContext _controllerContext;
private HttpContext _stubHttpContext;
public BaseControllerTests()
{
_stubHttpContext = new DefaultHttpContext();
_controllerContext = new ControllerContext(new ActionContext(_stubHttpContext, new RouteData(), new ControllerActionDescriptor()));
_sut = new BaseController();
_sut.ControllerContext = _controllerContext;
}
[Fact]
public void GetCorrelationShouldThrowExceptionIfCorrelationHeaderUnavailable()
{
// Arrange + Act + Assert
_sut.Invoking(x => x.GetCorrelationId())
.Should().Throw<KeyNotFoundException>()
.WithMessage("Request is missing a correlationId");
}
[Fact]
public void GetCorrelationShouldReturnCorrelationIdWhenExists()
{
// Arrange
_stubHttpContext.Request.Headers.Add(Constants.CorrelationId, "123");
// Act
var result = _sut.GetCorrelationId();
// Assert
result.Should().BeEquivalentTo("123");
}
}
}
| 31 | 143 | 0.665012 | [
"MIT"
] | LBHackney-IT/postgres-training | PostgresTraining.Tests/V1/Controllers/BaseControllerTests.cs | 1,612 | C# |
using System.Collections.Generic;
using System.Linq;
using YantraJS.Core.Core.Storage;
namespace YantraJS.Core.FastParser
{
public partial class FastScopeItem: LinkedStackItem<FastScopeItem>
{
private StringMap<(StringSpan name, FastVariableKind kind)> Variables;
// private readonly FastToken token;
public readonly FastNodeType NodeType;
// private readonly FastPool pool;
public FastScopeItem(FastNodeType nodeType)
{
// this.token = token;
this.NodeType = nodeType;
// this.pool = pool;
}
//public void CreateVariable(AstExpression d, FastVariableKind kind)
//{
// switch ((d.Type, d))
// {
// case (FastNodeType.Identifier, AstIdentifier id):
// AddVariable(d.Start, id.Name, kind);
// break;
// case (FastNodeType.SpreadElement, AstSpreadElement spe):
// CreateVariable(spe.Argument, kind);
// break;
// case (FastNodeType.ArrayPattern, AstArrayPattern ap):
// foreach (var e in ap.Elements)
// {
// CreateVariable(e, kind);
// }
// break;
// case (FastNodeType.ObjectPattern, AstObjectPattern op):
// foreach (ObjectProperty p in op.Properties)
// {
// CreateVariable(p.Value, kind);
// }
// break;
// }
//}
public void AddVariable(FastToken token,
in StringSpan name,
FastVariableKind kind = FastVariableKind.Var,
bool throwError = true)
{
if (name.IsNullOrWhiteSpace())
return;
var n = this;
while (n != null)
{
if (n.Variables.TryGetValue(name, out var pn))
{
if (pn.kind != FastVariableKind.Var)
{
if (throwError)
{
throw new FastParseException(token, $"{name} is already defined in current scope at {token.Start}");
}
return;
}
}
if (n.Parent != null && n.NodeType == FastNodeType.Block && n.Parent.NodeType == FastNodeType.Block)
{
n = n.Parent;
continue;
}
break;
}
n = this;
// all `var` variables must be hoisted to
// to top most scope
if (kind == FastVariableKind.Var) {
while (true) {
if (n.Parent == null)
break;
if (n.NodeType == FastNodeType.Block
&& n.Parent.NodeType == FastNodeType.Block) {
n = n.Parent;
continue;
}
break;
}
}
n.Variables.Put(name) = (name, kind);
}
public IFastEnumerable<StringSpan> GetVariables()
{
var list = new Sequence<StringSpan>();
try
{
foreach (var node in Variables.AllValues())
{
list.Add(node.Value.name);
}
if (list.Count == 0)
return Sequence<StringSpan>.Empty;
return list;
} finally
{
// list.Clear();
}
}
}
}
| 32.90678 | 129 | 0.420294 | [
"Apache-2.0"
] | yantrajs/yantra | YantraJS.Core/FastParser/Parser/FastScopeItem.cs | 3,768 | C# |
using System;
using Microsoft.Azure.Documents.Client;
using Microsoft.Extensions.Configuration;
namespace PartsUnlimited.WebsiteConfiguration
{
public class DocumentDbConfiguration : IDocumentDBConfiguration
{
private readonly DocumentClient _client;
public DocumentDbConfiguration(IConfiguration config)
{
URI = config["URI"];
Key = config["Key"];
DatabaseId = "PartsUnlimited";
CollectionId = "ProductCollection";
_client = null;
}
public string URI { get; }
public string Key { get; }
public string DatabaseId { get; }
public string CollectionId { get; }
public DocumentClient BuildClient()
{
if (_client == null)
{
var serviceEndpoint = new Uri(URI);
var client = new DocumentClient(serviceEndpoint, Key, ConnectionPolicy.Default);
return client;
}
return _client;
}
public Uri BuildProductCollectionLink()
{
return UriFactory.CreateDocumentCollectionUri(DatabaseId, CollectionId);
}
public Uri BuildProductLink(int productId)
{
return UriFactory.CreateDocumentUri(DatabaseId, CollectionId, productId.ToString());
}
public Uri BuildAttachmentLink(int productId)
{
return UriFactory.CreateAttachmentUri(DatabaseId, CollectionId, productId.ToString(), productId.ToString());
}
public Uri BuildDatabaseLink()
{
return UriFactory.CreateDatabaseUri(DatabaseId);
}
}
} | 29.892857 | 120 | 0.60693 | [
"MIT"
] | DChak2021/PartsUnlimited | src/PartsUnlimitedWebsite/WebsiteConfiguration/DocumentDbConfiguration.cs | 1,674 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
public class PauseMenu : MonoBehaviour
{
public static bool GameIsPaused = false;
public GameObject pauseMenuUI;
// Update is called once per frame
void Update()
{
//uses the p button to pause and unpause the game
if (Input.GetKeyDown(KeyCode.Escape))
{
if (GameIsPaused)
{
Resume();
}
else
{
Pause();
}
}
}
public void Resume()
{
AudioSource music = GameController.FindObjectOfType<AudioSource>();
pauseMenuUI.SetActive(false);
Time.timeScale = 1f;
GameIsPaused = false;
music.UnPause();
}
void Pause()
{
AudioSource music = GameController.FindObjectOfType<AudioSource>();
pauseMenuUI.SetActive(true);
Time.timeScale = 0f;
GameIsPaused = true;
music.Pause();
}
public void LoadMenu()
{
Time.timeScale = 1f;
SceneManager.LoadScene("Menu");
Destroy(gameObject);
}
public void ReloadLevel()
{
Time.timeScale = 1f;
SceneManager.LoadScene(SceneManager.GetActiveScene().buildIndex);
Destroy(gameObject);
}
}
| 23.101695 | 75 | 0.573734 | [
"MIT"
] | bautrey37/Outlight | Assets/Scripts/Menu/PauseMenu.cs | 1,365 | C# |
/* Yet Another Forum.NET
* Copyright (C) 2006-2013 Jaben Cargman
* http://www.yetanotherforum.net/
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA.
*/
namespace YAF.Types.Models
{
using System;
using ServiceStack.DataAnnotations;
using YAF.Types.Interfaces.Data;
/// <summary>
/// A class which represents the WatchTopic table.
/// </summary>
[Serializable]
public partial class WatchTopic : IEntity, IHaveID
{
partial void OnCreated();
public WatchTopic()
{
this.OnCreated();
}
#region Properties
[AutoIncrement]
[Alias("WatchTopicID")]
public int ID { get; set; }
public int TopicID { get; set; }
public int UserID { get; set; }
public DateTime Created { get; set; }
public DateTime? LastMail { get; set; }
#endregion
}
} | 27.946429 | 78 | 0.658147 | [
"Unlicense"
] | tlayson/MySC | Utils/Tools/YAF/YAF.Types/Models/WatchTopic.cs | 1,565 | C# |
using System;
using System.Linq;
using System.Net.Http;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Xamarin.Essentials;
namespace SquareSix.Core
{
public class RestService : IRestService
{
private readonly HttpClient _client;
protected virtual TimeSpan TimeoutAfter => TimeSpan.FromSeconds(15);
public RestService()
{
_client = new HttpClient
{
Timeout = TimeoutAfter
};
}
private async Task EnsureRequestHeaders(HttpRequestMessage msg)
{
if (SimpleIOC.Container.ContainsKey<IAuthorizationHeaderService>())
{
var headerService = SimpleIOC.Container.Resolve<IAuthorizationHeaderService>();
var authHeaders = await headerService.GetAuthorizationHeaders();
if (authHeaders?.Any() ?? false)
{
foreach (var kvp in authHeaders)
{
if (string.IsNullOrEmpty(kvp.Key) || string.IsNullOrEmpty(kvp.Value))
{
continue;
}
msg.Headers.Add(kvp.Key, kvp.Value);
}
}
}
}
public async Task<RestResponse<T>> PrepareAndSendRequest<T>(HttpMethod httpMethod, Uri uri, object data, CancellationToken cancellationToken, bool addAuthHeader = true, string contentType = "application/json")
{
if (Connectivity.NetworkAccess != NetworkAccess.Internet)
{
throw new NetworkException();
}
using (var message = new HttpRequestMessage(httpMethod, uri))
{
if (data != null)
{
var content = JsonConvert.SerializeObject(data);
message.Content = new StringContent(content, Encoding.UTF8, contentType);
}
if (addAuthHeader)
{
await EnsureRequestHeaders(message);
}
return await _client.RequestAsync<T>(message, cancellationToken);
}
}
}
}
| 31.666667 | 217 | 0.537719 | [
"MIT"
] | Square-Six/SquareSix.Core | src/SquareSix.Core/Services/RestService.cs | 2,282 | C# |
/*
* Made by: Ava Fritts
*
* Created Feb 9 2022
* last edited: Feb 9 2022
*/
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class HighScore : MonoBehaviour
{
static public int score = 1000;
void Awake()
{
if (PlayerPrefs.HasKey("HighScore"))
{
score = PlayerPrefs.GetInt("HighScore");
}
PlayerPrefs.SetInt("HighScore", score);
}
// Start is called before the first frame update
void Start()
{
}
// Update is called once per frame
void Update()
{
Text gt = this.GetComponent<Text>();
gt.text = "High Score: " + score;
if (score > PlayerPrefs.GetInt("HighScore"))
{
PlayerPrefs.SetInt("HighScore", score);
}
}
}
| 20.047619 | 52 | 0.572447 | [
"MIT"
] | AvaFritts/ApplePicker | ApplePicker-Unity/Assets/Scripts/HighScore.cs | 842 | C# |
using System;
using AGXUnity;
using AGXUnity.Collide;
using UnityEditor;
namespace AGXUnityEditor.Editors
{
[CustomEditor( typeof( AGXUnity.Model.OneBodyTire ) )]
[CanEditMultipleObjects]
public class AGXUnityModelOneBodyTireEditor : InspectorEditor
{ }
} | 20.384615 | 63 | 0.792453 | [
"Apache-2.0"
] | Algoryx/AGXUnity | Editor/CustomEditors/AGXUnity+Model+OneBodyTireEditor.cs | 265 | C# |
namespace System.Collections.Generic
{
class KeyValuePairList<TKey, TValue> : List<KeyValuePair<TKey, TValue>>
{
public KeyValuePairList()
{
}
public void Add(TKey key, TValue value)
{
this.Add(new KeyValuePair<TKey, TValue>(key, value));
}
}
}
| 22.714286 | 75 | 0.575472 | [
"MIT"
] | johnnyleecn/Chloe | src/Chloe/Utility/KeyValuePairList.cs | 320 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using JetBrains.Annotations;
namespace Yolol.Analysis.ControlFlowGraph
{
public interface IControlFlowGraph
: IEquatable<IControlFlowGraph>
{
IEnumerable<IEdge> Edges { get; }
uint EdgeCount { get; }
IEnumerable<IBasicBlock> Vertices { get; }
uint VertexCount { get; }
[CanBeNull] IBasicBlock Vertex(Guid id);
}
public interface IMutableControlFlowGraph
: IControlFlowGraph
{
IMutableBasicBlock CreateNewBlock(BasicBlockType type, int lineNumber, Guid? id = null);
IEdge CreateEdge([NotNull] IBasicBlock start, [NotNull] IBasicBlock end, EdgeType type);
}
public static class IControlFlowGraphExtensions
{
public static IBasicBlock EntryPoint([NotNull] this IControlFlowGraph cfg)
{
return cfg.Vertices.Single(a => a.Type == BasicBlockType.Entry);
}
}
}
| 25.631579 | 96 | 0.673511 | [
"MIT"
] | thomasio101/Yolol | Yolol.Analysis/ControlFlowGraph/IControlFlowGraph.cs | 976 | C# |
using System.Drawing;
using System.Drawing.Drawing2D;
namespace Sharp2048
{
class Drawing
{
public static GraphicsPath RoundedRect(Rectangle bounds, int radius)
{
int diameter = radius * 2;
Size size = new Size(diameter, diameter);
Rectangle arc = new Rectangle(bounds.Location, size);
GraphicsPath path = new GraphicsPath();
if (radius == 0)
{
path.AddRectangle(bounds);
return path;
}
// top left arc
path.AddArc(arc, 180, 90);
// top right arc
arc.X = bounds.Right - diameter;
path.AddArc(arc, 270, 90);
// bottom right arc
arc.Y = bounds.Bottom - diameter;
path.AddArc(arc, 0, 90);
// bottom left arc
arc.X = bounds.Left;
path.AddArc(arc, 90, 90);
path.CloseFigure();
return path;
}
public static void SetColor(int Number)
{
Color NumberColor;
switch (Number)
{
case 0: NumberColor = Color.FromArgb(204, 192, 179); break;
case 2: NumberColor = Color.FromArgb(238, 228, 218); break;
case 4: NumberColor = Color.FromArgb(237, 224, 200); break;
case 8: NumberColor = Color.FromArgb(242, 177, 121); break;
case 16: NumberColor = Color.FromArgb(245, 149, 99); break;
case 32: NumberColor = Color.FromArgb(246, 124, 95); break;
case 64: NumberColor = Color.FromArgb(246, 94, 59); break;
case 128: NumberColor = Color.FromArgb(237, 207, 114); break;
case 256: NumberColor = Color.FromArgb(237, 204, 97); break;
case 512: NumberColor = Color.FromArgb(237, 200, 80); break;
case 1024: NumberColor = Color.FromArgb(237, 197, 63); break;
case 2048: NumberColor = Color.FromArgb(237, 194, 46); break;
default: NumberColor = Color.FromArgb(204, 192, 179); break;
}
Parameters.NumberBrush = new SolidBrush(NumberColor);
}
public static void DrawGame(Graphics Paint, ref int[,] GameMatrix, Rectangle FieldRect)
{
int n = GameMatrix.GetLength(0);
Paint.Clear(Color.FromArgb(187, 173, 160));
for (int i = 0; i < n; i++)
{
for (int j = 0; j < n; j++)
{
SetColor(GameMatrix[i, j]);
Rectangle NumberRect = new Rectangle
(
i * FieldRect.Width / Parameters.FieldSize + 3,
j * FieldRect.Height / Parameters.FieldSize + 3,
FieldRect.Width / Parameters.FieldSize - 6,
FieldRect.Height / Parameters.FieldSize - 6
);
DrawNumber(Paint, GameMatrix[i, j], NumberRect);
}
}
}
public static void DrawNumber(Graphics Paint, int Number, Rectangle NumberRect)
{
RectangleF TextLayout = new RectangleF(NumberRect.X, NumberRect.Y, NumberRect.Width, NumberRect.Height);
StringFormat sf = new StringFormat
{
LineAlignment = StringAlignment.Center,
Alignment = StringAlignment.Center
};
Paint.SmoothingMode = SmoothingMode.AntiAlias;
if (Parameters.Pallete == Parameters.PalleteType.Rounded)
{
using (GraphicsPath path = Drawing.RoundedRect(NumberRect, 6))
{
Paint.FillPath(Parameters.NumberBrush, path);
}
}
else
{
Paint.FillRectangle(Parameters.NumberBrush, NumberRect);
}
if (Number > 0)
{
Paint.DrawString(Number.ToString(), Parameters.TextFont, Parameters.TextBrush, TextLayout, sf);
}
}
}
}
| 35.336134 | 116 | 0.502259 | [
"BSD-2-Clause"
] | Limows/Sharp2048 | Sharp2048-NC/Sharp2048/Drawing.cs | 4,207 | C# |
using System;
using Theraot.Core;
namespace Theraot.Collections
{
[Serializable]
public sealed class FilteredConvertedObserver<TInput, TOutput> : IObserver<TInput>
{
private readonly Converter<TInput, TOutput> _converter;
private readonly IObserver<TOutput> _observer;
private readonly Predicate<TInput> _predicate;
public FilteredConvertedObserver(IObserver<TOutput> observer, Converter<TInput, TOutput> converter, Predicate<TInput> predicate)
{
_observer = Check.NotNullArgument(observer, "observer");
_converter = Check.NotNullArgument(converter, "converter");
_predicate = Check.NotNullArgument(predicate, "predicate");
}
public void OnCompleted()
{
_observer.OnCompleted();
}
public void OnError(Exception error)
{
_observer.OnError(error);
}
public void OnNext(TInput value)
{
if (_predicate(value))
{
_observer.OnNext(_converter.Invoke(value));
}
}
}
} | 28.538462 | 136 | 0.617251 | [
"MIT",
"Unlicense"
] | qwertie/Theraot | Core/Theraot/Collections/FilteredConvertedObserver.cs | 1,113 | C# |
/*
* Copyright (c) 2007-2008, openmetaverse.org
* All rights reserved.
*
* - Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* - Redistributions of source code must retain the above copyright notice, this
* list of conditions and the following disclaimer.
* - Neither the name of the openmetaverse.org nor the names
* of its contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
* LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
* POSSIBILITY OF SUCH DAMAGE.
*/
using System;
using System.Text;
using System.Collections.Generic;
using OpenMetaverse.Packets;
namespace OpenMetaverse
{
/// <summary>
///
/// </summary>
[Flags]
public enum FriendRights : int
{
/// <summary>The avatar has no rights</summary>
None = 0,
/// <summary>The avatar can see the online status of the target avatar</summary>
CanSeeOnline = 1,
/// <summary>The avatar can see the location of the target avatar on the map</summary>
CanSeeOnMap = 2,
/// <summary>The avatar can modify the ojects of the target avatar </summary>
CanModifyObjects = 4
}
/// <summary>
/// This class holds information about an avatar in the friends list. There are two ways
/// to interface to this class. The first is through the set of boolean properties. This is the typical
/// way clients of this class will use it. The second interface is through two bitflag properties,
/// TheirFriendsRights and MyFriendsRights
/// </summary>
public class FriendInfo
{
private UUID m_id;
private string m_name;
private bool m_isOnline;
private bool m_canSeeMeOnline;
private bool m_canSeeMeOnMap;
private bool m_canModifyMyObjects;
private bool m_canSeeThemOnline;
private bool m_canSeeThemOnMap;
private bool m_canModifyTheirObjects;
#region Properties
/// <summary>
/// System ID of the avatar
/// </summary>
public UUID UUID { get { return m_id; } }
/// <summary>
/// full name of the avatar
/// </summary>
public string Name
{
get { return m_name; }
set { m_name = value; }
}
/// <summary>
/// True if the avatar is online
/// </summary>
public bool IsOnline
{
get { return m_isOnline; }
set { m_isOnline = value; }
}
/// <summary>
/// True if the friend can see if I am online
/// </summary>
public bool CanSeeMeOnline
{
get { return m_canSeeMeOnline; }
set
{
m_canSeeMeOnline = value;
// if I can't see them online, then I can't see them on the map
if (!m_canSeeMeOnline)
m_canSeeMeOnMap = false;
}
}
/// <summary>
/// True if the friend can see me on the map
/// </summary>
public bool CanSeeMeOnMap
{
get { return m_canSeeMeOnMap; }
set
{
// if I can't see them online, then I can't see them on the map
if (m_canSeeMeOnline)
m_canSeeMeOnMap = value;
}
}
/// <summary>
/// True if the freind can modify my objects
/// </summary>
public bool CanModifyMyObjects
{
get { return m_canModifyMyObjects; }
set { m_canModifyMyObjects = value; }
}
/// <summary>
/// True if I can see if my friend is online
/// </summary>
public bool CanSeeThemOnline { get { return m_canSeeThemOnline; } }
/// <summary>
/// True if I can see if my friend is on the map
/// </summary>
public bool CanSeeThemOnMap { get { return m_canSeeThemOnMap; } }
/// <summary>
/// True if I can modify my friend's objects
/// </summary>
public bool CanModifyTheirObjects { get { return m_canModifyTheirObjects; } }
/// <summary>
/// My friend's rights represented as bitmapped flags
/// </summary>
public FriendRights TheirFriendRights
{
get
{
FriendRights results = FriendRights.None;
if (m_canSeeMeOnline)
results |= FriendRights.CanSeeOnline;
if (m_canSeeMeOnMap)
results |= FriendRights.CanSeeOnMap;
if (m_canModifyMyObjects)
results |= FriendRights.CanModifyObjects;
return results;
}
set
{
m_canSeeMeOnline = (value & FriendRights.CanSeeOnline) != 0;
m_canSeeMeOnMap = (value & FriendRights.CanSeeOnMap) != 0;
m_canModifyMyObjects = (value & FriendRights.CanModifyObjects) != 0;
}
}
/// <summary>
/// My rights represented as bitmapped flags
/// </summary>
public FriendRights MyFriendRights
{
get
{
FriendRights results = FriendRights.None;
if (m_canSeeThemOnline)
results |= FriendRights.CanSeeOnline;
if (m_canSeeThemOnMap)
results |= FriendRights.CanSeeOnMap;
if (m_canModifyTheirObjects)
results |= FriendRights.CanModifyObjects;
return results;
}
set
{
m_canSeeThemOnline = (value & FriendRights.CanSeeOnline) != 0;
m_canSeeThemOnMap = (value & FriendRights.CanSeeOnMap) != 0;
m_canModifyTheirObjects = (value & FriendRights.CanModifyObjects) != 0;
}
}
#endregion Properties
/// <summary>
/// Used internally when building the initial list of friends at login time
/// </summary>
/// <param name="id">System ID of the avatar being prepesented</param>
/// <param name="theirRights">Rights the friend has to see you online and to modify your objects</param>
/// <param name="myRights">Rights you have to see your friend online and to modify their objects</param>
internal FriendInfo(UUID id, FriendRights theirRights, FriendRights myRights)
{
m_id = id;
m_canSeeMeOnline = (theirRights & FriendRights.CanSeeOnline) != 0;
m_canSeeMeOnMap = (theirRights & FriendRights.CanSeeOnMap) != 0;
m_canModifyMyObjects = (theirRights & FriendRights.CanModifyObjects) != 0;
m_canSeeThemOnline = (myRights & FriendRights.CanSeeOnline) != 0;
m_canSeeThemOnMap = (myRights & FriendRights.CanSeeOnMap) != 0;
m_canModifyTheirObjects = (myRights & FriendRights.CanModifyObjects) != 0;
}
/// <summary>
/// FriendInfo represented as a string
/// </summary>
/// <returns>A string reprentation of both my rights and my friends rights</returns>
public override string ToString()
{
if (!String.IsNullOrEmpty(m_name))
return String.Format("{0} (Their Rights: {1}, My Rights: {2})", m_name, TheirFriendRights,
MyFriendRights);
else
return String.Format("{0} (Their Rights: {1}, My Rights: {2})", m_id, TheirFriendRights,
MyFriendRights);
}
}
/// <summary>
/// This class is used to add and remove avatars from your friends list and to manage their permission.
/// </summary>
public class FriendsManager
{
#region Delegates
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendInfoEventArgs> m_FriendOnline;
/// <summary>Raises the FriendOnline event</summary>
/// <param name="e">A FriendInfoEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendOnline(FriendInfoEventArgs e)
{
EventHandler<FriendInfoEventArgs> handler = m_FriendOnline;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendOnlineLock = new object();
/// <summary>Raised when the simulator sends notification one of the members in our friends list comes online</summary>
public event EventHandler<FriendInfoEventArgs> FriendOnline
{
add { lock (m_FriendOnlineLock) { m_FriendOnline += value; } }
remove { lock (m_FriendOnlineLock) { m_FriendOnline -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendInfoEventArgs> m_FriendOffline;
/// <summary>Raises the FriendOffline event</summary>
/// <param name="e">A FriendInfoEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendOffline(FriendInfoEventArgs e)
{
EventHandler<FriendInfoEventArgs> handler = m_FriendOffline;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendOfflineLock = new object();
/// <summary>Raised when the simulator sends notification one of the members in our friends list goes offline</summary>
public event EventHandler<FriendInfoEventArgs> FriendOffline
{
add { lock (m_FriendOfflineLock) { m_FriendOffline += value; } }
remove { lock (m_FriendOfflineLock) { m_FriendOffline -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendInfoEventArgs> m_FriendRights;
/// <summary>Raises the FriendRightsUpdate event</summary>
/// <param name="e">A FriendInfoEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendRights(FriendInfoEventArgs e)
{
EventHandler<FriendInfoEventArgs> handler = m_FriendRights;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendRightsLock = new object();
/// <summary>Raised when the simulator sends notification one of the members in our friends list grants or revokes permissions</summary>
public event EventHandler<FriendInfoEventArgs> FriendRightsUpdate
{
add { lock (m_FriendRightsLock) { m_FriendRights += value; } }
remove { lock (m_FriendRightsLock) { m_FriendRights -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendNamesEventArgs> m_FriendNames;
/// <summary>Raises the FriendNames event</summary>
/// <param name="e">A FriendNamesEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendNames(FriendNamesEventArgs e)
{
EventHandler<FriendNamesEventArgs> handler = m_FriendNames;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendNamesLock = new object();
/// <summary>Raised when the simulator sends us the names on our friends list</summary>
public event EventHandler<FriendNamesEventArgs> FriendNames
{
add { lock (m_FriendNamesLock) { m_FriendNames += value; } }
remove { lock (m_FriendNamesLock) { m_FriendNames -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendshipOfferedEventArgs> m_FriendshipOffered;
/// <summary>Raises the FriendshipOffered event</summary>
/// <param name="e">A FriendshipOfferedEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendshipOffered(FriendshipOfferedEventArgs e)
{
EventHandler<FriendshipOfferedEventArgs> handler = m_FriendshipOffered;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendshipOfferedLock = new object();
/// <summary>Raised when the simulator sends notification another agent is offering us friendship</summary>
public event EventHandler<FriendshipOfferedEventArgs> FriendshipOffered
{
add { lock (m_FriendshipOfferedLock) { m_FriendshipOffered += value; } }
remove { lock (m_FriendshipOfferedLock) { m_FriendshipOffered -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendshipResponseEventArgs> m_FriendshipResponse;
/// <summary>Raises the FriendshipResponse event</summary>
/// <param name="e">A FriendshipResponseEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendshipResponse(FriendshipResponseEventArgs e)
{
EventHandler<FriendshipResponseEventArgs> handler = m_FriendshipResponse;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendshipResponseLock = new object();
/// <summary>Raised when a request we sent to friend another agent is accepted or declined</summary>
public event EventHandler<FriendshipResponseEventArgs> FriendshipResponse
{
add { lock (m_FriendshipResponseLock) { m_FriendshipResponse += value; } }
remove { lock (m_FriendshipResponseLock) { m_FriendshipResponse -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendshipTerminatedEventArgs> m_FriendshipTerminated;
/// <summary>Raises the FriendshipTerminated event</summary>
/// <param name="e">A FriendshipTerminatedEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendshipTerminated(FriendshipTerminatedEventArgs e)
{
EventHandler<FriendshipTerminatedEventArgs> handler = m_FriendshipTerminated;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendshipTerminatedLock = new object();
/// <summary>Raised when the simulator sends notification one of the members in our friends list has terminated
/// our friendship</summary>
public event EventHandler<FriendshipTerminatedEventArgs> FriendshipTerminated
{
add { lock (m_FriendshipTerminatedLock) { m_FriendshipTerminated += value; } }
remove { lock (m_FriendshipTerminatedLock) { m_FriendshipTerminated -= value; } }
}
/// <summary>The event subscribers. null if no subcribers</summary>
private EventHandler<FriendFoundReplyEventArgs> m_FriendFound;
/// <summary>Raises the FriendFoundReply event</summary>
/// <param name="e">A FriendFoundReplyEventArgs object containing the
/// data returned from the data server</param>
protected virtual void OnFriendFoundReply(FriendFoundReplyEventArgs e)
{
EventHandler<FriendFoundReplyEventArgs> handler = m_FriendFound;
if (handler != null)
handler(this, e);
}
/// <summary>Thread sync lock object</summary>
private readonly object m_FriendFoundLock = new object();
/// <summary>Raised when the simulator sends the location of a friend we have
/// requested map location info for</summary>
public event EventHandler<FriendFoundReplyEventArgs> FriendFoundReply
{
add { lock (m_FriendFoundLock) { m_FriendFound += value; } }
remove { lock (m_FriendFoundLock) { m_FriendFound -= value; } }
}
#endregion Delegates
#region Events
#endregion Events
private GridClient Client;
/// <summary>
/// A dictionary of key/value pairs containing known friends of this avatar.
///
/// The Key is the <seealso cref="UUID"/> of the friend, the value is a <seealso cref="FriendInfo"/>
/// object that contains detailed information including permissions you have and have given to the friend
/// </summary>
public InternalDictionary<UUID, FriendInfo> FriendList = new InternalDictionary<UUID, FriendInfo>();
/// <summary>
/// A Dictionary of key/value pairs containing current pending frienship offers.
///
/// The key is the <seealso cref="UUID"/> of the avatar making the request,
/// the value is the <seealso cref="UUID"/> of the request which is used to accept
/// or decline the friendship offer
/// </summary>
public InternalDictionary<UUID, UUID> FriendRequests = new InternalDictionary<UUID, UUID>();
/// <summary>
/// Internal constructor
/// </summary>
/// <param name="client">A reference to the GridClient Object</param>
internal FriendsManager(GridClient client)
{
Client = client;
Client.Network.LoginProgress += Network_OnConnect;
Client.Avatars.UUIDNameReply += new EventHandler<UUIDNameReplyEventArgs>(Avatars_OnAvatarNames);
Client.Self.IM += Self_IM;
Client.Network.RegisterCallback(PacketType.OnlineNotification, OnlineNotificationHandler);
Client.Network.RegisterCallback(PacketType.OfflineNotification, OfflineNotificationHandler);
Client.Network.RegisterCallback(PacketType.ChangeUserRights, ChangeUserRightsHandler);
Client.Network.RegisterCallback(PacketType.TerminateFriendship, TerminateFriendshipHandler);
Client.Network.RegisterCallback(PacketType.FindAgent, OnFindAgentReplyHandler);
Client.Network.RegisterLoginResponseCallback(new NetworkManager.LoginResponseCallback(Network_OnLoginResponse),
new string[] { "buddy-list" });
}
#region Public Methods
/// <summary>
/// Accept a friendship request
/// </summary>
/// <param name="fromAgentID">agentID of avatatar to form friendship with</param>
/// <param name="imSessionID">imSessionID of the friendship request message</param>
public void AcceptFriendship(UUID fromAgentID, UUID imSessionID)
{
UUID callingCardFolder = Client.Inventory.FindFolderForType(AssetType.CallingCard);
AcceptFriendshipPacket request = new AcceptFriendshipPacket();
request.AgentData.AgentID = Client.Self.AgentID;
request.AgentData.SessionID = Client.Self.SessionID;
request.TransactionBlock.TransactionID = imSessionID;
request.FolderData = new AcceptFriendshipPacket.FolderDataBlock[1];
request.FolderData[0] = new AcceptFriendshipPacket.FolderDataBlock();
request.FolderData[0].FolderID = callingCardFolder;
Client.Network.SendPacket(request);
FriendInfo friend = new FriendInfo(fromAgentID, FriendRights.CanSeeOnline,
FriendRights.CanSeeOnline);
if (!FriendList.ContainsKey(fromAgentID))
FriendList.Add(friend.UUID, friend);
if (FriendRequests.ContainsKey(fromAgentID))
FriendRequests.Remove(fromAgentID);
Client.Avatars.RequestAvatarName(fromAgentID);
}
/// <summary>
/// Decline a friendship request
/// </summary>
/// <param name="fromAgentID"><seealso cref="UUID"/> of friend</param>
/// <param name="imSessionID">imSessionID of the friendship request message</param>
public void DeclineFriendship(UUID fromAgentID, UUID imSessionID)
{
DeclineFriendshipPacket request = new DeclineFriendshipPacket();
request.AgentData.AgentID = Client.Self.AgentID;
request.AgentData.SessionID = Client.Self.SessionID;
request.TransactionBlock.TransactionID = imSessionID;
Client.Network.SendPacket(request);
if (FriendRequests.ContainsKey(fromAgentID))
FriendRequests.Remove(fromAgentID);
}
/// <summary>
/// Overload: Offer friendship to an avatar.
/// </summary>
/// <param name="agentID">System ID of the avatar you are offering friendship to</param>
public void OfferFriendship(UUID agentID)
{
OfferFriendship(agentID, "Do ya wanna be my buddy?");
}
/// <summary>
/// Offer friendship to an avatar.
/// </summary>
/// <param name="agentID">System ID of the avatar you are offering friendship to</param>
/// <param name="message">A message to send with the request</param>
public void OfferFriendship(UUID agentID, string message)
{
Client.Self.InstantMessage(Client.Self.Name,
agentID,
message,
UUID.Random(),
InstantMessageDialog.FriendshipOffered,
InstantMessageOnline.Offline,
Client.Self.SimPosition,
Client.Network.CurrentSim.ID,
null);
}
/// <summary>
/// Terminate a friendship with an avatar
/// </summary>
/// <param name="agentID">System ID of the avatar you are terminating the friendship with</param>
public void TerminateFriendship(UUID agentID)
{
if (FriendList.ContainsKey(agentID))
{
TerminateFriendshipPacket request = new TerminateFriendshipPacket();
request.AgentData.AgentID = Client.Self.AgentID;
request.AgentData.SessionID = Client.Self.SessionID;
request.ExBlock.OtherID = agentID;
Client.Network.SendPacket(request);
if (FriendList.ContainsKey(agentID))
FriendList.Remove(agentID);
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
private void TerminateFriendshipHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
TerminateFriendshipPacket itsOver = (TerminateFriendshipPacket)packet;
string name = String.Empty;
if (FriendList.ContainsKey(itsOver.ExBlock.OtherID))
{
name = FriendList[itsOver.ExBlock.OtherID].Name;
FriendList.Remove(itsOver.ExBlock.OtherID);
}
if (m_FriendshipTerminated != null)
{
OnFriendshipTerminated(new FriendshipTerminatedEventArgs(itsOver.ExBlock.OtherID, name));
}
}
/// <summary>
/// Change the rights of a friend avatar.
/// </summary>
/// <param name="friendID">the <seealso cref="UUID"/> of the friend</param>
/// <param name="rights">the new rights to give the friend</param>
/// <remarks>This method will implicitly set the rights to those passed in the rights parameter.</remarks>
public void GrantRights(UUID friendID, FriendRights rights)
{
GrantUserRightsPacket request = new GrantUserRightsPacket();
request.AgentData.AgentID = Client.Self.AgentID;
request.AgentData.SessionID = Client.Self.SessionID;
request.Rights = new GrantUserRightsPacket.RightsBlock[1];
request.Rights[0] = new GrantUserRightsPacket.RightsBlock();
request.Rights[0].AgentRelated = friendID;
request.Rights[0].RelatedRights = (int)rights;
Client.Network.SendPacket(request);
}
/// <summary>
/// Use to map a friends location on the grid.
/// </summary>
/// <param name="friendID">Friends UUID to find</param>
/// <remarks><seealso cref="E:OnFriendFound"/></remarks>
public void MapFriend(UUID friendID)
{
FindAgentPacket stalk = new FindAgentPacket();
stalk.AgentBlock.Hunter = Client.Self.AgentID;
stalk.AgentBlock.Prey = friendID;
stalk.AgentBlock.SpaceIP = 0; // Will be filled in by the simulator
stalk.LocationBlock = new FindAgentPacket.LocationBlockBlock[1];
stalk.LocationBlock[0] = new FindAgentPacket.LocationBlockBlock();
stalk.LocationBlock[0].GlobalX = 0.0; // Filled in by the simulator
stalk.LocationBlock[0].GlobalY = 0.0;
Client.Network.SendPacket(stalk);
}
/// <summary>
/// Use to track a friends movement on the grid
/// </summary>
/// <param name="friendID">Friends Key</param>
public void TrackFriend(UUID friendID)
{
TrackAgentPacket stalk = new TrackAgentPacket();
stalk.AgentData.AgentID = Client.Self.AgentID;
stalk.AgentData.SessionID = Client.Self.SessionID;
stalk.TargetData.PreyID = friendID;
Client.Network.SendPacket(stalk);
}
/// <summary>
/// Ask for a notification of friend's online status
/// </summary>
/// <param name="friendID">Friend's UUID</param>
public void RequestOnlineNotification(UUID friendID)
{
GenericMessagePacket gmp = new GenericMessagePacket();
gmp.AgentData.AgentID = Client.Self.AgentID;
gmp.AgentData.SessionID = Client.Self.SessionID;
gmp.AgentData.TransactionID = UUID.Zero;
gmp.MethodData.Method = Utils.StringToBytes("requestonlinenotification");
gmp.MethodData.Invoice = UUID.Zero;
gmp.ParamList = new GenericMessagePacket.ParamListBlock[1];
gmp.ParamList[0] = new GenericMessagePacket.ParamListBlock();
gmp.ParamList[0].Parameter = Utils.StringToBytes(friendID.ToString());
Client.Network.SendPacket(gmp);
}
#endregion
#region Internal events
private void Network_OnConnect(object sender, LoginProgressEventArgs e)
{
if (e.Status != LoginStatus.Success)
{
return;
}
List<UUID> names = new List<UUID>();
if (FriendList.Count > 0)
{
FriendList.ForEach(
delegate(KeyValuePair<UUID, FriendInfo> kvp)
{
if (String.IsNullOrEmpty(kvp.Value.Name))
names.Add(kvp.Key);
}
);
Client.Avatars.RequestAvatarNames(names);
}
}
/// <summary>
/// This handles the asynchronous response of a RequestAvatarNames call.
/// </summary>
/// <param name="sender"></param>
/// <param name="e">names cooresponding to the the list of IDs sent the the RequestAvatarNames call.</param>
private void Avatars_OnAvatarNames(object sender, UUIDNameReplyEventArgs e)
{
Dictionary<UUID, string> newNames = new Dictionary<UUID, string>();
foreach (KeyValuePair<UUID, string> kvp in e.Names)
{
FriendInfo friend;
lock (FriendList.Dictionary)
{
if (FriendList.TryGetValue(kvp.Key, out friend))
{
if (friend.Name == null)
newNames.Add(kvp.Key, e.Names[kvp.Key]);
friend.Name = e.Names[kvp.Key];
FriendList[kvp.Key] = friend;
}
}
}
if (newNames.Count > 0 && m_FriendNames != null)
{
OnFriendNames(new FriendNamesEventArgs(newNames));
}
}
#endregion
#region Packet Handlers
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void OnlineNotificationHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
if (packet.Type == PacketType.OnlineNotification)
{
OnlineNotificationPacket notification = ((OnlineNotificationPacket)packet);
foreach (OnlineNotificationPacket.AgentBlockBlock block in notification.AgentBlock)
{
FriendInfo friend;
lock (FriendList.Dictionary)
{
if (!FriendList.ContainsKey(block.AgentID))
{
friend = new FriendInfo(block.AgentID, FriendRights.CanSeeOnline,
FriendRights.CanSeeOnline);
FriendList.Add(block.AgentID, friend);
}
else
{
friend = FriendList[block.AgentID];
}
}
bool doNotify = !friend.IsOnline;
friend.IsOnline = true;
if (m_FriendOnline != null && doNotify)
{
OnFriendOnline(new FriendInfoEventArgs(friend));
}
}
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
protected void OfflineNotificationHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
if (packet.Type == PacketType.OfflineNotification)
{
OfflineNotificationPacket notification = (OfflineNotificationPacket)packet;
foreach (OfflineNotificationPacket.AgentBlockBlock block in notification.AgentBlock)
{
FriendInfo friend = new FriendInfo(block.AgentID, FriendRights.CanSeeOnline, FriendRights.CanSeeOnline);
lock (FriendList.Dictionary)
{
if (!FriendList.Dictionary.ContainsKey(block.AgentID))
FriendList.Dictionary[block.AgentID] = friend;
friend = FriendList.Dictionary[block.AgentID];
}
friend.IsOnline = false;
if (m_FriendOffline != null)
{
OnFriendOffline(new FriendInfoEventArgs(friend));
}
}
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
private void ChangeUserRightsHandler(object sender, PacketReceivedEventArgs e)
{
Packet packet = e.Packet;
if (packet.Type == PacketType.ChangeUserRights)
{
FriendInfo friend;
ChangeUserRightsPacket rights = (ChangeUserRightsPacket)packet;
foreach (ChangeUserRightsPacket.RightsBlock block in rights.Rights)
{
FriendRights newRights = (FriendRights)block.RelatedRights;
if (FriendList.TryGetValue(block.AgentRelated, out friend))
{
friend.TheirFriendRights = newRights;
if (m_FriendRights != null)
{
OnFriendRights(new FriendInfoEventArgs(friend));
}
}
else if (block.AgentRelated == Client.Self.AgentID)
{
if (FriendList.TryGetValue(rights.AgentData.AgentID, out friend))
{
friend.MyFriendRights = newRights;
if (m_FriendRights != null)
{
OnFriendRights(new FriendInfoEventArgs(friend));
}
}
}
}
}
}
/// <summary>Process an incoming packet and raise the appropriate events</summary>
/// <param name="sender">The sender</param>
/// <param name="e">The EventArgs object containing the packet data</param>
public void OnFindAgentReplyHandler(object sender, PacketReceivedEventArgs e)
{
if (m_FriendFound != null)
{
Packet packet = e.Packet;
FindAgentPacket reply = (FindAgentPacket)packet;
float x, y;
UUID prey = reply.AgentBlock.Prey;
ulong regionHandle = Helpers.GlobalPosToRegionHandle((float)reply.LocationBlock[0].GlobalX,
(float)reply.LocationBlock[0].GlobalY, out x, out y);
Vector3 xyz = new Vector3(x, y, 0f);
OnFriendFoundReply(new FriendFoundReplyEventArgs(prey, regionHandle, xyz));
}
}
#endregion
private void Self_IM(object sender, InstantMessageEventArgs e)
{
if (e.IM.Dialog == InstantMessageDialog.FriendshipOffered)
{
if (m_FriendshipOffered != null)
{
if (FriendRequests.ContainsKey(e.IM.FromAgentID))
FriendRequests[e.IM.FromAgentID] = e.IM.IMSessionID;
else
FriendRequests.Add(e.IM.FromAgentID, e.IM.IMSessionID);
OnFriendshipOffered(new FriendshipOfferedEventArgs(e.IM.FromAgentID, e.IM.FromAgentName, e.IM.IMSessionID));
}
}
else if (e.IM.Dialog == InstantMessageDialog.FriendshipAccepted)
{
FriendInfo friend = new FriendInfo(e.IM.FromAgentID, FriendRights.CanSeeOnline,
FriendRights.CanSeeOnline);
friend.Name = e.IM.FromAgentName;
lock (FriendList.Dictionary) FriendList[friend.UUID] = friend;
if (m_FriendshipResponse != null)
{
OnFriendshipResponse(new FriendshipResponseEventArgs(e.IM.FromAgentID, e.IM.FromAgentName, true));
}
RequestOnlineNotification(e.IM.FromAgentID);
}
else if (e.IM.Dialog == InstantMessageDialog.FriendshipDeclined)
{
if (m_FriendshipResponse != null)
{
OnFriendshipResponse(new FriendshipResponseEventArgs(e.IM.FromAgentID, e.IM.FromAgentName, false));
}
}
}
/// <summary>
/// Populate FriendList <seealso cref="InternalDictionary"/> with data from the login reply
/// </summary>
/// <param name="loginSuccess">true if login was successful</param>
/// <param name="redirect">true if login request is requiring a redirect</param>
/// <param name="message">A string containing the response to the login request</param>
/// <param name="reason">A string containing the reason for the request</param>
/// <param name="replyData">A <seealso cref="LoginResponseData"/> object containing the decoded
/// reply from the login server</param>
private void Network_OnLoginResponse(bool loginSuccess, bool redirect, string message, string reason,
LoginResponseData replyData)
{
int uuidLength = UUID.Zero.ToString().Length;
if (loginSuccess && replyData.BuddyList != null)
{
foreach (BuddyListEntry buddy in replyData.BuddyList)
{
UUID bubid;
string id = buddy.buddy_id.Length > uuidLength ? buddy.buddy_id.Substring(0, uuidLength) : buddy.buddy_id;
if (UUID.TryParse(id, out bubid))
{
lock (FriendList.Dictionary)
{
if (!FriendList.ContainsKey(bubid))
{
FriendList[bubid] = new FriendInfo(bubid,
(FriendRights)buddy.buddy_rights_given,
(FriendRights)buddy.buddy_rights_has);
}
}
}
}
}
}
}
#region EventArgs
/// <summary>Contains information on a member of our friends list</summary>
public class FriendInfoEventArgs : EventArgs
{
private readonly FriendInfo m_Friend;
/// <summary>Get the FriendInfo</summary>
public FriendInfo Friend { get { return m_Friend; } }
/// <summary>
/// Construct a new instance of the FriendInfoEventArgs class
/// </summary>
/// <param name="friend">The FriendInfo</param>
public FriendInfoEventArgs(FriendInfo friend)
{
this.m_Friend = friend;
}
}
/// <summary>Contains Friend Names</summary>
public class FriendNamesEventArgs : EventArgs
{
private readonly Dictionary<UUID, string> m_Names;
/// <summary>A dictionary where the Key is the ID of the Agent,
/// and the Value is a string containing their name</summary>
public Dictionary<UUID, string> Names { get { return m_Names; } }
/// <summary>
/// Construct a new instance of the FriendNamesEventArgs class
/// </summary>
/// <param name="names">A dictionary where the Key is the ID of the Agent,
/// and the Value is a string containing their name</param>
public FriendNamesEventArgs(Dictionary<UUID, string> names)
{
this.m_Names = names;
}
}
/// <summary>Sent when another agent requests a friendship with our agent</summary>
public class FriendshipOfferedEventArgs : EventArgs
{
private readonly UUID m_AgentID;
private readonly string m_AgentName;
private readonly UUID m_SessionID;
/// <summary>Get the ID of the agent requesting friendship</summary>
public UUID AgentID { get { return m_AgentID; } }
/// <summary>Get the name of the agent requesting friendship</summary>
public string AgentName { get { return m_AgentName; } }
/// <summary>Get the ID of the session, used in accepting or declining the
/// friendship offer</summary>
public UUID SessionID { get { return m_SessionID; } }
/// <summary>
/// Construct a new instance of the FriendshipOfferedEventArgs class
/// </summary>
/// <param name="agentID">The ID of the agent requesting friendship</param>
/// <param name="agentName">The name of the agent requesting friendship</param>
/// <param name="imSessionID">The ID of the session, used in accepting or declining the
/// friendship offer</param>
public FriendshipOfferedEventArgs(UUID agentID, string agentName, UUID imSessionID)
{
this.m_AgentID = agentID;
this.m_AgentName = agentName;
this.m_SessionID = imSessionID;
}
}
/// <summary>A response containing the results of our request to form a friendship with another agent</summary>
public class FriendshipResponseEventArgs : EventArgs
{
private readonly UUID m_AgentID;
private readonly string m_AgentName;
private readonly bool m_Accepted;
/// <summary>Get the ID of the agent we requested a friendship with</summary>
public UUID AgentID { get { return m_AgentID; } }
/// <summary>Get the name of the agent we requested a friendship with</summary>
public string AgentName { get { return m_AgentName; } }
/// <summary>true if the agent accepted our friendship offer</summary>
public bool Accepted { get { return m_Accepted; } }
/// <summary>
/// Construct a new instance of the FriendShipResponseEventArgs class
/// </summary>
/// <param name="agentID">The ID of the agent we requested a friendship with</param>
/// <param name="agentName">The name of the agent we requested a friendship with</param>
/// <param name="accepted">true if the agent accepted our friendship offer</param>
public FriendshipResponseEventArgs(UUID agentID, string agentName, bool accepted)
{
this.m_AgentID = agentID;
this.m_AgentName = agentName;
this.m_Accepted = accepted;
}
}
/// <summary>Contains data sent when a friend terminates a friendship with us</summary>
public class FriendshipTerminatedEventArgs : EventArgs
{
private readonly UUID m_AgentID;
private readonly string m_AgentName;
/// <summary>Get the ID of the agent that terminated the friendship with us</summary>
public UUID AgentID { get { return m_AgentID; } }
/// <summary>Get the name of the agent that terminated the friendship with us</summary>
public string AgentName { get { return m_AgentName; } }
/// <summary>
/// Construct a new instance of the FrindshipTerminatedEventArgs class
/// </summary>
/// <param name="agentID">The ID of the friend who terminated the friendship with us</param>
/// <param name="agentName">The name of the friend who terminated the friendship with us</param>
public FriendshipTerminatedEventArgs(UUID agentID, string agentName)
{
this.m_AgentID = agentID;
this.m_AgentName = agentName;
}
}
/// <summary>
/// Data sent in response to a <see cref="FindFriend"/> request which contains the information to allow us to map the friends location
/// </summary>
public class FriendFoundReplyEventArgs : EventArgs
{
private readonly UUID m_AgentID;
private readonly ulong m_RegionHandle;
private readonly Vector3 m_Location;
/// <summary>Get the ID of the agent we have received location information for</summary>
public UUID AgentID { get { return m_AgentID; } }
/// <summary>Get the region handle where our mapped friend is located</summary>
public ulong RegionHandle { get { return m_RegionHandle; } }
/// <summary>Get the simulator local position where our friend is located</summary>
public Vector3 Location { get { return m_Location; } }
/// <summary>
/// Construct a new instance of the FriendFoundReplyEventArgs class
/// </summary>
/// <param name="agentID">The ID of the agent we have requested location information for</param>
/// <param name="regionHandle">The region handle where our friend is located</param>
/// <param name="location">The simulator local position our friend is located</param>
public FriendFoundReplyEventArgs(UUID agentID, ulong regionHandle, Vector3 location)
{
this.m_AgentID = agentID;
this.m_RegionHandle = regionHandle;
this.m_Location = location;
}
}
#endregion
}
| 43.253482 | 145 | 0.585222 | [
"BSD-3-Clause"
] | benanhalt/libopenmetaverse | OpenMetaverse/FriendsManager.cs | 46,584 | 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
namespace DotNetNuke.Web.Razor.Helpers
{
using System;
using DotNetNuke.Abstractions;
using DotNetNuke.Common;
using DotNetNuke.UI.Modules;
using Microsoft.Extensions.DependencyInjection;
[Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")]
public class UrlHelper
{
private readonly ModuleInstanceContext _context;
[Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")]
public UrlHelper(ModuleInstanceContext context)
{
this._context = context;
this.NavigationManager = Globals.DependencyProvider.GetRequiredService<INavigationManager>();
}
protected INavigationManager NavigationManager { get; }
[Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")]
public string NavigateToControl()
{
return this.NavigationManager.NavigateURL(this._context.TabId);
}
[Obsolete("Deprecated in 9.3.2, will be removed in 11.0.0, use Razor Pages instead")]
public string NavigateToControl(string controlKey)
{
return this.NavigationManager.NavigateURL(this._context.TabId, controlKey, "mid=" + this._context.ModuleId);
}
}
}
| 37.85 | 120 | 0.68428 | [
"MIT"
] | Acidburn0zzz/Dnn.Platform | DNN Platform/DotNetNuke.Web.Razor/Helpers/UrlHelper.cs | 1,516 | C# |
using POETradeHelper.Common.UI;
namespace POETradeHelper.ItemSearch.Views
{
public interface IItemSearchResultOverlayView : IHideable
{
bool IsVisible { get; set; }
}
} | 21.111111 | 61 | 0.715789 | [
"Apache-2.0",
"MIT"
] | alueck/POE-TradeHelper | Source/POETradeHelper.ItemSearch/Views/IItemSearchResultOverlayView.cs | 192 | C# |
using System;
using System.Collections.Generic;
using System.Collections.Concurrent;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using System.Threading;
namespace FreeSql
{
public abstract partial class DbContext : IDisposable
{
internal DbContextScopedFreeSql _ormScoped;
internal IFreeSql OrmOriginal => _ormScoped?._originalFsql ?? throw new ArgumentNullException("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql");
public IFreeSql Orm => _ormScoped ?? throw new ArgumentNullException("请在 OnConfiguring 或 AddFreeDbContext 中配置 UseFreeSql");
#region Property UnitOfWork
internal bool _isUseUnitOfWork = true; //是否创建工作单元事务
IUnitOfWork _uowPriv;
public IUnitOfWork UnitOfWork
{
set => _uowPriv = value;
get
{
if (_uowPriv != null) return _uowPriv;
if (_isUseUnitOfWork == false) return null;
return _uowPriv = new UnitOfWork(OrmOriginal);
}
}
#endregion
#region Property Options
internal DbContextOptions _optionsPriv;
public DbContextOptions Options
{
set => _optionsPriv = value;
get
{
if (_optionsPriv == null)
{
_optionsPriv = new DbContextOptions();
if (FreeSqlDbContextExtensions._dicSetDbContextOptions.TryGetValue(OrmOriginal.Ado.Identifier, out var opt))
{
_optionsPriv.EnableAddOrUpdateNavigateList = opt.EnableAddOrUpdateNavigateList;
_optionsPriv.OnEntityChange = opt.OnEntityChange;
}
}
return _optionsPriv;
}
}
internal void EmitOnEntityChange(List<EntityChangeReport.ChangeInfo> report)
{
var oec = UnitOfWork?.EntityChangeReport?.OnChange ?? Options.OnEntityChange;
if (oec == null || report == null || report.Any() == false) return;
oec(report);
}
#endregion
protected DbContext() : this(null, null) { }
protected DbContext(IFreeSql fsql, DbContextOptions options)
{
_ormScoped = DbContextScopedFreeSql.Create(fsql, () => this, () => UnitOfWork);
_optionsPriv = options;
if (_ormScoped == null)
{
var builder = new DbContextOptionsBuilder();
OnConfiguring(builder);
_ormScoped = DbContextScopedFreeSql.Create(builder._fsql, () => this, () => UnitOfWork);
_optionsPriv = builder._options;
}
if (_ormScoped != null) InitPropSets();
}
protected virtual void OnConfiguring(DbContextOptionsBuilder builder) { }
#region Set
static ConcurrentDictionary<Type, PropertyInfo[]> _dicGetDbSetProps = new ConcurrentDictionary<Type, PropertyInfo[]>();
internal void InitPropSets()
{
var props = _dicGetDbSetProps.GetOrAdd(this.GetType(), tp =>
tp.GetProperties(BindingFlags.NonPublic | BindingFlags.Instance | BindingFlags.Public)
.Where(a => a.PropertyType.IsGenericType &&
a.PropertyType == typeof(DbSet<>).MakeGenericType(a.PropertyType.GetGenericArguments()[0])).ToArray());
foreach (var prop in props)
{
var set = this.Set(prop.PropertyType.GetGenericArguments()[0]);
prop.SetValue(this, set, null);
AllSets.Add(prop.Name, set);
}
}
protected List<IDbSet> _listSet = new List<IDbSet>();
protected Dictionary<Type, IDbSet> _dicSet = new Dictionary<Type, IDbSet>();
internal Dictionary<Type, IDbSet> InternalDicSet => _dicSet;
public DbSet<TEntity> Set<TEntity>() where TEntity : class => this.Set(typeof(TEntity)) as DbSet<TEntity>;
public virtual IDbSet Set(Type entityType)
{
if (_dicSet.ContainsKey(entityType)) return _dicSet[entityType];
var sd = Activator.CreateInstance(typeof(DbContextDbSet<>).MakeGenericType(entityType), this) as IDbSet;
_listSet.Add(sd);
if (entityType != typeof(object)) _dicSet.Add(entityType, sd);
return sd;
}
protected Dictionary<string, IDbSet> AllSets { get; } = new Dictionary<string, IDbSet>();
#endregion
#region DbSet 快速代理
void CheckEntityTypeOrThrow(Type entityType)
{
if (OrmOriginal.CodeFirst.GetTableByEntity(entityType) == null)
throw new ArgumentException($"参数 data 类型错误 {entityType.FullName} ");
}
/// <summary>
/// 添加
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void Add<TEntity>(TEntity data) where TEntity : class
{
CheckEntityTypeOrThrow(typeof(TEntity));
this.Set<TEntity>().Add(data);
}
public void AddRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AddRange(data);
/// <summary>
/// 更新
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void Update<TEntity>(TEntity data) where TEntity : class
{
CheckEntityTypeOrThrow(typeof(TEntity));
this.Set<TEntity>().Update(data);
}
public void UpdateRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().UpdateRange(data);
/// <summary>
/// 删除
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void Remove<TEntity>(TEntity data) where TEntity : class
{
CheckEntityTypeOrThrow(typeof(TEntity));
this.Set<TEntity>().Remove(data);
}
public void RemoveRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().RemoveRange(data);
/// <summary>
/// 添加或更新
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void AddOrUpdate<TEntity>(TEntity data) where TEntity : class
{
CheckEntityTypeOrThrow(typeof(TEntity));
this.Set<TEntity>().AddOrUpdate(data);
}
/// <summary>
/// 保存实体的指定 ManyToMany/OneToMany 导航属性(完整对比)<para></para>
/// 场景:在关闭级联保存功能之后,手工使用本方法<para></para>
/// 例子:保存商品的 OneToMany 集合属性,SaveMany(goods, "Skus")<para></para>
/// 当 goods.Skus 为空(非null)时,会删除表中已存在的所有数据<para></para>
/// 当 goods.Skus 不为空(非null)时,添加/更新后,删除表中不存在 Skus 集合属性的所有记录
/// </summary>
/// <param name="data">实体对象</param>
/// <param name="propertyName">属性名</param>
public void SaveMany<TEntity>(TEntity data, string propertyName) where TEntity : class
{
CheckEntityTypeOrThrow(typeof(TEntity));
this.Set<TEntity>().SaveMany(data, propertyName);
}
/// <summary>
/// 附加实体,可用于不查询就更新或删除
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public void Attach<TEntity>(TEntity data) where TEntity : class
{
CheckEntityTypeOrThrow(typeof(TEntity));
this.Set<TEntity>().Attach(data);
}
public void AttachRange<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AttachRange(data);
/// <summary>
/// 附加实体,并且只附加主键值,可用于不更新属性值为null或默认值的字段
/// </summary>
/// <typeparam name="TEntity"></typeparam>
/// <param name="data"></param>
public DbContext AttachOnlyPrimary<TEntity>(TEntity data) where TEntity : class
{
CheckEntityTypeOrThrow(typeof(TEntity));
this.Set<TEntity>().AttachOnlyPrimary(data);
return this;
}
#if net40
#else
public Task AddAsync<TEntity>(TEntity data) where TEntity : class
{
CheckEntityTypeOrThrow(typeof(TEntity));
return this.Set<TEntity>().AddAsync(data);
}
public Task AddRangeAsync<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().AddRangeAsync(data);
public Task UpdateAsync<TEntity>(TEntity data) where TEntity : class
{
CheckEntityTypeOrThrow(typeof(TEntity));
return this.Set<TEntity>().UpdateAsync(data);
}
public Task UpdateRangeAsync<TEntity>(IEnumerable<TEntity> data) where TEntity : class => this.Set<TEntity>().UpdateRangeAsync(data);
public Task AddOrUpdateAsync<TEntity>(TEntity data) where TEntity : class
{
CheckEntityTypeOrThrow(typeof(TEntity));
return this.Set<TEntity>().AddOrUpdateAsync(data);
}
public Task SaveManyAsync<TEntity>(TEntity data, string propertyName) where TEntity : class
{
CheckEntityTypeOrThrow(typeof(TEntity));
return this.Set<TEntity>().SaveManyAsync(data, propertyName);
}
#endif
#endregion
#region Queue Action
public class EntityChangeReport
{
public class ChangeInfo
{
public object Object { get; set; }
public EntityChangeType Type { get; set; }
}
/// <summary>
/// 实体变化记录
/// </summary>
public List<ChangeInfo> Report { get; } = new List<ChangeInfo>();
/// <summary>
/// 实体变化事件
/// </summary>
public Action<List<ChangeInfo>> OnChange { get; set; }
}
internal List<EntityChangeReport.ChangeInfo> _entityChangeReport = new List<EntityChangeReport.ChangeInfo>();
public enum EntityChangeType { Insert, Update, Delete, SqlRaw }
internal class ExecCommandInfo
{
public EntityChangeType changeType { get; set; }
public IDbSet dbSet { get; set; }
public Type stateType { get; set; }
public Type entityType { get; set; }
public object state { get; set; }
}
Queue<ExecCommandInfo> _actions = new Queue<ExecCommandInfo>();
internal int _affrows = 0;
internal void EnqueueAction(EntityChangeType changeType, IDbSet dbSet, Type stateType, Type entityType, object state) =>
_actions.Enqueue(new ExecCommandInfo { changeType = changeType, dbSet = dbSet, stateType = stateType, entityType = entityType, state = state });
#endregion
~DbContext() => this.Dispose();
int _disposeCounter;
public void Dispose()
{
if (Interlocked.Increment(ref _disposeCounter) != 1) return;
try
{
_actions.Clear();
foreach (var set in _listSet)
try
{
set.Dispose();
}
catch { }
_listSet.Clear();
_dicSet.Clear();
AllSets.Clear();
if (_isUseUnitOfWork)
UnitOfWork?.Dispose();
}
finally
{
GC.SuppressFinalize(this);
}
}
}
}
| 39.619863 | 156 | 0.577146 | [
"MIT"
] | jiargcn/FreeSql | FreeSql.DbContext/DbContext/DbContext.cs | 11,991 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Luval.DataStore.DataAnnotations
{
/// <summary>
/// Specificies the name of a column
/// </summary>
public abstract class NameBaseAttribute : Attribute
{
/// <summary>
/// Creates a new instance of <see cref="NameBaseAttribute"/>
/// </summary>
/// <param name="name">The column name</param>
public NameBaseAttribute(string name)
{
Name = name;
}
/// <summary>
/// Gets or sets the column name
/// </summary>
public string Name { get; set; }
}
}
| 24.103448 | 69 | 0.585122 | [
"MIT"
] | marinoscar/Luval-DataStore | src/Luval.DataStore/DataAnnotations/NameBaseAttributte.cs | 701 | C# |
using System.ComponentModel.DataAnnotations;
namespace Sikiro.WebApi.Customer.Models.User.Request
{
/// <summary>
/// 修改密码
/// </summary>
public class UserUpdatePwdRequest
{
/// <summary>
/// 用户ID
/// </summary>
[Required(ErrorMessage = "请输入用户ID")]
public string UserId { get; set; }
/// <summary>
/// 登录密码(旧)
/// </summary>
[Required(ErrorMessage = "请输入登录密码")]
public string OldPassword { get; set; }
/// <summary>
/// 新登录密码
/// </summary>
[Required(ErrorMessage = "请输入新登录密码")]
public string NewPassword { get; set; }
}
}
| 23.137931 | 52 | 0.529061 | [
"MIT"
] | SkyChenSky/Sikiro | samples/客户系统解决方案-新分层/Sikiro.WebApi.Customer/Models/User/Request/UserUpdatePwdRequest.cs | 749 | C# |
using CoAPnet.Protocol;
using CoAPnet.Protocol.Options;
using System;
using System.Collections.Generic;
namespace CoAPnet.Client
{
public sealed class CoapRequestToMessageConverter
{
readonly CoapMessageOptionFactory _optionFactory = new CoapMessageOptionFactory();
public CoapMessage Convert(CoapRequest request)
{
if (request is null) throw new ArgumentNullException(nameof(request));
var message = new CoapMessage
{
Type = CoapMessageType.Confirmable,
Code = GetMessageCode(request.Method),
Options = new List<CoapMessageOption>(),
Payload = request.Payload
};
ApplyUriHost(request, message);
ApplyUriPort(request, message);
ApplyUriPath(request, message);
ApplyUriQuery(request, message);
return message;
}
void ApplyUriHost(CoapRequest request, CoapMessage message)
{
if (string.IsNullOrEmpty(request.Options.UriHost))
{
return;
}
message.Options.Add(_optionFactory.CreateUriHost(request.Options.UriHost));
}
void ApplyUriPort(CoapRequest request, CoapMessage message)
{
if (!request.Options.UriPort.HasValue)
{
return;
}
message.Options.Add(_optionFactory.CreateUriPort((uint)request.Options.UriPort.Value));
}
void ApplyUriPath(CoapRequest request, CoapMessage message)
{
if (string.IsNullOrEmpty(request.Options.UriPath))
{
return;
}
var paths = request.Options.UriPath.Split(new char[] { '/' }, StringSplitOptions.RemoveEmptyEntries);
foreach (var path in paths)
{
message.Options.Add(_optionFactory.CreateUriPath(path));
}
}
void ApplyUriQuery(CoapRequest request, CoapMessage message)
{
if (request.Options.UriQuery == null)
{
return;
}
foreach (var query in request.Options.UriQuery)
{
message.Options.Add(_optionFactory.CreateUriQuery(query));
}
}
static CoapMessageCode GetMessageCode(CoapRequestMethod method)
{
switch (method)
{
case CoapRequestMethod.Get: return CoapMessageCodes.Get;
case CoapRequestMethod.Post: return CoapMessageCodes.Post;
case CoapRequestMethod.Delete: return CoapMessageCodes.Delete;
case CoapRequestMethod.Put: return CoapMessageCodes.Put;
default: throw new NotSupportedException();
}
}
}
}
| 30.634409 | 113 | 0.576343 | [
"MIT"
] | vankooch/CoAPnet | Source/CoAPnet/Client/CoapRequestToMessageConverter.cs | 2,851 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.Diagnostics;
namespace Microsoft.AspNetCore.Razor.Language.Syntax
{
internal class SyntaxListBuilder
{
private ArrayElement<GreenNode>[] _nodes;
public int Count { get; private set; }
public SyntaxListBuilder(int size)
{
_nodes = new ArrayElement<GreenNode>[size];
}
public void Clear()
{
Count = 0;
}
public void Add(SyntaxNode item)
{
AddInternal(item.Green);
}
internal void AddInternal(GreenNode item)
{
if (item == null)
{
throw new ArgumentNullException();
}
if (_nodes == null || Count >= _nodes.Length)
{
Grow(Count == 0 ? 8 : _nodes.Length * 2);
}
_nodes[Count++].Value = item;
}
public void AddRange(SyntaxNode[] items)
{
AddRange(items, 0, items.Length);
}
public void AddRange(SyntaxNode[] items, int offset, int length)
{
if (_nodes == null || Count + length > _nodes.Length)
{
Grow(Count + length);
}
for (int i = offset, j = Count; i < offset + length; ++i, ++j)
{
_nodes[j].Value = items[i].Green;
}
var start = Count;
Count += length;
Validate(start, Count);
}
[Conditional("DEBUG")]
private void Validate(int start, int end)
{
for (var i = start; i < end; i++)
{
if (_nodes[i].Value == null)
{
throw new ArgumentException("Cannot add a null node.");
}
}
}
public void AddRange(SyntaxList<SyntaxNode> list)
{
AddRange(list, 0, list.Count);
}
public void AddRange(SyntaxList<SyntaxNode> list, int offset, int count)
{
if (_nodes == null || Count + count > _nodes.Length)
{
Grow(Count + count);
}
var dst = Count;
for (int i = offset, limit = offset + count; i < limit; i++)
{
_nodes[dst].Value = list.ItemInternal(i).Green;
dst++;
}
var start = Count;
Count += count;
Validate(start, Count);
}
public void AddRange<TNode>(SyntaxList<TNode> list) where TNode : SyntaxNode
{
AddRange(list, 0, list.Count);
}
public void AddRange<TNode>(SyntaxList<TNode> list, int offset, int count)
where TNode : SyntaxNode
{
AddRange(new SyntaxList<SyntaxNode>(list.Node), offset, count);
}
private void Grow(int size)
{
var tmp = new ArrayElement<GreenNode>[size];
Array.Copy(_nodes, tmp, _nodes.Length);
_nodes = tmp;
}
public bool Any(SyntaxKind kind)
{
for (var i = 0; i < Count; i++)
{
if (_nodes[i].Value.Kind == kind)
{
return true;
}
}
return false;
}
internal GreenNode ToListNode()
{
switch (Count)
{
case 0:
return null;
case 1:
return _nodes[0].Value;
case 2:
return InternalSyntax.SyntaxList.List(_nodes[0].Value, _nodes[1].Value);
case 3:
return InternalSyntax.SyntaxList.List(
_nodes[0].Value,
_nodes[1].Value,
_nodes[2].Value
);
default:
var tmp = new ArrayElement<GreenNode>[Count];
for (var i = 0; i < Count; i++)
{
tmp[i].Value = _nodes[i].Value;
}
return InternalSyntax.SyntaxList.List(tmp);
}
}
public static implicit operator SyntaxList<SyntaxNode>(SyntaxListBuilder builder)
{
if (builder == null)
{
return default(SyntaxList<SyntaxNode>);
}
return builder.ToList();
}
internal void RemoveLast()
{
Count -= 1;
_nodes[Count] = default(ArrayElement<GreenNode>);
}
}
}
| 27.005618 | 111 | 0.45517 | [
"Apache-2.0"
] | belav/aspnetcore | src/Razor/Microsoft.AspNetCore.Razor.Language/src/Syntax/SyntaxListBuilder.cs | 4,809 | C# |
//------------------------------------------------------------
// Game Framework v3.x
// Copyright © 2013-2018 Jiang Yin. All rights reserved.
// Homepage: http://gameframework.cn/
// Feedback: mailto:jiangyin@gameframework.cn
//------------------------------------------------------------
using GameFramework.Event;
namespace UnityGameFramework.Runtime
{
/// <summary>
/// Web 请求开始事件。
/// </summary>
public sealed class WebRequestStartEventArgs : GameEventArgs
{
/// <summary>
/// Web 请求开始事件编号。
/// </summary>
public static readonly int EventId = typeof(WebRequestStartEventArgs).GetHashCode();
/// <summary>
/// 获取 Web 请求开始事件编号。
/// </summary>
public override int Id
{
get
{
return EventId;
}
}
/// <summary>
/// 获取 Web 请求任务的序列编号。
/// </summary>
public int SerialId
{
get;
private set;
}
/// <summary>
/// 获取 Web 请求地址。
/// </summary>
public string WebRequestUri
{
get;
private set;
}
/// <summary>
/// 获取用户自定义数据。
/// </summary>
public object UserData
{
get;
private set;
}
/// <summary>
/// 清理 Web 请求开始事件。
/// </summary>
public override void Clear()
{
SerialId = default(int);
WebRequestUri = default(string);
UserData = default(object);
}
/// <summary>
/// 填充 Web 请求开始事件。
/// </summary>
/// <param name="e">内部事件。</param>
/// <returns>Web 请求开始事件。</returns>
public WebRequestStartEventArgs Fill(GameFramework.WebRequest.WebRequestStartEventArgs e)
{
WWWFormInfo wwwFormInfo = (WWWFormInfo)e.UserData;
SerialId = e.SerialId;
WebRequestUri = e.WebRequestUri;
UserData = wwwFormInfo.UserData;
return this;
}
}
}
| 24.418605 | 97 | 0.46381 | [
"MIT"
] | Data-XiaoYu/UnityWorld | FlappyBird/Assets/GameFramework/Scripts/Runtime/WebRequest/WebRequestStartEventArgs.cs | 2,275 | C# |
// The MIT License (MIT)
//
// Copyright (c) Andrew Armstrong/FacticiusVir 2018
//
// 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.
// This file was automatically generated and should not be edited directly.
namespace SharpVk
{
/// <summary>
/// Buffer and image sharing modes.
/// </summary>
public enum SharingMode
{
/// <summary>
/// Specifies that access to any range or image subresource of the
/// object will be exclusive to a single queue family at a time.
/// </summary>
Exclusive = 0,
/// <summary>
/// Specifies that concurrent access to any range or image subresource
/// of the object from multiple queue families is supported.
/// </summary>
Concurrent = 1,
}
}
| 40.444444 | 81 | 0.7 | [
"MIT"
] | sebastianulm/SharpVk | src/SharpVk/SharingMode.gen.cs | 1,820 | C# |
using Microsoft.VisualStudio.TestTools.UnitTesting;
using System;
using System.Collections.Generic;
using System.Text;
namespace Anf.Test
{
[TestClass]
public class ComicSourceContextTest
{
[TestMethod]
public void GivenNullValue_MustThrowException()
{
Assert.ThrowsException<ArgumentException>(() => new ComicSourceContext((string)null));
Assert.ThrowsException<ArgumentNullException>(() => new ComicSourceContext((Uri)null));
}
[TestMethod]
public void GivenValue_PropertyMustEquipGiven()
{
var uri = new Uri("http://www.bing.com/");
var ctx = new ComicSourceContext(uri);
Assert.AreEqual(uri, ctx.Uri);
Assert.AreEqual(uri.AbsoluteUri, ctx.Source);
ctx = new ComicSourceContext(uri.AbsoluteUri);
Assert.AreEqual(uri, ctx.Uri);
Assert.AreEqual(uri.AbsoluteUri, ctx.Source);
var str = "-no-uri-";
ctx = new ComicSourceContext(str);
Assert.AreEqual(str, ctx.Source);
}
}
}
| 33.30303 | 99 | 0.620564 | [
"BSD-3-Clause"
] | Cricle/Anf | test/Anf.Test/ComicSourceContextTest.cs | 1,101 | C# |
using System;
using System.Collections.Generic;
using Mono.Cecil.Cil;
using Telerik.JustDecompiler.Ast.Expressions;
namespace Telerik.JustDecompiler.Ast.Statements
{
public class LockStatement : BasePdbStatement
{
private BlockStatement body;
private readonly List<Instruction> mappedFinallyInstructions;
public LockStatement(Expression expression, BlockStatement body, IEnumerable<Instruction> finallyInstructions)
{
this.Expression = expression;
this.body = body;
this.mappedFinallyInstructions = new List<Instruction>();
if (finallyInstructions != null)
{
this.mappedFinallyInstructions.AddRange(finallyInstructions);
this.mappedFinallyInstructions.Sort((x, y) => x.Offset.CompareTo(y.Offset));
}
}
protected override IEnumerable<Instruction> GetOwnInstructions()
{
foreach (Instruction instruction in this.mappedFinallyInstructions)
{
yield return instruction;
}
}
public override IEnumerable<ICodeNode> Children
{
get
{
if (this.Expression != null)
{
yield return this.Expression;
}
if (this.body != null)
{
yield return this.body;
}
}
}
public override Statement Clone()
{
BlockStatement clonedBody = null;
if (body != null)
{
clonedBody = body.Clone() as BlockStatement;
}
LockStatement result = new LockStatement(Expression.Clone(), clonedBody, this.mappedFinallyInstructions);
CopyParentAndLabel(result);
return result;
}
public override Statement CloneStatementOnly()
{
BlockStatement clonedBody = body != null ? body.CloneStatementOnly() as BlockStatement : null;
LockStatement result = new LockStatement(Expression.CloneExpressionOnly(), clonedBody, null);
CopyParentAndLabel(result);
return result;
}
public Expression Expression { get; set; }
public BlockStatement Body
{
get { return body; }
set
{
this.body = value;
if(this.body != null)
{
this.body.Parent = this;
}
}
}
public override CodeNodeType CodeNodeType
{
get { return CodeNodeType.LockStatement; }
}
}
}
| 29.898876 | 118 | 0.558437 | [
"MIT"
] | nguyenthiennam1992/Decompiler | JustDecompileEngine-master/JustDecompileEngine-master/Cecil.Decompiler/Ast/Statements/LockStatement.cs | 2,663 | C# |
// c:\program files (x86)\windows kits\10\include\10.0.22000.0\shared\d3dkmthk.h(1889,9)
using System;
using System.Runtime.InteropServices;
namespace DirectN
{
[StructLayout(LayoutKind.Sequential)]
public partial struct _D3DKMT_ISBADDRIVERFORHWPROTECTIONDISABLED
{
public bool Disabled;
}
}
| 25.384615 | 90 | 0.715152 | [
"MIT"
] | Steph55/DirectN | DirectN/DirectN/Generated/_D3DKMT_ISBADDRIVERFORHWPROTECTIONDISABLED.cs | 332 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System.Collections.Generic;
using Microsoft.Framework.DependencyInjection.Tests.Fakes;
namespace Microsoft.Framework.DependencyInjection.ServiceLookup
{
public class TypeWithEnumerableConstructors
{
public TypeWithEnumerableConstructors(
IEnumerable<IFakeService> fakeServices)
{
}
public TypeWithEnumerableConstructors(
IEnumerable<IFakeService> fakeServices,
IEnumerable<IFactoryService> factoryServices)
{
}
}
}
| 29.913043 | 111 | 0.715116 | [
"Apache-2.0"
] | benaadams/DependencyInjection | test/Microsoft.Framework.DependencyInjection.Tests/ServiceLookup/Types/TypeWithEnumerableConstructors.cs | 690 | C# |
using System;
using System.Diagnostics.CodeAnalysis;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
using SpiderEye.Tools;
namespace SpiderEye.Bridge
{
internal class ApiMethod
{
public string Name { get; }
public Type? ParameterType { get; }
public Type ReturnType { get; }
public bool HasReturnValue { get; }
[MemberNotNullWhen(true, nameof(ParameterType))]
public bool HasParameter { get; }
public bool IsAsync { get; }
private readonly object instance;
private readonly MethodInfo info;
private readonly Func<object, object?>? getTaskResult;
public ApiMethod(object instance, MethodInfo info)
{
this.instance = instance ?? throw new ArgumentNullException(nameof(instance));
this.info = info ?? throw new ArgumentNullException(nameof(info));
Name = JsTools.NormalizeToJsName(info.Name);
ParameterType = info.GetParameters().FirstOrDefault()?.ParameterType;
HasParameter = ParameterType != null;
ReturnType = info.ReturnType;
if (ReturnType.IsGenericType && ReturnType.GetGenericTypeDefinition() == typeof(Task<>))
{
var prop = ReturnType.GetProperty("Result");
getTaskResult = (task) => prop!.GetValue(task, null);
ReturnType = ReturnType.GenericTypeArguments[0];
IsAsync = true;
}
else if (ReturnType == typeof(Task))
{
ReturnType = typeof(void);
IsAsync = true;
}
HasReturnValue = ReturnType != typeof(void);
}
public async Task<object?> InvokeAsync(object? parameter)
{
object? result;
if (HasParameter) { result = info.Invoke(instance, new object?[] { parameter }); }
else { result = info.Invoke(instance, null); }
if (!IsAsync) { return result; }
await (result as Task)!;
if (!HasReturnValue) { return null; }
else { return getTaskResult!(result); }
}
}
}
| 32.537313 | 100 | 0.586697 | [
"Apache-2.0"
] | JBildstein/SpiderEye | Source/SpiderEye.Core/Bridge/ApiMethod.cs | 2,182 | C# |
namespace IntegrationTests.Services.Ordering
{
using IntegrationTests.Services.Extensions;
using Microsoft.AspNetCore.TestHost;
using Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands;
using Newtonsoft.Json;
using System;
using System.Net.Http;
using System.Text;
using System.Threading.Tasks;
using Xunit;
using System.Collections;
using static Microsoft.eShopOnContainers.Services.Ordering.API.Application.Commands.CreateOrderCommand;
using System.Collections.Generic;
public class OrderingScenarios
: OrderingScenarioBase
{
[Fact]
public async Task Get_get_all_stored_orders_and_response_ok_status_code()
{
using (var server = CreateServer())
{
var response = await server.CreateClient()
.GetAsync(Get.Orders);
response.EnsureSuccessStatusCode();
}
}
[Fact]
public async Task AddNewOrder_add_new_order_and_response_ok_status_code()
{
using (var server = CreateServer())
{
var content = new StringContent(BuildOrder(), UTF8Encoding.UTF8, "application/json");
var response = await server.CreateIdempotentClient()
.PostAsync(Post.AddNewOrder, content);
response.EnsureSuccessStatusCode();
}
}
[Fact]
public async Task AddNewOrder_response_bad_request_if_card_expiration_is_invalid()
{
using (var server = CreateServer())
{
var content = new StringContent(BuildOrderWithInvalidExperationTime(), UTF8Encoding.UTF8, "application/json");
var response = await server.CreateIdempotentClient()
.PostAsync(Post.AddNewOrder, content);
Assert.True(response.StatusCode == System.Net.HttpStatusCode.BadRequest);
}
}
//public CreateOrderCommand(string city, string street, string state, string country, string zipcode,
// string cardNumber, string cardHolderName, DateTime cardExpiration,
// string cardSecurityNumber, int cardTypeId, int paymentId, int buyerId) : this()
string BuildOrder()
{
List<OrderItemDTO> orderItemsList = new List<OrderItemDTO>();
orderItemsList.Add(new OrderItemDTO()
{
ProductId = 1,
Discount = 10M,
UnitPrice = 10,
Units = 1,
ProductName = "Some name"
}
);
var order = new CreateOrderCommand(
orderItemsList,
cardExpiration: DateTime.UtcNow.AddYears(1),
cardNumber: "5145-555-5555",
cardHolderName: "Jhon Senna",
cardSecurityNumber: "232",
cardTypeId: 1,
city: "Redmon",
country: "USA",
state: "WA",
street: "One way",
zipcode: "zipcode",
paymentId: 1,
buyerId: 1
);
return JsonConvert.SerializeObject(order);
}
string BuildOrderWithInvalidExperationTime()
{
var order = new CreateOrderCommand(
null,
cardExpiration: DateTime.UtcNow.AddYears(-1),
cardNumber: "5145-555-5555",
cardHolderName: "Jhon Senna",
cardSecurityNumber: "232",
cardTypeId: 1,
city: "Redmon",
country: "USA",
state: "WA",
street: "One way",
zipcode: "zipcode",
buyerId: 1,
paymentId:1
);
return JsonConvert.SerializeObject(order);
}
}
}
| 36.791304 | 126 | 0.513827 | [
"MIT"
] | cheahengsoon/eShopOnContainers | test/Services/IntegrationTests/Services/Ordering/OrderingScenarios.cs | 4,233 | C# |
namespace OrionLib.QueryContext
{
public class RestrictedQueryContextRequestDto : QueryContextRequestDto
{
public QueryRestrictionDto Restriction { get; private set; }
public RestrictedQueryContextRequestDto(string type, QueryRestrictionScopeDto restrictionScope) : base(type)
{
Restriction = QueryRestrictionDto.WithOneRestrictionScope(restrictionScope);
}
}
}
| 32.307692 | 116 | 0.733333 | [
"MIT"
] | bt-skyrise/OrionLib | Source/OrionLib/QueryContext/RestrictedQueryContextRequestDto.cs | 422 | C# |
using System.Reflection;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("AWSSDK.CostExplorer")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Cost Explorer Service. The AWS Cost Explorer API gives customers programmatic access to AWS cost and usage information, allowing them to perform adhoc queries and build interactive cost management applications that leverage this dataset.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2020 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[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)]
// 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("3.3")]
[assembly: AssemblyFileVersion("3.3.109.39")] | 49.96875 | 321 | 0.759225 | [
"Apache-2.0"
] | danielmarbach/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/CostExplorer/Properties/AssemblyInfo.cs | 1,599 | C# |
using PointOfSaleUI.Business.Domain;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace PointOfSaleUI.Business.Services.Local
{
public class GetLoggedInUserRoleService : PointOfSaleService
{
private UserRole loggedInUserRole;
protected override void AccessControl()
{
/* Empty */
}
protected override void Dispatch()
{
loggedInUserRole = PointOfSaleRoot.GetInstance().LoggedInUser.Role;
}
public UserRole GetUserRole()
{
return loggedInUserRole;
}
}
}
| 20.6875 | 79 | 0.648036 | [
"MIT"
] | Strabox/PointOfSale | PointOfSale/PointOfSaleUI/Business/Services/Local/GetLoggedInUserRoleService.cs | 664 | 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.Linq;
namespace ReactiveUI
{
internal static class CompatMixins
{
internal static void ForEach<T>(this IEnumerable<T> This, Action<T> block)
{
foreach (var v in This) {
block(v);
}
}
internal static IEnumerable<T> SkipLast<T>(this IEnumerable<T> This, int count)
{
return This.Take(This.Count() - count);
}
}
// according to spouliot, this is just a string match, and will cause the
// linker to be ok with everything.
internal class PreserveAttribute : Attribute
{
public bool AllMembers { get; set; }
}
}
| 27.727273 | 87 | 0.63388 | [
"MIT"
] | editor-tools/ReactiveUI | src/ReactiveUI/CompatMixins.cs | 915 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.Rendering;
using System.IO;
public class RenderFisheye : MonoBehaviour {
public RenderCubemap cubemap_script;
public Shader shader;
public float focalLength_x = 1.0f;
public float focalLength_y = 1.0f;
private string screenshotsDirectory = "Logs";
private Material _material;
private Material material {
get {
if (_material == null) {
_material = new Material(shader);
_material.hideFlags = HideFlags.HideAndDontSave;
}
return _material;
}
}
void Start () {
}
private void OnDisable() {
if (_material != null)
DestroyImmediate(_material);
}
void OnRenderImage(RenderTexture source, RenderTexture destination)
{
Debug.Log("OnRenderImage: Fisheye");
if (shader != null) {
material.SetTexture("_Cube", cubemap_script.cubemap);
material.SetFloat("_FocalLength_x", focalLength_x);
material.SetFloat("_FocalLength_y", focalLength_y);
Graphics.Blit(source, destination, material);
}
else {
Graphics.Blit(source, destination);
}
if (Time.frameCount <= 6)
{
SaveBitmap(source, "test" + Time.frameCount + ".png");
}
}
void SaveBitmap(RenderTexture myRenderTexture, string filename)
{
Debug.Log("final textue width: " + myRenderTexture.width);
Debug.Log("final textue height: " + myRenderTexture.height);
var tex = new Texture2D(myRenderTexture.width, myRenderTexture.height, TextureFormat.RGBA32, false);
tex.ReadPixels(new Rect(0, 0, myRenderTexture.width, myRenderTexture.height), 0, 0);
tex.Apply();
byte[] bytes = tex.EncodeToPNG();
Destroy(tex);
var path = screenshotsDirectory + "/" + "fisheye" + filename;
File.WriteAllBytes(path, bytes);
}
}
| 30.268657 | 108 | 0.620316 | [
"MIT"
] | summeryqc/unity_fisheye_camera | test_camera/Assets/FisheyeLens/RenderFisheye.cs | 2,030 | C# |
namespace MaterialColor.Json
{
using MaterialColor.Data;
using ONI_Common.Data;
using ONI_Common.IO;
using ONI_Common.Json;
public class ConfiguratorStateManager : BaseManager
{
public ConfiguratorStateManager(JsonManager manager, Logger logger = null)
: base(manager, logger)
{
}
public MaterialColorState LoadMaterialColorState()
{
return this._manager.Deserialize<MaterialColorState>(Paths.MaterialColorStatePath);
}
/*
public OnionState LoadOnionState()
{
return this._manager.Deserialize<OnionState>(Paths.OnionStatePath);
}
*/
public TemperatureOverlayState LoadTemperatureState()
{
return this._manager.Deserialize<TemperatureOverlayState>(Paths.TemperatureStatePath);
}
public void SaveMaterialColorState(MaterialColorState state)
{
this._manager.Serialize(state, Paths.MaterialColorStatePath);
}
/*
public void SaveOnionState(OnionState state)
{
this._manager.Serialize(state, Paths.OnionStatePath);
}
*/
public void SaveTemperatureState(TemperatureOverlayState state)
{
this._manager.Serialize(state, Paths.TemperatureStatePath);
}
}
} | 27.77551 | 98 | 0.635562 | [
"MIT"
] | NitroturtleONI/ONI-Modloader-Mods | Source/MaterialColor/Json/ConfiguratorStateManager.cs | 1,363 | C# |
using System.Collections;
using UnityEngine;
using UniRx;
using System;
namespace UniRxLession
{
public class CoroutineWhenAllExample : MonoBehaviour
{
IEnumerator A()
{
yield return new WaitForSeconds(1.0f);
Debug.Log("-----A");
}
IEnumerator B()
{
yield return new WaitForSeconds(2.0f);
Debug.Log("-----B");
}
private void Start()
{
var streamA = Observable.FromCoroutine(_ => A());
var streamB = Observable.FromCoroutine(_ => B());
Observable.WhenAll(streamA, streamB)
.Subscribe(_ =>
{
Debug.Log("print completed");
}).AddTo(this);
}
}
} | 22.914286 | 62 | 0.485037 | [
"MIT"
] | DiazGames/UniRxExample | Assets/Chapter2/5.WhenAll/CoroutineWhenAllExample.cs | 804 | C# |
using System;
using System.Runtime.InteropServices;
namespace thor
{
public class VTFFileTypes : IFileTypeFactory
{
public static readonly FileType Vtf = new VtfFileType();
private static FileType[] FileTypes = new FileType[] { Vtf };
internal FileTypeCollection GetFileTypeCollection()
{
return new FileTypeCollection(FileTypes);
}
public FileType[] GetFileTypeInstances()
{
return (FileType[])FileTypes.Clone();
}
}
[Guid("449c5c3e-cf3c-11db-8314-0800200c9a66")]
public class VtfFileType : FileType
{
public VtfFileType() : base("VTF", true, false, true, true, false, new string[] { ".vtf" })
{
VtfLib.vlInitialize();
}
~VtfFileType()
{
// It seems there are multiple concurrent instances of this class...
//VtfLib.vlShutdown();
}
public override SaveConfigWidget CreateSaveConfigWidget()
{
return new VtfSaveConfigWidget();
}
protected override SaveConfigToken OnCreateDefaultSaveConfigToken()
{
return new VtfSaveConfigToken();
}
protected override void OnSave(Document Input, System.IO.Stream Output, SaveConfigToken Token, Surface ScratchSurface, ProgressEventHandler Callback)
{
new VtfFile().Save(Output, Input, (VtfSaveConfigToken)Token, ScratchSurface);
}
protected override Document OnLoad(System.IO.Stream Input)
{
return new VtfFile().Load(Input);
}
}
}
| 25.947368 | 157 | 0.667343 | [
"BSD-3-Clause"
] | LogicAndTrick/thor | thor/VtfFileType.cs | 1,479 | C# |
/**
* (C) Copyright IBM Corp. 2020.
*
* 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 IBM.Cloud.SDK.Core.Model;
using Newtonsoft.Json;
namespace IBM.Watson.Assistant.v2.Model
{
/// <summary>
/// System context data used by the skill.
/// </summary>
public class MessageContextSkillSystem : DynamicModel<object>
{
/// <summary>
/// An encoded string that represents the current conversation state. By saving this value and then sending it
/// in the context of a subsequent message request, you can return to an earlier point in the conversation. If
/// you are using stateful sessions, you can also use a stored state value to restore a paused conversation
/// whose session is expired.
/// </summary>
[JsonProperty("state", NullValueHandling = NullValueHandling.Ignore)]
public string State { get; set; }
}
}
| 36.128205 | 118 | 0.701916 | [
"Apache-2.0"
] | darkmatter2222/dotnet-standard-sdk | src/IBM.Watson.Assistant.v2/Model/MessageContextSkillSystem.cs | 1,409 | C# |
using System;
namespace NewsPress.Models
{
public class ErrorViewModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
}
}
| 17.333333 | 70 | 0.663462 | [
"MIT"
] | clementbouvard/NewsPress | NewsPress/NewsPress/Models/ErrorViewModel.cs | 208 | C# |
//------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
//------------------------------------------------------------
namespace Microsoft.Azure.Cosmos.SqlObjects
{
using Microsoft.Azure.Cosmos.SqlObjects.Visitors;
#if INTERNAL
#pragma warning disable CS1591 // Missing XML comment for publicly visible type or member
#pragma warning disable SA1600 // Elements should be documented
public
#else
internal
#endif
abstract class SqlScalarExpression : SqlObject
{
protected SqlScalarExpression()
{
}
public abstract void Accept(SqlScalarExpressionVisitor visitor);
public abstract TResult Accept<TResult>(SqlScalarExpressionVisitor<TResult> visitor);
public abstract TResult Accept<T, TResult>(SqlScalarExpressionVisitor<T, TResult> visitor, T input);
}
}
| 31 | 108 | 0.632925 | [
"MIT"
] | Arithmomaniac/azure-cosmos-dotnet-v3 | Microsoft.Azure.Cosmos/src/SqlObjects/SqlScalarExpression.cs | 901 | C# |
using System;
using Microsoft.EntityFrameworkCore.Migrations;
using Npgsql.EntityFrameworkCore.PostgreSQL.Metadata;
namespace Infrastructure.Migrations
{
public partial class FistMigration : Migration
{
protected override void Up(MigrationBuilder migrationBuilder)
{
migrationBuilder.EnsureSchema(
name: "sistema_escolar");
migrationBuilder.CreateTable(
name: "ano_letivo",
schema: "sistema_escolar",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false),
ano = table.Column<string>(type: "char(4)", nullable: false),
data_inicio = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
data_final = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
vigente = table.Column<bool>(type: "boolean", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_ano_letivo", x => x.id);
});
migrationBuilder.CreateTable(
name: "estado",
schema: "sistema_escolar",
columns: table => new
{
Id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
nome = table.Column<string>(type: "text", nullable: false),
sigla = table.Column<string>(type: "char(2)", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_estado", x => x.Id);
});
migrationBuilder.CreateTable(
name: "cidade",
schema: "sistema_escolar",
columns: table => new
{
id = table.Column<int>(type: "integer", nullable: false)
.Annotation("Npgsql:ValueGenerationStrategy", NpgsqlValueGenerationStrategy.IdentityByDefaultColumn),
nome = table.Column<string>(type: "text", nullable: false),
id_estado = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_cidade", x => x.id);
table.ForeignKey(
name: "fk_c_estado",
column: x => x.id_estado,
principalSchema: "sistema_escolar",
principalTable: "estado",
principalColumn: "Id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "endereco",
schema: "sistema_escolar",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false),
logradouro = table.Column<string>(type: "text", nullable: false),
numero = table.Column<int>(type: "integer", nullable: true),
complemento = table.Column<string>(type: "text", nullable: true),
bairro = table.Column<string>(type: "text", nullable: false),
cep = table.Column<string>(type: "char(8)", nullable: false),
id_cidade = table.Column<int>(type: "integer", nullable: false)
},
constraints: table =>
{
table.PrimaryKey("PK_endereco", x => x.id);
table.ForeignKey(
name: "fk_e_cidade",
column: x => x.id_cidade,
principalSchema: "sistema_escolar",
principalTable: "cidade",
principalColumn: "id",
onDelete: ReferentialAction.Cascade);
});
migrationBuilder.CreateTable(
name: "pessoa",
schema: "sistema_escolar",
columns: table => new
{
id = table.Column<Guid>(type: "uuid", nullable: false),
nome = table.Column<string>(type: "character varying(100)", maxLength: 100, nullable: false),
data_nascimento = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
genero = table.Column<string>(type: "text", nullable: false),
cpf = table.Column<string>(type: "char(11)", nullable: true),
estado_civil = table.Column<string>(type: "text", nullable: false),
email = table.Column<string>(type: "character varying(50)", maxLength: 50, nullable: true),
telefone = table.Column<string>(type: "character varying(15)", maxLength: 15, nullable: true),
celular = table.Column<string>(type: "character varying(15)", maxLength: 15, nullable: true),
ativo = table.Column<bool>(type: "boolean", nullable: false),
foto = table.Column<string>(type: "text", nullable: true),
data_cadastro = table.Column<DateTime>(type: "timestamp without time zone", nullable: false),
data_alteracao = table.Column<DateTime>(type: "timestamp without time zone", nullable: true),
data_exclusao = table.Column<DateTime>(type: "timestamp without time zone", nullable: true),
id_endereco = table.Column<Guid>(type: "uuid", nullable: true)
},
constraints: table =>
{
table.PrimaryKey("PK_pessoa", x => x.id);
table.ForeignKey(
name: "FK_pessoa_endereco_id_endereco",
column: x => x.id_endereco,
principalSchema: "sistema_escolar",
principalTable: "endereco",
principalColumn: "id",
onDelete: ReferentialAction.Restrict);
});
migrationBuilder.CreateIndex(
name: "IX_cidade_id_estado",
schema: "sistema_escolar",
table: "cidade",
column: "id_estado");
migrationBuilder.CreateIndex(
name: "IX_endereco_id_cidade",
schema: "sistema_escolar",
table: "endereco",
column: "id_cidade");
migrationBuilder.CreateIndex(
name: "IX_pessoa_id_endereco",
schema: "sistema_escolar",
table: "pessoa",
column: "id_endereco");
}
protected override void Down(MigrationBuilder migrationBuilder)
{
migrationBuilder.DropTable(
name: "ano_letivo",
schema: "sistema_escolar");
migrationBuilder.DropTable(
name: "pessoa",
schema: "sistema_escolar");
migrationBuilder.DropTable(
name: "endereco",
schema: "sistema_escolar");
migrationBuilder.DropTable(
name: "cidade",
schema: "sistema_escolar");
migrationBuilder.DropTable(
name: "estado",
schema: "sistema_escolar");
}
}
}
| 45.821429 | 125 | 0.502078 | [
"MIT"
] | phjb/SistemaEscolar | src/Infrastructure/Migrations/20210120000912_Fist-Migration.cs | 7,700 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class InputSource : MonoBehaviour
{
public enum Button
{
Cross,
Circle,
Square,
Triangle
}
private Dictionary<Button, string> buttonStrings;
private void Awake()
{
buttonStrings = new Dictionary<Button, string>()
{
{Button.Cross, "Jump" },
{Button.Circle, "Fire2" },
{Button.Square, "Fire1" },
{Button.Triangle, "" }
};
}
public virtual bool GetButtonDown(Button button)
{
return Input.GetButtonDown(buttonStrings[button]);
}
public virtual float GetHorizontalAxisLeftStick()
{
return Input.GetAxis("Horizontal");
}
public virtual float GetVerticalAxisLeftStick()
{
return Input.GetAxis("Vertical");
}
}
| 21.142857 | 58 | 0.593468 | [
"MIT"
] | Feverfew826/SideScrollStrategy | Assets/Scripts/Inputs/InputSource.cs | 890 | C# |
using System;
namespace CafeLib.Authorization.Tokens
{
public class TokenResponse
{
public Token Token { get; set; }
public string Message { get; set; }
public Exception Exception { get; set; }
}
}
| 17 | 48 | 0.617647 | [
"MIT"
] | chrissolutions/CafeLib | Authorization/CafeLib.Authorization.Tokens/TokenResponse.cs | 240 | C# |
using System;
using System.Collections.Generic;
using UnityEngine;
// public enum FlareTexModel
// {
// _2x2 = 0,
// _4x4 = 1,
// _Mega = 2,
// _1L4S = 3,
// _1L2M8S = 4,
// }
[CreateAssetMenu(fileName = "FlareAsset", menuName = "MFLensflare/Create FlareAsset split by Cell")]
[Serializable]
public class MFFlareAssetCell : MFFlareAsset
{
[SerializeField]public Vector2Int modelCell;
}
| 19.428571 | 100 | 0.681373 | [
"MIT"
] | Reguluz/Moonflow-Lensflare-System | Assets/MoonFlowLensFlare/MFFlareAssetCell.cs | 410 | C# |
using System;
using System.Collections.Generic;
namespace Nuclear.TestSite.TestSuites {
class ReferenceTestSuite_uTests {
#region IsEqual
[TestMethod]
[TestData(nameof(IsEqualData))]
void IsEqual(Object input1, Object input2, (Int32 count, Boolean result, String message) expected) {
Statics.DDTResultState(() => DummyTest.If.Reference.IsEqual(input1, input2),
expected, "Test.If.Reference.IsEqual");
}
IEnumerable<Object[]> IsEqualData() {
return new List<Object[]>() {
new Object[] { null, null, (1, true, "References equal.") },
new Object[] { null, new Object(), (2, false, "References don't equal.") },
new Object[] { new Object(), null, (3, false, "References don't equal.") },
new Object[] { new Object(), new Object(), (4, false, "References don't equal.") },
new Object[] { DummyTestResults.Instance, DummyTestResults.Instance, (5, true, "References equal.") },
};
}
[TestMethod]
[TestData(nameof(NotIsEqualData))]
void NotIsEqual(Object input1, Object input2, (Int32 count, Boolean result, String message) expected) {
Statics.DDTResultState(() => DummyTest.IfNot.Reference.IsEqual(input1, input2),
expected, "Test.IfNot.Reference.IsEqual");
}
IEnumerable<Object[]> NotIsEqualData() {
return new List<Object[]>() {
new Object[] { null, null, (1, false, "References equal.") },
new Object[] { null, new Object(), (2, true, "References don't equal.") },
new Object[] { new Object(), null, (3, true, "References don't equal.") },
new Object[] { new Object(), new Object(), (4, true, "References don't equal.") },
new Object[] { DummyTestResults.Instance, DummyTestResults.Instance, (5, false, "References equal.") },
};
}
#endregion
#region IsEqualWithMessage
[TestMethod]
[TestData(nameof(IsEqualWithMessageData))]
void IsEqualWithMessage(Object input1, Object input2, String customMessage, (Int32 count, Boolean result, String message) expected) {
Statics.DDTResultState(() => DummyTest.If.Reference.IsEqual(input1, input2, customMessage),
expected, "Test.If.Reference.IsEqual");
}
IEnumerable<Object[]> IsEqualWithMessageData() {
return new List<Object[]>() {
new Object[] { null, null, "message", (1, true, "References equal.") },
new Object[] { null, new Object(), "message", (2, false, "message") },
};
}
[TestMethod]
[TestData(nameof(NotIsEqualWithMessageData))]
void NotIsEqualWithMessage(Object input1, Object input2, String customMessage, (Int32 count, Boolean result, String message) expected) {
Statics.DDTResultState(() => DummyTest.IfNot.Reference.IsEqual(input1, input2, customMessage),
expected, "Test.IfNot.Reference.IsEqual");
}
IEnumerable<Object[]> NotIsEqualWithMessageData() {
return new List<Object[]>() {
new Object[] { null, null, "message", (1, false, "message") },
new Object[] { null, new Object(), "message", (2, true, "References don't equal.") },
};
}
#endregion
}
}
| 40.126437 | 144 | 0.578058 | [
"MIT"
] | MikeLimaSierra/Nuclear.TestSite | src/Nuclear.TestSite.uTests/TestSuites/ReferenceTestSuite_uTests.cs | 3,493 | C# |
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information.
// Ported from um/wingdi.h in the Windows SDK for Windows 10.0.20348.0
// Original source is Copyright © Microsoft. All rights reserved.
namespace TerraFX.Interop
{
public partial struct LOGBRUSH32
{
[NativeTypeName("UINT")]
public uint lbStyle;
[NativeTypeName("COLORREF")]
public uint lbColor;
[NativeTypeName("ULONG")]
public uint lbHatch;
}
}
| 27.85 | 145 | 0.684022 | [
"MIT"
] | DaZombieKiller/terrafx.interop.windows | sources/Interop/Windows/um/wingdi/LOGBRUSH32.cs | 559 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See License.txt in the project root for license information.
// Code generated by Microsoft (R) AutoRest Code Generator.
// Changes may cause incorrect behavior and will be lost if the code is regenerated.
namespace Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview
{
using static Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Extensions;
/// <summary>Role eligibility schedule</summary>
public partial class RoleEligibilitySchedule
{
/// <summary>
/// <c>AfterFromJson</c> will be called after the json deserialization has finished, allowing customization of the object
/// before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
partial void AfterFromJson(Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonObject json);
/// <summary>
/// <c>AfterToJson</c> will be called after the json serialization has finished, allowing customization of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonObject"
/// /> before it is returned. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
partial void AfterToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonObject container);
/// <summary>
/// <c>BeforeFromJson</c> will be called before the json deserialization has commenced, allowing complete customization of
/// the object before it is deserialized.
/// If you wish to disable the default deserialization entirely, return <c>true</c> in the <paramref name= "returnNow" />
/// output parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="json">The JsonNode that should be deserialized into this object.</param>
/// <param name="returnNow">Determines if the rest of the deserialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeFromJson(Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonObject json, ref bool returnNow);
/// <summary>
/// <c>BeforeToJson</c> will be called before the json serialization has commenced, allowing complete customization of the
/// object before it is serialized.
/// If you wish to disable the default serialization entirely, return <c>true</c> in the <paramref name="returnNow" /> output
/// parameter.
/// Implement this method in a partial class to enable this behavior.
/// </summary>
/// <param name="container">The JSON container that the serialization result will be placed in.</param>
/// <param name="returnNow">Determines if the rest of the serialization should be processed, or if the method should return
/// instantly.</param>
partial void BeforeToJson(ref Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonObject container, ref bool returnNow);
/// <summary>
/// Deserializes a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonNode"/> into an instance of Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleEligibilitySchedule.
/// </summary>
/// <param name="node">a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonNode" /> to deserialize from.</param>
/// <returns>
/// an instance of Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleEligibilitySchedule.
/// </returns>
public static Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.IRoleEligibilitySchedule FromJson(Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonNode node)
{
return node is Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonObject json ? new RoleEligibilitySchedule(json) : null;
}
/// <summary>
/// Deserializes a Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonObject into a new instance of <see cref="RoleEligibilitySchedule" />.
/// </summary>
/// <param name="json">A Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonObject instance to deserialize from.</param>
internal RoleEligibilitySchedule(Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonObject json)
{
bool returnNow = false;
BeforeFromJson(json, ref returnNow);
if (returnNow)
{
return;
}
{_property = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonObject>("properties"), out var __jsonProperties) ? Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Models.Api20201001Preview.RoleEligibilityScheduleProperties.FromJson(__jsonProperties) : Property;}
{_id = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonString>("id"), out var __jsonId) ? (string)__jsonId : (string)Id;}
{_name = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonString>("name"), out var __jsonName) ? (string)__jsonName : (string)Name;}
{_type = If( json?.PropertyT<Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonString>("type"), out var __jsonType) ? (string)__jsonType : (string)Type;}
AfterFromJson(json);
}
/// <summary>
/// Serializes this instance of <see cref="RoleEligibilitySchedule" /> into a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonNode" />.
/// </summary>
/// <param name="container">The <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonObject"/> container to serialize this object into. If the caller
/// passes in <c>null</c>, a new instance will be created and returned to the caller.</param>
/// <param name="serializationMode">Allows the caller to choose the depth of the serialization. See <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.SerializationMode"/>.</param>
/// <returns>
/// a serialized instance of <see cref="RoleEligibilitySchedule" /> as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonNode" />.
/// </returns>
public Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonNode ToJson(Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonObject container, Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.SerializationMode serializationMode)
{
container = container ?? new Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonObject();
bool returnNow = false;
BeforeToJson(ref container, ref returnNow);
if (returnNow)
{
return container;
}
AddIf( null != this._property ? (Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonNode) this._property.ToJson(null,serializationMode) : null, "properties" ,container.Add );
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._id)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonString(this._id.ToString()) : null, "id" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._name)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonString(this._name.ToString()) : null, "name" ,container.Add );
}
if (serializationMode.HasFlag(Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.SerializationMode.IncludeReadOnly))
{
AddIf( null != (((object)this._type)?.ToString()) ? (Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonNode) new Microsoft.Azure.PowerShell.Cmdlets.Resources.Authorization.Runtime.Json.JsonString(this._type.ToString()) : null, "type" ,container.Add );
}
AfterToJson(ref container);
return container;
}
}
} | 77.520325 | 331 | 0.705296 | [
"MIT"
] | AlanFlorance/azure-powershell | src/Resources/Authorization.Autorest/generated/api/Models/Api20201001Preview/RoleEligibilitySchedule.json.cs | 9,413 | C# |
using System;
using System.Xml.Serialization;
namespace Aop.Api.Domain
{
/// <summary>
/// SearchOrderBaseKeyWordNumRequest Data Structure.
/// </summary>
[Serializable]
public class SearchOrderBaseKeyWordNumRequest : AopObject
{
/// <summary>
/// appid
/// </summary>
[XmlElement("appid")]
public string Appid { get; set; }
/// <summary>
/// 应用类型
/// </summary>
[XmlElement("spec_code")]
public string SpecCode { get; set; }
}
}
| 22.56 | 62 | 0.535461 | [
"Apache-2.0"
] | 554393109/alipay-sdk-net-all | AlipaySDKNet.Standard/Domain/SearchOrderBaseKeyWordNumRequest.cs | 572 | C# |
using System.Linq;
namespace Eventualize.Projection.FluentProjection
{
public interface IFluentUpdateEventHandler<TProjectionModel, TEvent> : IFluentEventHandler<IFluentUpdateEventHandler<TProjectionModel, TEvent>, TProjectionModel, TEvent>
{
}
} | 32.375 | 173 | 0.814672 | [
"MIT"
] | Useurmind/Eventualize | Eventualize.Projection/FluentProjection/IFluentUpdateEventHandler.cs | 259 | 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("TwoUniquesAmongDuplicatesTestGenerator")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("TwoUniquesAmongDuplicatesTestGenerator")]
[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("f0824f6c-77e6-461b-b674-897957ce0371")]
// 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")]
| 39.162162 | 84 | 0.754313 | [
"MIT"
] | dushka-dragoeva/TelerikSeson2016 | Useful Materials/C Sharp/BitwiseMagicDemos/TwoUniquesAmongDuplicatesTestGenerator/Properties/AssemblyInfo.cs | 1,452 | C# |
using System.Collections;
using UnityEngine;
namespace CippSharp.Core.Coroutines
{
public static class AnimatorTransitions
{
#region Edit Parameters
/// <summary>
/// Move an animator float parameter from his current value to final value
/// </summary>
/// <param name="animator"></param>
/// <param name="parameterId"></param>
/// <param name="finalValue"></param>
/// <param name="duration"></param>
/// <param name="onComplete"></param>
/// <param name="debugContext"></param>
public static Coroutine MoveFloatParameter(Animator animator, int parameterId, float finalValue,
float duration, CompletedCallback onComplete = null, Object debugContext = null)
{
string logName = debugContext != null ? LogUtils.LogName(debugContext.GetType()) : string.Empty;
if (animator == null)
{
Debug.LogError(logName+$"{nameof(MoveFloatParameter)} {nameof(animator)} is null!", debugContext);
onComplete?.Invoke(false);
return null;
}
float target = animator.GetFloat(parameterId);
return MoveFloatParameterInternal(animator, parameterId, target, finalValue, duration, onComplete, debugContext);
}
/// <summary>
/// Move an animator float parameter from his current value to final value
/// </summary>
/// <param name="animator"></param>
/// <param name="parameterId"></param>
/// <param name="currentValue"></param>
/// <param name="finalValue"></param>
/// <param name="duration"></param>
/// <param name="onComplete"></param>
/// <param name="debugContext"></param>
private static Coroutine MoveFloatParameterInternal (Animator animator, int parameterId, float currentValue, float finalValue, float duration, CompletedCallback onComplete = null, Object debugContext = null)
{
return CoroutineUtils.StartCoroutine(MoveFloatParameterCoroutineInternal(animator, parameterId, currentValue, finalValue, duration, onComplete, debugContext));
}
private static IEnumerator MoveFloatParameterCoroutineInternal(Animator animator, int parameterId, float currentValue, float finalValue, float duration, CompletedCallback onComplete = null, Object debugContext = null)
{
string logName = debugContext != null ? LogUtils.LogName(debugContext.GetType()) : string.Empty;
if (duration <= 0.0f)
{
if (animator != null)
{
animator.SetFloat(parameterId, finalValue);
}
onComplete?.Invoke(true);
yield break;
}
float rate = 1.0f / duration;
float t = 0.0f;
while (t < 1.0f)
{
yield return null;
t += Time.deltaTime * rate;
float currentLerp = Mathf.Lerp(currentValue, finalValue, t);
if (animator != null)
{
animator.SetFloat(parameterId, currentLerp);
}
else
{
Debug.LogError(logName+$"{nameof(MoveFloatParameterCoroutineInternal)} {nameof(animator)} is null! Fallback exit Coroutine.", debugContext);
onComplete?.Invoke(false);
yield break;
}
}
onComplete?.Invoke(true);
yield break;
}
#endregion
}
}
| 41.337079 | 225 | 0.569176 | [
"MIT"
] | ZiosTheCloudburster/CippSharpCoreCoroutines | Runtime/AnimatorTransitions.cs | 3,681 | C# |
using System.Resources;
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("ApmToTap")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("ApmToTap")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[assembly: NeutralResourcesLanguage("en")]
// 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")]
| 34.516129 | 84 | 0.742991 | [
"Apache-2.0"
] | aliozgur/xamarin-forms-book-samples | Chapter20/ApmToTap/ApmToTap/ApmToTap/Properties/AssemblyInfo.cs | 1,071 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace CompoundTools.CFB
{
public class CFBDirectoryEntry
{
public string Name { get; set; }
public ushort NameBufferSize { get; set; }
public EntryType Type { get; set; }
public byte NodeColor { get; set; }
public int DirIDLeftChild { get; set; }
public int DirIDRightChild { get; set; }
public int DirIDRoot { get; set; }
public string UID { get; set; }
public uint Flags { get; set; }
public ulong CreationTime { get; set; }
public ulong ModificationTime { get; set; }
public int FirstSecID { get; set; }
public uint StreamSize { get; set; }
public int DirID { get; set; }
public bool ShortStream
{
get
{
return this.StreamSize > 0 && this.StreamSize < this.File.Header.StreamMinSize;
}
}
private CFBFile File;
public enum EntryType
{
Empty = 0x00,
UserStorage= 0x01,
UserStream = 0x02,
LockBytes = 0x03,
Property = 0x04,
RootStorage = 0x05
}
public static int GetPos(int DirID)
{
return DirID * 128;
}
public CFBDirectoryEntry(int DirID, CFBFile file)
{
this.DirID = DirID;
this.Parse(file.RootStream.Data.Skip(GetPos(DirID)).ToArray(), file);
}
void Parse(byte[] data, CFBFile file)
{
this.NameBufferSize = BitConverter.ToUInt16(data, 64);
this.Name = Encoding.Unicode.GetString(data.Take(NameBufferSize-2).ToArray());
this.Type = (EntryType)data[66];
this.NodeColor = data[67];
this.DirIDLeftChild = BitConverter.ToInt32(data, 68);
this.DirIDRightChild = BitConverter.ToInt32(data, 72);
this.DirIDRoot = BitConverter.ToInt32(data, 76);
this.UID = Encoding.Unicode.GetString(data.Skip(80).Take(16).ToArray());
this.Flags = BitConverter.ToUInt32(data, 96);
this.CreationTime = BitConverter.ToUInt64(data, 100);
this.ModificationTime = BitConverter.ToUInt64(data, 108);
this.FirstSecID = BitConverter.ToInt32(data, 116);
this.StreamSize = BitConverter.ToUInt32(data, 120);
this.File = file;
}
}
}
| 33.558442 | 96 | 0.555728 | [
"MIT"
] | FuSoftware/CompoundTools | CompoundTools/CFB/CFBDirectoryEntry.cs | 2,586 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// Dieser Code wurde von einem Tool generiert.
// Laufzeitversion:4.0.30319.42000
//
// Änderungen an dieser Datei können falsches Verhalten verursachen und gehen verloren, wenn
// der Code erneut generiert wird.
// </auto-generated>
//------------------------------------------------------------------------------
using NMF.Collections.Generic;
using NMF.Collections.ObjectModel;
using NMF.Expressions;
using NMF.Expressions.Linq;
using NMF.Models;
using NMF.Models.Collections;
using NMF.Models.Expressions;
using NMF.Models.Meta;
using NMF.Models.Repository;
using NMF.Serialization;
using NMF.Utilities;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using TTC2017.SmartGrids.CIM;
using TTC2017.SmartGrids.CIM.IEC61968.Assets;
using TTC2017.SmartGrids.CIM.IEC61968.PaymentMetering;
using TTC2017.SmartGrids.CIM.IEC61970.Core;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfAssets;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfCommon;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfERPSupport;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfGMLSupport;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfLocations;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfOperations;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.InfWork;
using TTC2017.SmartGrids.CIM.IEC61970.Informative.MarketOperations;
using TTC2017.SmartGrids.CIM.IEC61970.Meas;
namespace TTC2017.SmartGrids.CIM.IEC61968.Common
{
/// <summary>
/// The public interface for TownDetail
/// </summary>
[DefaultImplementationTypeAttribute(typeof(TownDetail))]
[XmlDefaultImplementationTypeAttribute(typeof(TownDetail))]
public interface ITownDetail : IModelElement, IElement
{
/// <summary>
/// The country property
/// </summary>
string Country
{
get;
set;
}
/// <summary>
/// The code property
/// </summary>
string Code
{
get;
set;
}
/// <summary>
/// The name property
/// </summary>
string Name
{
get;
set;
}
/// <summary>
/// The section property
/// </summary>
string Section
{
get;
set;
}
/// <summary>
/// The stateOrProvince property
/// </summary>
string StateOrProvince
{
get;
set;
}
/// <summary>
/// Gets fired before the Country property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> CountryChanging;
/// <summary>
/// Gets fired when the Country property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> CountryChanged;
/// <summary>
/// Gets fired before the Code property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> CodeChanging;
/// <summary>
/// Gets fired when the Code property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> CodeChanged;
/// <summary>
/// Gets fired before the Name property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> NameChanging;
/// <summary>
/// Gets fired when the Name property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> NameChanged;
/// <summary>
/// Gets fired before the Section property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> SectionChanging;
/// <summary>
/// Gets fired when the Section property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> SectionChanged;
/// <summary>
/// Gets fired before the StateOrProvince property changes its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> StateOrProvinceChanging;
/// <summary>
/// Gets fired when the StateOrProvince property changed its value
/// </summary>
event System.EventHandler<ValueChangedEventArgs> StateOrProvinceChanged;
}
}
| 31.368421 | 96 | 0.612626 | [
"MIT"
] | georghinkel/ttc2017smartGrids | generator/Schema/IEC61968/Common/ITownDetail.cs | 4,770 | C# |
using SwitcherServer.Atem;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
namespace SwitcherServer
{
public interface IConnectionChangeNotifyQueue : INotificationQueue<ConnectionChangeNotify>
{
}
}
| 20.066667 | 95 | 0.760797 | [
"MIT"
] | tomblchr/atem-streamlia | App/IConnectionChangeNotifyQueue.cs | 303 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License. See LICENSE in the project root for license information.
using UnityEditor;
namespace Microsoft.MixedReality.Toolkit.Utilities.Editor
{
[CustomEditor(typeof(GridObjectCollection), true)]
public class GridObjectCollectionInspector : BaseCollectionInspector
{
private SerializedProperty surfaceType;
private SerializedProperty orientType;
private SerializedProperty layout;
private SerializedProperty radius;
private SerializedProperty radialRange;
private SerializedProperty distance;
private SerializedProperty rows;
private SerializedProperty cellWidth;
private SerializedProperty cellHeight;
protected override void OnEnable()
{
base.OnEnable();
surfaceType = serializedObject.FindProperty("surfaceType");
orientType = serializedObject.FindProperty("orientType");
layout = serializedObject.FindProperty("layout");
radius = serializedObject.FindProperty("radius");
distance = serializedObject.FindProperty("distance");
radialRange = serializedObject.FindProperty("radialRange");
rows = serializedObject.FindProperty("rows");
cellWidth = serializedObject.FindProperty("cellWidth");
cellHeight = serializedObject.FindProperty("cellHeight");
}
protected override void OnInspectorGUIInsertion()
{
EditorGUILayout.PropertyField(surfaceType);
EditorGUILayout.PropertyField(orientType);
EditorGUILayout.PropertyField(layout);
if ((ObjectOrientationSurfaceType) surfaceType.enumValueIndex == ObjectOrientationSurfaceType.Plane)
{
EditorGUILayout.PropertyField(distance);
}
else
{
EditorGUILayout.PropertyField(radius);
EditorGUILayout.PropertyField(radialRange);
}
LayoutOrder layoutTypeIndex = (LayoutOrder) layout.enumValueIndex;
if (layoutTypeIndex != LayoutOrder.Horizontal && layoutTypeIndex != LayoutOrder.Vertical)
{
EditorGUILayout.PropertyField(rows);
}
if (layoutTypeIndex != LayoutOrder.Vertical)
{
EditorGUILayout.PropertyField(cellWidth);
}
if (layoutTypeIndex != LayoutOrder.Horizontal)
{
EditorGUILayout.PropertyField(cellHeight);
}
}
}
}
| 39.253731 | 112 | 0.647148 | [
"MIT"
] | ActiveNick/HoloBot | Assets/MixedRealityToolkit.SDK/Inspectors/UX/Collections/GridObjectCollectionInspector.cs | 2,632 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) 2015 Microsoft Corporation
//
// 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 OneDriveApiBrowser
{
partial class OneDriveTile
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Component Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.labelName = new System.Windows.Forms.Label();
this.pictureBoxThumbnail = new System.Windows.Forms.PictureBox();
((System.ComponentModel.ISupportInitialize)(this.pictureBoxThumbnail)).BeginInit();
this.SuspendLayout();
//
// labelName
//
this.labelName.AutoEllipsis = true;
this.labelName.BackColor = System.Drawing.Color.Transparent;
this.labelName.Dock = System.Windows.Forms.DockStyle.Bottom;
this.labelName.Font = new System.Drawing.Font("Segoe UI", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.labelName.ForeColor = System.Drawing.Color.White;
this.labelName.Location = new System.Drawing.Point(0, 91);
this.labelName.Margin = new System.Windows.Forms.Padding(0);
this.labelName.Name = "labelName";
this.labelName.Padding = new System.Windows.Forms.Padding(0, 0, 7, 6);
this.labelName.Size = new System.Drawing.Size(179, 27);
this.labelName.TabIndex = 0;
this.labelName.Text = "Documents (Microsoft)";
this.labelName.TextAlign = System.Drawing.ContentAlignment.BottomLeft;
this.labelName.Click += new System.EventHandler(this.Control_Click);
this.labelName.DoubleClick += new System.EventHandler(this.Control_DoubleClick);
//
// pictureBoxThumbnail
//
this.pictureBoxThumbnail.Dock = System.Windows.Forms.DockStyle.Fill;
this.pictureBoxThumbnail.Location = new System.Drawing.Point(0, 0);
this.pictureBoxThumbnail.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.pictureBoxThumbnail.Name = "pictureBoxThumbnail";
this.pictureBoxThumbnail.Padding = new System.Windows.Forms.Padding(2);
this.pictureBoxThumbnail.Size = new System.Drawing.Size(179, 91);
this.pictureBoxThumbnail.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pictureBoxThumbnail.TabIndex = 1;
this.pictureBoxThumbnail.TabStop = false;
this.pictureBoxThumbnail.Click += new System.EventHandler(this.Control_Click);
this.pictureBoxThumbnail.DoubleClick += new System.EventHandler(this.Control_DoubleClick);
//
// OneDriveTile
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BackColor = System.Drawing.Color.MediumBlue;
this.Controls.Add(this.pictureBoxThumbnail);
this.Controls.Add(this.labelName);
this.Margin = new System.Windows.Forms.Padding(2, 2, 2, 2);
this.Name = "OneDriveTile";
this.Size = new System.Drawing.Size(179, 118);
((System.ComponentModel.ISupportInitialize)(this.pictureBoxThumbnail)).EndInit();
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.Label labelName;
private System.Windows.Forms.PictureBox pictureBoxThumbnail;
}
}
| 49.234234 | 157 | 0.631473 | [
"MIT"
] | HandsomeMark/onedrive-sdk-csharp-master | samples/OneDriveApiBrowser/OneDriveTile.Designer.cs | 5,467 | C# |
using System.IO;
using static LiteDB.Constants;
namespace LiteDB.Engine
{
/// <summary>
/// FileStream disk implementation of disk factory
/// [ThreadSafe]
/// </summary>
internal class FileStreamFactory : IStreamFactory
{
private readonly string _filename;
private readonly string _password;
private readonly bool _readonly;
private readonly bool _hidden;
public FileStreamFactory(string filename, string password, bool readOnly, bool hidden)
{
_filename = filename;
_password = password;
_readonly = readOnly;
_hidden = hidden;
}
/// <summary>
/// Get data filename
/// </summary>
public string Name => Path.GetFileName(_filename);
/// <summary>
/// Create new data file FileStream instance based on filename
/// </summary>
public Stream GetStream(bool canWrite, bool sequencial)
{
var write = canWrite && (_readonly == false);
var isNewFile = write && this.Exists() == false;
var stream = new FileStream(_filename,
_readonly ? FileMode.Open : FileMode.OpenOrCreate,
write ? FileAccess.ReadWrite : FileAccess.Read,
write ? FileShare.Read : FileShare.ReadWrite,
PAGE_SIZE,
// FILE_FLAG_NO_BUFFERING = 0x20000000
(sequencial ? FileOptions.SequentialScan : FileOptions.RandomAccess) | FileOptions.WriteThrough | (FileOptions)0x20000000);
if (isNewFile && _hidden)
{
File.SetAttributes(_filename, FileAttributes.Hidden);
}
return _password == null ? (Stream)stream : new AesStream(_password, stream);
}
/// <summary>
/// Get file length using FileInfo
/// </summary>
public long GetLength()
{
// getting size from OS - if encrypted must remove salt first page
return new FileInfo(_filename).Length - (_password == null ? 0 : PAGE_SIZE);
}
/// <summary>
/// Check if file exists (without open it)
/// </summary>
public bool Exists()
{
return File.Exists(_filename);
}
/// <summary>
/// Delete file (must all stream be closed)
/// </summary>
public void Delete()
{
File.Delete(_filename);
}
/// <summary>
/// Test if this file are locked by another process
/// </summary>
public bool IsLocked() => this.Exists() && FileHelper.IsFileLocked(_filename);
/// <summary>
/// Close all stream on end
/// </summary>
public bool CloseOnDispose => true;
}
} | 31.344444 | 139 | 0.558667 | [
"MIT"
] | gan4-ua/LiteDB | LiteDB/Engine/Disk/StreamFactory/FileStreamFactory.cs | 2,823 | C# |
// preamble: original source: https://github.com/migueldeicaza/redis-sharp/blob/master/redis-sharp.cs
// included here for performance test purposes only; this is a separate and parallel implementation
//
// redis-sharp.cs: ECMA CLI Binding to the Redis key-value storage system
//
// Authors:
// Miguel de Icaza (miguel@gnome.org)
//
// Copyright 2010 Novell, Inc.
//
// Licensed under the same terms of reddis: new BSD license.
//
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Net.Sockets;
using System.Text;
public class Redis : IDisposable
{
Socket socket;
BufferedStream bstream;
public enum KeyType
{
None, String, List, Set
}
public class ResponseException : Exception
{
public ResponseException(string code)
: base("Response error")
{
Code = code;
}
public string Code { get; private set; }
}
public Redis(string host, int port)
{
if (host == null)
throw new ArgumentNullException("host");
Host = host;
Port = port;
SendTimeout = -1;
}
public Redis(string host)
: this(host, 6379)
{
}
public Redis()
: this("localhost", 6379)
{
}
public string Host { get; private set; }
public int Port { get; private set; }
public int RetryTimeout { get; set; }
public int RetryCount { get; set; }
public int SendTimeout { get; set; }
public string Password { get; set; }
int db;
public int Db
{
get
{
return db;
}
set
{
db = value;
SendExpectSuccess("SELECT {0}\r\n", db);
}
}
public string this[string key]
{
get { return GetString(key); }
set { Set(key, value); }
}
public void Set(string key, string value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
Set(key, Encoding.UTF8.GetBytes(value));
}
public void Set(string key, byte[] value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value");
if (!SendDataCommand(value, "SET {0} {1}\r\n", key, value.Length))
throw new Exception("Unable to connect");
ExpectSuccess();
}
public bool SetNX(string key, string value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
return SetNX(key, Encoding.UTF8.GetBytes(value));
}
public bool SetNX(string key, byte[] value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value");
return SendDataExpectInt(value, "SETNX {0} {1}\r\n", key, value.Length) > 0 ? true : false;
}
public void Set(IDictionary<string, string> dict)
{
Set(dict.ToDictionary(k => k.Key, v => Encoding.UTF8.GetBytes(v.Value)));
}
public void Set(IDictionary<string, byte[]> dict)
{
if (dict == null)
throw new ArgumentNullException("dict");
var nl = Encoding.UTF8.GetBytes("\r\n");
var ms = new MemoryStream();
foreach (var key in dict.Keys)
{
var val = dict[key];
var kLength = Encoding.UTF8.GetBytes("$" + key.Length + "\r\n");
var k = Encoding.UTF8.GetBytes(key + "\r\n");
var vLength = Encoding.UTF8.GetBytes("$" + val.Length + "\r\n");
ms.Write(kLength, 0, kLength.Length);
ms.Write(k, 0, k.Length);
ms.Write(vLength, 0, vLength.Length);
ms.Write(val, 0, val.Length);
ms.Write(nl, 0, nl.Length);
}
SendDataCommand(ms.ToArray(), "*" + (dict.Count * 2 + 1) + "\r\n$4\r\nMSET\r\n");
ExpectSuccess();
}
public byte[] Get(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectData(null, "GET " + key + "\r\n");
}
public string GetString(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return Encoding.UTF8.GetString(Get(key));
}
public byte[][] Sort(SortOptions options)
{
return SendDataCommandExpectMultiBulkReply(null, options.ToCommand() + "\r\n");
}
public byte[] GetSet(string key, byte[] value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
if (value.Length > 1073741824)
throw new ArgumentException("value exceeds 1G", "value");
if (!SendDataCommand(value, "GETSET {0} {1}\r\n", key, value.Length))
throw new Exception("Unable to connect");
return ReadData();
}
public string GetSet(string key, string value)
{
if (key == null)
throw new ArgumentNullException("key");
if (value == null)
throw new ArgumentNullException("value");
return Encoding.UTF8.GetString(GetSet(key, Encoding.UTF8.GetBytes(value)));
}
string ReadLine()
{
var sb = new StringBuilder();
int c;
while ((c = bstream.ReadByte()) != -1)
{
if (c == '\r')
continue;
if (c == '\n')
break;
sb.Append((char)c);
}
return sb.ToString();
}
void Connect()
{
socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
socket.NoDelay = true;
socket.SendTimeout = SendTimeout;
socket.Connect(Host, Port);
if (!socket.Connected)
{
socket.Close();
socket = null;
return;
}
bstream = new BufferedStream(new NetworkStream(socket), 16 * 1024);
if (Password != null)
SendExpectSuccess("AUTH {0}\r\n", Password);
}
byte[] end_data = new byte[] { (byte)'\r', (byte)'\n' };
bool SendDataCommand(byte[] data, string cmd, params object[] args)
{
if (socket == null)
Connect();
if (socket == null)
return false;
var s = args.Length > 0 ? String.Format(cmd, args) : cmd;
byte[] r = Encoding.UTF8.GetBytes(s);
try
{
Log("S: " + String.Format(cmd, args));
socket.Send(r);
if (data != null)
{
socket.Send(data);
socket.Send(end_data);
}
}
catch (SocketException)
{
// timeout;
socket.Close();
socket = null;
return false;
}
return true;
}
bool SendCommand(string cmd, params object[] args)
{
if (socket == null)
Connect();
if (socket == null)
return false;
var s = args != null && args.Length > 0 ? String.Format(cmd, args) : cmd;
byte[] r = Encoding.UTF8.GetBytes(s);
try
{
Log("S: " + String.Format(cmd, args));
socket.Send(r);
}
catch (SocketException)
{
// timeout;
socket.Close();
socket = null;
return false;
}
return true;
}
[Conditional("DEBUG")]
void Log(string fmt, params object[] args)
{
Console.WriteLine("{0}", String.Format(fmt, args).Trim());
}
void ExpectSuccess()
{
int c = bstream.ReadByte();
if (c == -1)
throw new ResponseException("No more data");
var s = ReadLine();
Log((char)c + s);
if (c == '-')
throw new ResponseException(s.StartsWith("ERR") ? s.Substring(4) : s);
}
void SendExpectSuccess(string cmd, params object[] args)
{
if (!SendCommand(cmd, args))
throw new Exception("Unable to connect");
ExpectSuccess();
}
int SendDataExpectInt(byte[] data, string cmd, params object[] args)
{
if (!SendDataCommand(data, cmd, args))
throw new Exception("Unable to connect");
int c = bstream.ReadByte();
if (c == -1)
throw new ResponseException("No more data");
var s = ReadLine();
Log("R: " + s);
if (c == '-')
throw new ResponseException(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == ':')
{
int i;
if (int.TryParse(s, out i))
return i;
}
throw new ResponseException("Unknown reply on integer request: " + c + s);
}
int SendExpectInt(string cmd, params object[] args)
{
if (!SendCommand(cmd, args))
throw new Exception("Unable to connect");
int c = bstream.ReadByte();
if (c == -1)
throw new ResponseException("No more data");
var s = ReadLine();
Log("R: " + s);
if (c == '-')
throw new ResponseException(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == ':')
{
int i;
if (int.TryParse(s, out i))
return i;
}
throw new ResponseException("Unknown reply on integer request: " + c + s);
}
string SendExpectString(string cmd, params object[] args)
{
if (!SendCommand(cmd, args))
throw new Exception("Unable to connect");
int c = bstream.ReadByte();
if (c == -1)
throw new ResponseException("No more data");
var s = ReadLine();
Log("R: " + s);
if (c == '-')
throw new ResponseException(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == '+')
return s;
throw new ResponseException("Unknown reply on integer request: " + c + s);
}
//
// This one does not throw errors
//
string SendGetString(string cmd, params object[] args)
{
if (!SendCommand(cmd, args))
throw new Exception("Unable to connect");
return ReadLine();
}
byte[] SendExpectData(byte[] data, string cmd, params object[] args)
{
if (!SendDataCommand(data, cmd, args))
throw new Exception("Unable to connect");
return ReadData();
}
byte[] ReadData()
{
string r = ReadLine();
Log("R: {0}", r);
if (r.Length == 0)
throw new ResponseException("Zero length respose");
char c = r[0];
if (c == '-')
throw new ResponseException(r.StartsWith("-ERR") ? r.Substring(5) : r.Substring(1));
if (c == '$')
{
if (r == "$-1")
return null;
int n;
if (Int32.TryParse(r.Substring(1), out n))
{
byte[] retbuf = new byte[n];
int bytesRead = 0;
do
{
int read = bstream.Read(retbuf, bytesRead, n - bytesRead);
if (read < 1)
throw new ResponseException("Invalid termination mid stream");
bytesRead += read;
}
while (bytesRead < n);
if (bstream.ReadByte() != '\r' || bstream.ReadByte() != '\n')
throw new ResponseException("Invalid termination");
return retbuf;
}
throw new ResponseException("Invalid length");
}
//returns the number of matches
if (c == '*')
{
int n;
if (Int32.TryParse(r.Substring(1), out n))
return n <= 0 ? new byte[0] : ReadData();
throw new ResponseException("Unexpected length parameter" + r);
}
throw new ResponseException("Unexpected reply: " + r);
}
public bool ContainsKey(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("EXISTS " + key + "\r\n") == 1;
}
public bool Remove(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("DEL " + key + "\r\n", key) == 1;
}
public int Remove(params string[] args)
{
if (args == null)
throw new ArgumentNullException("args");
return SendExpectInt("DEL " + string.Join(" ", args) + "\r\n");
}
public int Increment(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("INCR " + key + "\r\n");
}
public int Increment(string key, int count)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("INCRBY {0} {1}\r\n", key, count);
}
public int Decrement(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("DECR " + key + "\r\n");
}
public int Decrement(string key, int count)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("DECRBY {0} {1}\r\n", key, count);
}
public KeyType TypeOf(string key)
{
if (key == null)
throw new ArgumentNullException("key");
switch (SendExpectString("TYPE {0}\r\n", key))
{
case "none":
return KeyType.None;
case "string":
return KeyType.String;
case "set":
return KeyType.Set;
case "list":
return KeyType.List;
}
throw new ResponseException("Invalid value");
}
public string RandomKey()
{
return SendExpectString("RANDOMKEY\r\n");
}
public bool Rename(string oldKeyname, string newKeyname)
{
if (oldKeyname == null)
throw new ArgumentNullException("oldKeyname");
if (newKeyname == null)
throw new ArgumentNullException("newKeyname");
return SendGetString("RENAME {0} {1}\r\n", oldKeyname, newKeyname)[0] == '+';
}
public bool Expire(string key, int seconds)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("EXPIRE {0} {1}\r\n", key, seconds) == 1;
}
public bool ExpireAt(string key, int time)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("EXPIREAT {0} {1}\r\n", key, time) == 1;
}
public int TimeToLive(string key)
{
if (key == null)
throw new ArgumentNullException("key");
return SendExpectInt("TTL {0}\r\n", key);
}
public int DbSize
{
get
{
return SendExpectInt("DBSIZE\r\n");
}
}
public string Save()
{
return SendGetString("SAVE\r\n");
}
public void BackgroundSave()
{
SendGetString("BGSAVE\r\n");
}
public void Shutdown()
{
SendGetString("SHUTDOWN\r\n");
}
public void FlushAll()
{
SendGetString("FLUSHALL\r\n");
}
public void FlushDb()
{
SendGetString("FLUSHDB\r\n");
}
const long UnixEpoch = 621355968000000000L;
public DateTime LastSave
{
get
{
int t = SendExpectInt("LASTSAVE\r\n");
return new DateTime(UnixEpoch) + TimeSpan.FromSeconds(t);
}
}
public Dictionary<string, string> GetInfo()
{
byte[] r = SendExpectData(null, "INFO\r\n");
var dict = new Dictionary<string, string>();
foreach (var line in Encoding.UTF8.GetString(r).Split('\n'))
{
int p = line.IndexOf(':');
if (p == -1)
continue;
dict.Add(line.Substring(0, p), line.Substring(p + 1));
}
return dict;
}
public string[] Keys
{
get
{
string commandResponse = Encoding.UTF8.GetString(SendExpectData(null, "KEYS *\r\n"));
if (commandResponse.Length < 1)
return new string[0];
else
return commandResponse.Split(' ');
}
}
public string[] GetKeys(string pattern)
{
if (pattern == null)
throw new ArgumentNullException("key");
var keys = SendExpectData(null, "KEYS {0}\r\n", pattern);
if (keys.Length == 0)
return new string[0];
return Encoding.UTF8.GetString(keys).Split(' ');
}
public byte[][] GetKeys(params string[] keys)
{
if (keys == null)
throw new ArgumentNullException("key1");
if (keys.Length == 0)
throw new ArgumentException("keys");
return SendDataCommandExpectMultiBulkReply(null, "MGET {0}\r\n", string.Join(" ", keys));
}
public byte[][] SendDataCommandExpectMultiBulkReply(byte[] data, string command, params object[] args)
{
if (!SendDataCommand(data, command, args))
throw new Exception("Unable to connect");
int c = bstream.ReadByte();
if (c == -1)
throw new ResponseException("No more data");
var s = ReadLine();
Log("R: " + s);
if (c == '-')
throw new ResponseException(s.StartsWith("ERR") ? s.Substring(4) : s);
if (c == '*')
{
int count;
if (int.TryParse(s, out count))
{
var result = new byte[count][];
for (int i = 0; i < count; i++)
result[i] = ReadData();
return result;
}
}
throw new ResponseException("Unknown reply on multi-request: " + c + s);
}
#region List commands
public byte[][] ListRange(string key, int start, int end)
{
return SendDataCommandExpectMultiBulkReply(null, "LRANGE {0} {1} {2}\r\n", key, start, end);
}
public void RightPush(string key, string value)
{
SendExpectSuccess("RPUSH {0} {1}\r\n{2}\r\n", key, value.Length, value);
}
public int ListLength(string key)
{
return SendExpectInt("LLEN {0}\r\n", key);
}
public byte[] ListIndex(string key, int index)
{
SendCommand("LINDEX {0} {1}\r\n", key, index);
return ReadData();
}
public byte[] LeftPop(string key)
{
SendCommand("LPOP {0}\r\n", key);
return ReadData();
}
#endregion
#region Set commands
public bool AddToSet(string key, byte[] member)
{
return SendDataExpectInt(member, "SADD {0} {1}\r\n", key, member.Length) > 0;
}
public bool AddToSet(string key, string member)
{
return AddToSet(key, Encoding.UTF8.GetBytes(member));
}
public int CardinalityOfSet(string key)
{
return SendDataExpectInt(null, "SCARD {0}\r\n", key);
}
public bool IsMemberOfSet(string key, byte[] member)
{
return SendDataExpectInt(member, "SISMEMBER {0} {1}\r\n", key, member.Length) > 0;
}
public bool IsMemberOfSet(string key, string member)
{
return IsMemberOfSet(key, Encoding.UTF8.GetBytes(member));
}
public byte[][] GetMembersOfSet(string key)
{
return SendDataCommandExpectMultiBulkReply(null, "SMEMBERS {0}\r\n", key);
}
public byte[] GetRandomMemberOfSet(string key)
{
return SendExpectData(null, "SRANDMEMBER {0}\r\n", key);
}
public byte[] PopRandomMemberOfSet(string key)
{
return SendExpectData(null, "SPOP {0}\r\n", key);
}
public bool RemoveFromSet(string key, byte[] member)
{
return SendDataExpectInt(member, "SREM {0} {1}\r\n", key, member.Length) > 0;
}
public bool RemoveFromSet(string key, string member)
{
return RemoveFromSet(key, Encoding.UTF8.GetBytes(member));
}
public byte[][] GetUnionOfSets(params string[] keys)
{
if (keys == null)
throw new ArgumentNullException();
return SendDataCommandExpectMultiBulkReply(null, "SUNION " + string.Join(" ", keys) + "\r\n");
}
void StoreSetCommands(string cmd, string destKey, params string[] keys)
{
if (String.IsNullOrEmpty(cmd))
throw new ArgumentNullException("cmd");
if (String.IsNullOrEmpty(destKey))
throw new ArgumentNullException("destKey");
if (keys == null)
throw new ArgumentNullException("keys");
SendExpectSuccess("{0} {1} {2}\r\n", cmd, destKey, String.Join(" ", keys));
}
public void StoreUnionOfSets(string destKey, params string[] keys)
{
StoreSetCommands("SUNIONSTORE", destKey, keys);
}
public byte[][] GetIntersectionOfSets(params string[] keys)
{
if (keys == null)
throw new ArgumentNullException();
return SendDataCommandExpectMultiBulkReply(null, "SINTER " + string.Join(" ", keys) + "\r\n");
}
public void StoreIntersectionOfSets(string destKey, params string[] keys)
{
StoreSetCommands("SINTERSTORE", destKey, keys);
}
public byte[][] GetDifferenceOfSets(params string[] keys)
{
if (keys == null)
throw new ArgumentNullException();
return SendDataCommandExpectMultiBulkReply(null, "SDIFF " + string.Join(" ", keys) + "\r\n");
}
public void StoreDifferenceOfSets(string destKey, params string[] keys)
{
StoreSetCommands("SDIFFSTORE", destKey, keys);
}
public bool MoveMemberToSet(string srcKey, string destKey, byte[] member)
{
return SendDataExpectInt(member, "SMOVE {0} {1} {2}\r\n", srcKey, destKey, member.Length) > 0;
}
#endregion
public void Dispose()
{
Dispose(true);
GC.SuppressFinalize(this);
}
~Redis()
{
Dispose(false);
}
protected virtual void Dispose(bool disposing)
{
if (disposing)
{
SendCommand("QUIT\r\n");
socket.Close();
socket = null;
}
}
}
public class SortOptions
{
public string Key { get; set; }
public bool Descending { get; set; }
public bool Lexographically { get; set; }
public Int32 LowerLimit { get; set; }
public Int32 UpperLimit { get; set; }
public string By { get; set; }
public string StoreInKey { get; set; }
public string Get { get; set; }
public string ToCommand()
{
var command = "SORT " + this.Key;
if (LowerLimit != 0 || UpperLimit != 0)
command += " LIMIT " + LowerLimit + " " + UpperLimit;
if (Lexographically)
command += " ALPHA";
if (!string.IsNullOrEmpty(By))
command += " BY " + By;
if (!string.IsNullOrEmpty(Get))
command += " GET " + Get;
if (!string.IsNullOrEmpty(StoreInKey))
command += " STORE " + StoreInKey;
return command;
}
}
| 26.872437 | 106 | 0.535433 | [
"Apache-2.0"
] | Pliner/StackExchange.Redis | MigratedBookSleeveTestSuite/redis-sharp.cs | 23,596 | C# |
// Copyright (C) 2013-2021 Xtensive LLC.
// This code is distributed under MIT license terms.
// See the License.txt file in the project root for more information.
// Created by: Alexey Kulakov
// Created: 2013.08.12
using System.Linq;
using NUnit.Framework;
using Xtensive.Orm.Configuration;
using Xtensive.Orm.Tests.Issues.IssueJira0471_LikeOperatorSupportModel;
using Xtensive.Core;
namespace Xtensive.Orm.Tests.Issues.IssueJira0471_LikeOperatorSupportModel
{
[HierarchyRoot]
public class Customer : Entity
{
[Field, Key]
public long Id { get; private set; }
[Field]
public string FirstName { get; set; }
[Field]
public string LastName { get; set; }
}
}
namespace Xtensive.Orm.Tests.Issues
{
public class IssueJira0471_LikeOperatorSupport : AutoBuildTest
{
[Test]
public void SimlpeOneSymbolTest()
{
using (var session = Domain.OpenSession())
using (var transaction = session.OpenTransaction()) {
var firstQuery = from a in session.Query.All<Customer>()
where a.FirstName.Like("K_le")
select a;
Assert.That(firstQuery.First().FirstName,Is.EqualTo("Kyle"));
}
}
[Test]
public void SimpleSequenceTest()
{
using (var session = Domain.OpenSession())
using (var transaction = session.OpenTransaction()) {
var firstQuery = from a in session.Query.All<Customer>()
where a.FirstName.Like("%xey")
select a;
Assert.That(firstQuery.Count(), Is.EqualTo(4));
}
}
[Test]
public void SimpleSpecialRegExpSimbolsTest()
{
using (var session = Domain.OpenSession())
using (var transaction = session.OpenTransaction()) {
var firstQuery = from a in session.Query.All<Customer>()
where a.LastName.Like("$%")
select a;
Assert.That(firstQuery.First().LastName, Is.EqualTo("$mith"));
}
}
[Test]
public void SimpleEscapeSpecialSymbolsTest()
{
using (var session = Domain.OpenSession())
using (var transaction = session.OpenTransaction()) {
var firstQuery = from a in session.Query.All<Customer>()
where a.FirstName.Like("E!%ric", '!')
select a;
Assert.That(firstQuery.First().FirstName, Is.EqualTo("E%ric"));
}
}
[Test]
public void AllInOneForSqlServerTest()
{
Require.ProviderIs(StorageProvider.SqlServer);
using (var session = Domain.OpenSession())
using (var transaction = session.OpenTransaction()) {
var firstQuery = from a in session.Query.All<Customer>()
where a.LastName.Like("K!%![m%f_", '!')
select a;
Assert.That(firstQuery.First().LastName, Is.EqualTo("K%[maroff"));
}
}
[Test]
public void AllInOneTest()
{
Require.ProviderIsNot(StorageProvider.SqlServer);
using (var session = Domain.OpenSession())
using (var transaction = session.OpenTransaction()) {
var firstQuery = from a in session.Query.All<Customer>()
where a.LastName.Like("K$%[m%f_", '$')
select a;
Assert.That(firstQuery.First().LastName, Is.EqualTo("K%[maroff"));
}
}
protected override DomainConfiguration BuildConfiguration()
{
var configuration = base.BuildConfiguration();
configuration.Types.Register(typeof(Customer).Assembly, typeof(Customer).Namespace);
return configuration;
}
protected override void PopulateData()
{
using (var session = Domain.OpenSession())
using (var transaction = session.OpenTransaction()) {
_ = new Customer { FirstName = "Alexey", LastName = "Kulakov" };
_ = new Customer { FirstName = "Ulexey", LastName = "Kerzhakov" };
_ = new Customer { FirstName = "Klexey", LastName = "Komarov" };
_ = new Customer { FirstName = "Klexey", LastName = "K%[maroff" };
_ = new Customer { FirstName = "Martha", LastName = "$mith" };
_ = new Customer { FirstName = "E%ric", LastName = "Cartman" };
_ = new Customer { FirstName = "Kyle", LastName = "Broflovski" };
transaction.Complete();
}
}
}
}
| 32.115385 | 90 | 0.632096 | [
"MIT"
] | DataObjects-NET/dataobjects-net | Orm/Xtensive.Orm.Tests/Issues/IssueJira0471_LikeOperatorSupport.cs | 4,175 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(SpriteRenderer))]
public class BorderSpriteVisuals : MonoBehaviour {
[SerializeField] private SpriteRenderer _spriteRenderer;
private void Start() {
if (_spriteRenderer == null)
_spriteRenderer = GetComponent<SpriteRenderer>();
ManagerVisuals.I.BorderGrid.Add(_spriteRenderer);
}
} | 26.875 | 61 | 0.737209 | [
"MIT"
] | lightvsdarkness/ImperativeTetro | Assets/Scripts/BorderSpriteVisuals.cs | 432 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See License.txt in the repo root for license information.
// ------------------------------------------------------------
namespace Microsoft.Azure.IIoT.Http {
using Microsoft.Azure.IIoT.Http.Exceptions;
using Microsoft.Azure.IIoT.Exceptions;
using System;
using System.Net;
using System.Text;
/// <summary>
/// Http response extensions
/// </summary>
public static class HttpResponseEx {
/// <summary>
/// Response content
/// </summary>
public static string GetContentAsString(this IHttpResponse response,
Encoding encoding) => encoding.GetString(response.Content);
/// <summary>
/// Response content
/// </summary>
public static string GetContentAsString(this IHttpResponse response) =>
GetContentAsString(response, Encoding.UTF8);
/// <summary>
/// Validate response
/// </summary>
/// <param name="response"></param>
public static void Validate(this IHttpResponse response) {
switch (response.StatusCode) {
case HttpStatusCode.OK:
case HttpStatusCode.Created:
case HttpStatusCode.Accepted:
case HttpStatusCode.NonAuthoritativeInformation:
case HttpStatusCode.NoContent:
case HttpStatusCode.ResetContent:
case HttpStatusCode.PartialContent:
break;
case HttpStatusCode.MethodNotAllowed:
throw new InvalidOperationException(response.GetContentAsString());
case HttpStatusCode.NotAcceptable:
case HttpStatusCode.BadRequest:
throw new BadRequestException(response.GetContentAsString());
case HttpStatusCode.Forbidden:
case HttpStatusCode.Unauthorized:
throw new UnauthorizedAccessException(response.GetContentAsString());
case HttpStatusCode.NotFound:
throw new ResourceNotFoundException(response.GetContentAsString());
case HttpStatusCode.Conflict:
throw new ConflictingResourceException(response.GetContentAsString());
case HttpStatusCode.RequestTimeout:
throw new TimeoutException(response.GetContentAsString());
case HttpStatusCode.PreconditionFailed:
throw new ResourceOutOfDateException(response.GetContentAsString());
case HttpStatusCode.InternalServerError:
case HttpStatusCode.GatewayTimeout:
case HttpStatusCode.ServiceUnavailable:
case HttpStatusCode.TemporaryRedirect:
case (HttpStatusCode)429:
// Retried
throw new HttpTransientException(response.StatusCode,
response.GetContentAsString());
default:
throw new HttpResponseException(response.StatusCode,
response.GetContentAsString());
}
}
/// <summary>
/// Response is not completed
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static bool IsIncomplete(this IHttpResponse response) {
var status = (int)response.StatusCode;
return
(status >= 100 && status <= 199) ||
(status >= 300 && status <= 399);
}
/// <summary>
/// Check whether the response could have a body
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static bool CanHaveBody(this IHttpResponse response) {
switch (response.StatusCode) {
case HttpStatusCode.NotModified:
case HttpStatusCode.NoContent:
case HttpStatusCode.ResetContent:
// HTTP status codes without a body - see RFC 2616
return false;
default:
return true;
}
}
/// <summary>
/// True if request resulted in error
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static bool IsError(this IHttpResponse response) =>
(int)response.StatusCode >= 400 || response.StatusCode == 0;
/// <summary>
/// Error and cannot be retried.
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static bool IsNonRetriableError(this IHttpResponse response) =>
response.IsError() && !response.IsRetriableError();
/// <summary>
/// Technically can be retried
/// </summary>
/// <param name="response"></param>
/// <returns></returns>
public static bool IsRetriableError(this IHttpResponse response) {
switch (response.StatusCode) {
case HttpStatusCode.NotFound:
case HttpStatusCode.RequestTimeout:
case (HttpStatusCode)429:
return true;
default:
return false;
}
}
}
}
| 40.345588 | 99 | 0.554219 | [
"MIT"
] | marcschier/azure-iiot-common | src/Microsoft.Azure.IIoT.Abstractions/src/Http/Extensions/HttpResponseEx.cs | 5,487 | C# |
using System;
using MoonSharp.Interpreter;
namespace GwenNetLua.Control
{
public class RadioButton : CheckBox
{
public static new RadioButton Create(Internal.ControlBase parent)
{
return new RadioButton(new Gwen.Control.RadioButton(parent.Target));
}
[MoonSharpHidden]
public static new RadioButton Create(Gwen.Control.ControlBase control)
{
if (control == null)
return null;
else
return new RadioButton(control);
}
[MoonSharpHidden]
public RadioButton(Gwen.Control.ControlBase control)
: base(control)
{
}
}
}
| 19.310345 | 72 | 0.728571 | [
"MIT"
] | kpalosaa/gwen-net-lua | Library/Portable/Control/RadioButton.cs | 562 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace PowerBIAPI.Models
{
public class PowerBIDataset
{
public string name { get; set; }
public List<Tables> tables { get; set; }
public class Tables
{
public string name { get; set; }
public List<Columns> columns { get; set; }
public class Columns
{
public string name { get; set; }
public string dataType { get; set; }
}
}
}
} | 22.6 | 54 | 0.538053 | [
"Apache-2.0"
] | Velkata/IntorductionToLogicApps_AzureBootcampBulgaria2016 | src/powerbi/PowerBIAPI/Models/PowerBIDataset.cs | 567 | C# |
namespace Teronis.Identity.Entities
{
public interface IBearerUserEntity
{
string Id { get; }
string UserName { get; }
string SecurityStamp { get; }
}
}
| 19 | 38 | 0.6 | [
"MIT"
] | BrunoZell/Teronis.DotNet | src/NetCoreApp/Identity/EntityFrameworkCore/src/Entities/IBearerUserEntity.cs | 192 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.
using System;
using System.Linq;
using System.Net.Http;
using System.Security.Claims;
using System.Security.Principal;
using System.Threading.Tasks;
using Microsoft.Azure.Mobile.Server.Authentication;
using Microsoft.ApplicationInsights;
namespace MyDrivingService.Helpers
{
public static class IdentitiyHelper
{
public static async Task<string> FindSidAsync(IPrincipal claimsPrincipal, HttpRequestMessage request)
{
var aiTelemetry = new TelemetryClient();
var principal = claimsPrincipal as ClaimsPrincipal;
if (principal == null)
{
aiTelemetry.TrackEvent("FindSidAsync: ClaimsPrincipal is null!");
return string.Empty;
}
var match = principal.FindFirst("http://schemas.microsoft.com/identity/claims/identityprovider");
string provider;
if (match != null)
provider = match.Value;
else
{
aiTelemetry.TrackEvent("FindSidAsync: Can't find identity provider");
return string.Empty;
}
ProviderCredentials creds = null;
if (string.Equals(provider, "facebook", StringComparison.OrdinalIgnoreCase))
{
creds = await claimsPrincipal.GetAppServiceIdentityAsync<FacebookCredentials>(request);
}
else if (string.Equals(provider, "microsoftaccount", StringComparison.OrdinalIgnoreCase))
{
creds = await claimsPrincipal.GetAppServiceIdentityAsync<MicrosoftAccountCredentials>(request);
}
else if (string.Equals(provider, "twitter", StringComparison.OrdinalIgnoreCase))
{
creds = await claimsPrincipal.GetAppServiceIdentityAsync<TwitterCredentials>(request);
}
if (creds == null)
{
aiTelemetry.TrackEvent("FindSidAsync: Credentials not found");
return string.Empty;
}
var finalId = $"{creds.Provider}:{creds.UserClaims.First(c => c.Type == ClaimTypes.NameIdentifier).Value}";
return finalId;
}
}
} | 37.822581 | 119 | 0.626439 | [
"MIT"
] | Adhavanbalajiap/MyDriving | src/MobileAppService/MyDrivingService/Helpers/IdentitiyHelper.cs | 2,347 | C# |
using System;
using tree.Classes;
using linked_list.Classes;
namespace tree
{
class Program
{
static void Main(string[] args)
{
TestBinTree();
TestBSTree();
Console.ReadLine();
}
/// <summary>
/// populates BinaryTree for testing
/// </summary>
/// <param name="tree"> tree to populate</param>
/// <returns> populated tree </returns>
public static BinaryTree BuildBinTree(BinaryTree tree)
{
tree.Root = new Node(1);
tree.Root.Left = new Node(2);
tree.Root.Right = new Node(3);
tree.Root.Left.Left = new Node(4);
tree.Root.Left.Right = new Node(5);
tree.Root.Right.Left = new Node(6);
tree.Root.Right.Right = new Node(7);
return tree;
}
/// <summary>
/// populates BinarySearchTree for testing
/// </summary>
/// <param name="tree"> tree to populate</param>
/// <returns> populated tree </returns>
public static BinarySearchTree BuildBSTree(BinarySearchTree tree)
{
tree.Root = new Node(40);
tree.Root.Left = new Node(20);
tree.Root.Right = new Node(60);
tree.Root.Left.Left = new Node(10);
tree.Root.Left.Right = new Node(30);
tree.Root.Right.Left = new Node(50);
tree.Root.Right.Right = new Node(70);
return tree;
}
/// <summary>
/// tests BinaryTree methods
/// </summary>
public static void TestBinTree()
{
Console.WriteLine("Test Binary Tree");
BinaryTree tree = new BinaryTree();
Console.WriteLine("Build tree...");
tree = BuildBinTree(tree);
Console.Write("Check 'PreOrder': ");
PrintTreeValues(tree.PreOrder());
Console.Write("Check 'InOrder': ");
PrintTreeValues(tree.InOrder());
Console.Write("Check 'PostOrder': ");
PrintTreeValues(tree.PostOrder());
}
/// <summary>
/// tests BinarySearchTree methods
/// </summary>
public static void TestBSTree()
{
Console.WriteLine("\n- - - - - -\n");
Console.WriteLine("Test Binary Search Tree");
BinarySearchTree tree = new BinarySearchTree();
tree = BuildBSTree(tree);
Console.WriteLine("Build tree...");
Console.Write("InOrder (original): ");
PrintTreeValues(tree.InOrder());
int value = 63;
Console.WriteLine("Check 'Add'...");
Console.WriteLine($"{value} present? {tree.Contains(value)}");
tree.Add(value);
Console.Write($"InOrder (added {value}): ");
PrintTreeValues(tree.InOrder());
Console.WriteLine("Check 'Contains'...");
Console.WriteLine($"{value} present? {tree.Contains(value)}");
}
/// <summary>
/// prints node values returned by Pre/In/PostOrder method
/// </summary>
/// <param name="tree"></param>
public static void PrintTreeValues(int[] tree)
{
foreach (int value in tree)
{
Console.Write($"{value}=> ");
}
Console.WriteLine();
}
}
}
| 31.981308 | 74 | 0.514904 | [
"MIT"
] | GwennyB/code-challenges-401 | StructuresAndAlgorithms/tree/tree/Program.cs | 3,424 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using NUnit.Framework;
using Simple.Data.Ado;
using Simple.Data.Mocking.Ado;
namespace Simple.Data.IntegrationTest
{
[TestFixture]
public class RangeAndArrayFindTest
{
static Database CreateDatabase(MockDatabase mockDatabase)
{
var mockSchemaProvider = new MockSchemaProvider();
mockSchemaProvider.SetTables(new[] { "dbo", "Users", "BASE TABLE" });
mockSchemaProvider.SetColumns(new[] { "dbo", "Users", "Id" },
new[] { "dbo", "Users", "Name" },
new[] { "dbo", "Users", "Password" },
new[] { "dbo", "Users", "Age" },
new[] { "dbo", "Users", "JoinDate"});
mockSchemaProvider.SetPrimaryKeys(new object[] { "dbo", "Users", "Id", 0 });
return new Database(new AdoAdapter(new MockConnectionProvider(new MockDbConnection(mockDatabase), mockSchemaProvider)));
}
[Test]
public void TestFindByWithIntRange()
{
var mockDatabase = new MockDatabase();
dynamic database = CreateDatabase(mockDatabase);
database.Users.FindAllById(1.to(10)).ToList();
Assert.AreEqual("select [dbo].[users].[id],[dbo].[users].[name],[dbo].[users].[password],[dbo].[users].[age],[dbo].[users].[joindate] from [dbo].[users] where [dbo].[users].[id] between @p1_start and @p1_end".ToLowerInvariant(), mockDatabase.Sql.ToLowerInvariant());
Assert.AreEqual(1, mockDatabase.Parameters[0]);
Assert.AreEqual(10, mockDatabase.Parameters[1]);
}
[Test]
public void TestFindByWithIntArray()
{
var mockDatabase = new MockDatabase();
dynamic database = CreateDatabase(mockDatabase);
database.Users.FindAllById(new[] { 1, 2, 3 }).ToList();
Assert.AreEqual("select [dbo].[users].[id],[dbo].[users].[name],[dbo].[users].[password],[dbo].[users].[age],[dbo].[users].[joindate] from [dbo].[users] where [dbo].[users].[id] in (@p1_0,@p1_1,@p1_2)".ToLowerInvariant(), mockDatabase.Sql.ToLowerInvariant());
Assert.AreEqual(1, mockDatabase.Parameters[0]);
Assert.AreEqual(2, mockDatabase.Parameters[1]);
Assert.AreEqual(3, mockDatabase.Parameters[2]);
}
[Test]
public void TestQueryWithNotEqualIntArray()
{
var mockDatabase = new MockDatabase();
dynamic database = CreateDatabase(mockDatabase);
database.Users.Query().Where(database.Users.Id != new[] { 1, 2, 3 }).ToList();
Assert.AreEqual("select [dbo].[users].[id],[dbo].[users].[name],[dbo].[users].[password],[dbo].[users].[age],[dbo].[users].[joindate] from [dbo].[users] where [dbo].[users].[id] not in (@p1_0,@p1_1,@p1_2)".ToLowerInvariant(), mockDatabase.Sql.ToLowerInvariant());
Assert.AreEqual(1, mockDatabase.Parameters[0]);
Assert.AreEqual(2, mockDatabase.Parameters[1]);
Assert.AreEqual(3, mockDatabase.Parameters[2]);
}
[Test]
public void TestFindByWithDateRange()
{
var mockDatabase = new MockDatabase();
dynamic database = CreateDatabase(mockDatabase);
database.Users.FindAllByJoinDate("2011-01-01".to("2011-01-31")).ToList();
Assert.AreEqual("select [dbo].[users].[id],[dbo].[users].[name],[dbo].[users].[password],[dbo].[users].[age],[dbo].[users].[joindate] from [dbo].[users] where [dbo].[users].[joindate] between @p1_start and @p1_end".ToLowerInvariant(), mockDatabase.Sql.ToLowerInvariant());
Assert.AreEqual(new DateTime(2011,1,1), mockDatabase.Parameters[0]);
Assert.AreEqual(new DateTime(2011,1,31), mockDatabase.Parameters[1]);
}
}
}
| 54.418919 | 285 | 0.586044 | [
"MIT"
] | SimonH/Simple.Data | Simple.Data.BehaviourTest/RangeAndArrayFindTest.cs | 4,029 | C# |
using Caf.Midden.Cli.Common;
using Caf.Midden.Core.Models.v0_2;
using Caf.Midden.Core.Services;
using Caf.Midden.Core.Services.Metadata;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Caf.Midden.Cli.Services
{
public class LocalFileSystemCrawler: ICrawl
{
private const string MIDDEN_FILE_EXTENSION = ".midden";
private const string MIPPEN_FILE_SEARCH_TERM = "DESCRIPTION.md";
private readonly string rootDirectory;
public LocalFileSystemCrawler(string rootDirectory)
{
if (string.IsNullOrEmpty(rootDirectory))
throw new ArgumentNullException("Directory not specified");
if(!Directory.Exists(rootDirectory))
throw new ArgumentNullException("Directory does not exist");
this.rootDirectory = rootDirectory;
}
public List<string> GetFileNames(string fileExtension)
{
string[] files = Directory.GetFiles(
rootDirectory,
$"*{fileExtension}",
SearchOption.AllDirectories);
Console.WriteLine($"Found a total of {files.Length} files");
return files.ToList();
}
public List<Metadata> GetMetadatas(
IMetadataParser parser)
{
var files = GetFileNames(MIDDEN_FILE_EXTENSION);
List<Metadata> metadatas = new List<Metadata>();
foreach (var file in files)
{
string json = File.ReadAllText(file);
Metadata metadata = parser.Parse(json);
string relativePath = Path.GetRelativePath(this.rootDirectory, file);
metadata.Dataset.DatasetPath = relativePath.Replace(MIDDEN_FILE_EXTENSION, "");
metadatas.Add(metadata);
}
return metadatas;
}
public List<Project> GetProjects(
ProjectReader reader)
{
var files = GetFileNames(MIPPEN_FILE_SEARCH_TERM);
List<Project> projects = new List<Project>();
foreach (var file in files)
{
Project project;
using(var stream = File.OpenRead(file))
{
project = reader.Read(stream);
}
if(project is not null)
projects.Add(project);
}
return projects;
}
}
}
| 28.52809 | 95 | 0.582513 | [
"CC0-1.0"
] | GSWRL-USDA-ARS/Midden | Caf.Midden.Cli/Services/LocalFileSystemCrawler.cs | 2,541 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Dispath
{
/// <summary>
/// 提供用于计算指定文件哈希值的方法
/// <example>例如计算文件的MD5值:
/// <code>
/// String hashMd5=HashHelper.ComputeMD5("MyFile.txt");
/// </code>
/// </example>
/// <example>例如计算文件的CRC32值:
/// <code>
/// String hashCrc32 = HashHelper.ComputeCRC32("MyFile.txt");
/// </code>
/// </example>
/// <example>例如计算文件的SHA1值:
/// <code>
/// String hashSha1 =HashHelper.ComputeSHA1("MyFile.txt");
/// </code>
/// </example>
/// </summary>
public sealed class HashHelper
{
/// <summary>
/// 计算指定文件的MD5值
/// </summary>
/// <param name="fileName">指定文件的完全限定名称</param>
/// <returns>返回值的字符串形式</returns>
public static String ComputeMD5(String fileName)
{
String hashMD5 = String.Empty;
//检查文件是否存在,如果文件存在则进行计算,否则返回空值
if (System.IO.File.Exists(fileName))
{
using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
//计算文件的MD5值
System.Security.Cryptography.MD5 calculator = System.Security.Cryptography.MD5.Create();
Byte[] buffer = calculator.ComputeHash(fs);
calculator.Clear();
//将字节数组转换成十六进制的字符串形式
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
{
stringBuilder.Append(buffer[i].ToString("x2"));
}
hashMD5 = stringBuilder.ToString();
}//关闭文件流
}//结束计算
return hashMD5;
}//ComputeMD5
/// <summary>
/// 计算指定文件的CRC32值
/// </summary>
/// <param name="fileName">指定文件的完全限定名称</param>
/// <returns>返回值的字符串形式</returns>
public static String ComputeCRC32(String fileName)
{
String hashCRC32 = String.Empty;
//检查文件是否存在,如果文件存在则进行计算,否则返回空值
if (System.IO.File.Exists(fileName))
{
using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
//计算文件的CSC32值
Crc32 calculator = new Crc32();
Byte[] buffer = calculator.ComputeHash(fs);
calculator.Clear();
//将字节数组转换成十六进制的字符串形式
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
{
stringBuilder.Append(buffer[i].ToString("x2"));
}
hashCRC32 = stringBuilder.ToString();
}//关闭文件流
}
return hashCRC32;
}//ComputeCRC32
/// <summary>
/// 计算指定文件的SHA1值
/// </summary>
/// <param name="fileName">指定文件的完全限定名称</param>
/// <returns>返回值的字符串形式</returns>
public static String ComputeSHA1(String fileName)
{
String hashSHA1 = String.Empty;
//检查文件是否存在,如果文件存在则进行计算,否则返回空值
if (System.IO.File.Exists(fileName))
{
using (System.IO.FileStream fs = new System.IO.FileStream(fileName, System.IO.FileMode.Open, System.IO.FileAccess.Read))
{
//计算文件的SHA1值
System.Security.Cryptography.SHA1 calculator = System.Security.Cryptography.SHA1.Create();
Byte[] buffer = calculator.ComputeHash(fs);
calculator.Clear();
//将字节数组转换成十六进制的字符串形式
StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < buffer.Length; i++)
{
stringBuilder.Append(buffer[i].ToString("x2"));
}
hashSHA1 = stringBuilder.ToString();
}//关闭文件流
}
return hashSHA1;
}//ComputeSHA1
}//end class: HashHelper
/// <summary>
/// 提供 CRC32 算法的实现
/// </summary>
public class Crc32 : System.Security.Cryptography.HashAlgorithm
{
public const UInt32 DefaultPolynomial = 0xedb88320;
public const UInt32 DefaultSeed = 0xffffffff;
private UInt32 hash;
private UInt32 seed;
private UInt32[] table;
private static UInt32[] defaultTable;
public Crc32()
{
table = InitializeTable(DefaultPolynomial);
seed = DefaultSeed;
Initialize();
}
public Crc32(UInt32 polynomial, UInt32 seed)
{
table = InitializeTable(polynomial);
this.seed = seed;
Initialize();
}
public override void Initialize()
{
hash = seed;
}
protected override void HashCore(byte[] buffer, int start, int length)
{
hash = CalculateHash(table, hash, buffer, start, length);
}
protected override byte[] HashFinal()
{
byte[] hashBuffer = UInt32ToBigEndianBytes(~hash);
this.HashValue = hashBuffer;
return hashBuffer;
}
public static UInt32 Compute(byte[] buffer)
{
return ~CalculateHash(InitializeTable(DefaultPolynomial), DefaultSeed, buffer, 0, buffer.Length);
}
public static UInt32 Compute(UInt32 seed, byte[] buffer)
{
return ~CalculateHash(InitializeTable(DefaultPolynomial), seed, buffer, 0, buffer.Length);
}
public static UInt32 Compute(UInt32 polynomial, UInt32 seed, byte[] buffer)
{
return ~CalculateHash(InitializeTable(polynomial), seed, buffer, 0, buffer.Length);
}
private static UInt32[] InitializeTable(UInt32 polynomial)
{
if (polynomial == DefaultPolynomial && defaultTable != null)
{
return defaultTable;
}
UInt32[] createTable = new UInt32[256];
for (int i = 0; i < 256; i++)
{
UInt32 entry = (UInt32)i;
for (int j = 0; j < 8; j++)
{
if ((entry & 1) == 1)
entry = (entry >> 1) ^ polynomial;
else
entry = entry >> 1;
}
createTable[i] = entry;
}
if (polynomial == DefaultPolynomial)
{
defaultTable = createTable;
}
return createTable;
}
private static UInt32 CalculateHash(UInt32[] table, UInt32 seed, byte[] buffer, int start, int size)
{
UInt32 crc = seed;
for (int i = start; i < size; i++)
{
unchecked
{
crc = (crc >> 8) ^ table[buffer[i] ^ crc & 0xff];
}
}
return crc;
}
private byte[] UInt32ToBigEndianBytes(UInt32 x)
{
return new byte[] { (byte)((x >> 24) & 0xff), (byte)((x >> 16) & 0xff), (byte)((x >> 8) & 0xff), (byte)(x & 0xff) };
}
}//end class: Crc32
}
| 34.736111 | 136 | 0.501666 | [
"MIT"
] | lylxiaole/webrtc_remote_win | RemoteWindowWpf/LYL.Common/文件操作/HashHelper.cs | 8,111 | C# |
using System.Runtime.InteropServices;
namespace Vulkan
{
[StructLayout(LayoutKind.Sequential)]
public struct VkEventCreateInfo
{
public VkStructureType SType;
[NativeTypeName("const void *")] public nuint PNext;
[NativeTypeName("VkEventCreateFlags")] public uint Flags;
}
}
| 21.133333 | 65 | 0.697161 | [
"BSD-3-Clause"
] | trmcnealy/Vulkan | Vulkan/Structs/VkEventCreateInfo.cs | 317 | C# |
using System;
using System.IO;
using System.Text;
using Valve.VR;
using Newtonsoft.Json;
namespace SteamVR_WebKit
{
/// <summary>
/// Registers applications to SteamVR/OpenVR and allows to set autostart (starts with SteamVR). A .vrmanifest file is needed.
/// No file is copied. Instead OepnVR is provided with the current working directory. Removing the directory will unregister
/// the application on next start.
/// </summary>
public class SteamVR_Application
{
private string _applicationKey;
private string _manifestFullPath;
private string _manifestFileName;
public SteamVR_Application(string manifestPath = "manifest.vrmanifest")
{
_manifestFullPath = Path.GetFullPath(manifestPath);
_manifestFileName = Path.GetFileName(_manifestFullPath);
string manifestJSON = File.ReadAllText(manifestPath);
JsInterop.Applications.VRManifest manifest = JsonConvert.DeserializeObject<JsInterop.Applications.VRManifest>(manifestJSON);
if (manifest.applications.Count != 0)
{
_applicationKey = manifest.applications[0].app_key;
} else
{
throw new Exception("No application found in VR manifest file: " + _manifestFullPath);
}
}
/// <summary>
/// Installs/Registers the application. This does not copy any files, but instead points OpenVR to the current working directory.
/// </summary>
/// <param name="cleanInstall">If an existing installation is found, setting cleanInstall to true will remove the old registration first (no files are deleted).</param>
/// <param name="autoStart">If true, the registered application will start with SteamVR</param>
public void InstallManifest(bool cleanInstall = false, bool autoStart = true)
{
if (File.Exists(_manifestFullPath))
{
bool alreadyInstalled = false;
if (OpenVR.Applications.IsApplicationInstalled(_applicationKey))
{
Console.WriteLine("Found existing installation.");
if (cleanInstall)
{
StringBuilder buffer = new StringBuilder(1024);
EVRApplicationError appError = new EVRApplicationError();
OpenVR.Applications.GetApplicationPropertyString(_applicationKey, EVRApplicationProperty.WorkingDirectory_String, buffer, 1024, ref appError);
if (appError == EVRApplicationError.None)
{
string oldManifestPath = Path.Combine(buffer.ToString(), _manifestFileName);
if (!_manifestFullPath.Equals(oldManifestPath))
{
Console.WriteLine("Clean install: Removing old manifest.");
OpenVR.Applications.RemoveApplicationManifest(oldManifestPath);
Console.WriteLine(oldManifestPath);
}
else
{
alreadyInstalled = true;
}
}
}
else
{
alreadyInstalled = true;
}
}
else
{
Console.WriteLine("Could not find existing installation. Installing now...");
}
EVRApplicationError error = OpenVR.Applications.AddApplicationManifest(_manifestFullPath, false);
if (error != EVRApplicationError.None)
{
throw new Exception("Could not add application manifest: " + error.ToString());
}
else if (autoStart && (!alreadyInstalled || cleanInstall))
{
error = OpenVR.Applications.SetApplicationAutoLaunch(_applicationKey, true);
if (error != EVRApplicationError.None)
{
throw new Exception("Could not set autostart: " + error.ToString());
}
}
}
else
{
throw new Exception("Could not find application manifest: " + _manifestFullPath);
}
}
/// <summary>
/// Uninstalls/Unregisters the application. No files are deleted.
/// </summary>
public void RemoveManifest()
{
if (File.Exists(_manifestFullPath))
{
if (OpenVR.Applications.IsApplicationInstalled(_applicationKey))
{
EVRApplicationError error = OpenVR.Applications.RemoveApplicationManifest(_manifestFullPath);
if (error != EVRApplicationError.None)
{
throw new Exception("Could not remove application manifest: " + error.ToString());
}
}
}
else
{
throw new Exception("Could not find application manifest: " + _manifestFullPath);
}
}
/// <summary>
/// Sets the autostart property.
/// </summary>
/// <param name="value">If true, the application will start with SteamVR</param>
public void SetAutoStartEnabled(bool value)
{
EVRApplicationError error = OpenVR.Applications.SetApplicationAutoLaunch(_applicationKey, value);
if (error != EVRApplicationError.None)
{
Console.WriteLine("Could not set auto start: " + error.ToString());
}
}
}
} | 44.210526 | 176 | 0.545918 | [
"MIT"
] | BenWoodford/SteamVR-Webkit | SteamVR-WebKit/SteamVR_Application.cs | 5,882 | C# |
using System;
using Foundation;
using UIKit;
using System.Collections.Generic;
namespace KeyboardCompanion
{
public partial class RemoteConfigsListVC : UIViewController
{
RemoteConfigurationsListSource _source;
UIActivityIndicatorView _activityIndicator;
public RemoteConfigsListVC () : base ("RemoteConfigsListVC", null)
{
}
public override void DidReceiveMemoryWarning ()
{
// Releases the view if it doesn't have a superview.
base.DidReceiveMemoryWarning ();
// Release any cached data, images, etc that aren't in use.
}
public override void ViewDidLoad ()
{
base.ViewDidLoad ();
_source = new RemoteConfigurationsListSource ();
_source.OnConfigurationSelected += OnConfigSelected;
RemoteConfigsTable.Source = _source;
RemoteConfigsTable.ReloadData ();
RemoteConfigsTable.TableFooterView = new UIView ();
_activityIndicator = new UIActivityIndicatorView (this.View.Frame);
_activityIndicator.ActivityIndicatorViewStyle = UIActivityIndicatorViewStyle.Gray;
this.NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Done);
this.NavigationItem.RightBarButtonItem.Clicked += (object sender, EventArgs e) => this.DismissViewController(true,null);
}
private async void OnConfigSelected (RepoConfig config)
{
string configZipFile = await ConfigsEngine.ImportFile(config.Path,config.Name);
}
public override void ViewWillAppear (bool animated)
{
base.ViewWillAppear (animated);
RefreshConfigurationsList ();
}
private async void RefreshConfigurationsList()
{
RemoteConfigsTable.Hidden = true;
_activityIndicator.StartAnimating ();
this.Add (_activityIndicator);
var configs = await ConfigsEngine.GetServerConfigurations();
if (configs != null) {
_source.UpdateData (configs);
RemoteConfigsTable.ReloadData ();
}
RemoteConfigsTable.Hidden = false;
_activityIndicator.RemoveFromSuperview ();
}
}
public class RemoteConfigurationsListSource : UITableViewSource
{
List<RepoConfig> _source;
public delegate void ConfigurationSelectedDelegate(RepoConfig config);
public event ConfigurationSelectedDelegate OnConfigurationSelected;
public RemoteConfigurationsListSource ()
{
_source = new List<RepoConfig> ();
}
public override UITableViewCell GetCell (UITableView tableView, NSIndexPath indexPath)
{
UITableViewCell cell = tableView.DequeueReusableCell ("cell");
// if there are no cells to reuse, create a new one
if (cell == null)
cell = new UITableViewCell (UITableViewCellStyle.Default, "cell");
cell.TextLabel.Text = _source [indexPath.Row].Name;
cell.TextLabel.Font = UIFont.FromName ("HelveticaNeue-Light", 18f);
//cell.TextLabel.TextColor = Helpers.DefaultBlue;
return cell;
}
public void UpdateData(List<RepoConfig> data)
{
_source = data;
}
public override nint RowsInSection (UITableView tableview, nint section)
{
return _source.Count;
}
public override void RowSelected (UITableView tableView, NSIndexPath indexPath)
{
tableView.DeselectRow (indexPath,false);
if (OnConfigurationSelected != null) {
OnConfigurationSelected (_source [indexPath.Row]);
}
}
}
}
| 25.3125 | 123 | 0.746914 | [
"Apache-2.0"
] | timefrancesco/touchboard | sources/TouchBoard.ios/ViewControllers/RemoteConfigsListVC.cs | 3,242 | C# |
namespace DigitalLearningSolutions.Web.Tests.Helpers
{
using DigitalLearningSolutions.Web.Helpers;
using FakeItEasy;
using FluentAssertions;
using Microsoft.Extensions.Configuration;
using NUnit.Framework;
class ContentUrlHelperTests
{
private IConfiguration config;
private const string BaseUrl = "https://example.com";
[SetUp]
public void SetUp()
{
config = A.Fake<IConfiguration>();
A.CallTo(() => config["CurrentSystemBaseUrl"]).Returns(BaseUrl);
}
[Test]
public void GetContentPath_should_parse_absolute_url()
{
// Given
const string videoPath = "https://example.com/testVideo.mp4";
// When
var parsedPath = ContentUrlHelper.GetContentPath(config, videoPath);
// Then
parsedPath.Should().Be(videoPath);
}
[Test]
public void GetContentPath_should_parse_protocol_relative_url()
{
// Given
const string videoPath = "example.com/testVideo.mp4";
// When
var parsedPath = ContentUrlHelper.GetContentPath(config, videoPath);
// Then
parsedPath.Should().Be($"https://{videoPath}");
}
[Test]
public void GetContentPath_should_parse_relative_path()
{
// Given
const string videoPath = "/testVideo.mp4";
// When
var parsedPath = ContentUrlHelper.GetContentPath(config, videoPath);
// Then
parsedPath.Should().Be(BaseUrl + videoPath);
}
[TestCase("https://example.com/testVideo.mp4", "https://example.com/testVideo.mp4")]
[TestCase("example.com/testVideo.mp4", "https://example.com/testVideo.mp4")]
[TestCase("/testVideo.mp4", BaseUrl + "/testVideo.mp4")]
[TestCase(null, null)]
public void GetNullableContentPath_should_parse_paths(
string? givenVideoPath,
string? expectedParsedPath
)
{
// When
var actualParsedPath = ContentUrlHelper.GetNullableContentPath(config, givenVideoPath);
// Then
actualParsedPath.Should().Be(expectedParsedPath);
}
}
}
| 30.961039 | 100 | 0.57005 | [
"MIT"
] | TechnologyEnhancedLearning/DLSV2 | DigitalLearningSolutions.Web.Tests/Helpers/ContentUrlHelperTests.cs | 2,386 | C# |
using System.Windows;
using System.Collections.Generic;
namespace ESRI.ArcLogistics.App.Controls
{
/// <summary>
/// Drag pane services
/// </summary>
internal class DragPaneServices
{
#region Members
/// <summary>
/// List of managed surfaces
/// </summary>
private List<IDropSurface> _surfaces = new List<IDropSurface>();
/// <summary>
/// List of managed surfaces with drag over
/// </summary>
private List<IDropSurface> _surfacesWithDragOver = new List<IDropSurface>();
/// <summary>
/// Offset to be use to set floating window screen position
/// </summary>
private Point _offset;
/// <summary>
/// Current managed floating window
/// </summary>
private FloatingWindow _wnd = null;
/// <summary>
/// Get current managed floating window
/// </summary>
public FloatingWindow FloatingWindow
{
get { return _wnd; }
}
#endregion // Members
#region Constructors
/// <summary>
/// Create drag pane services
/// </summary>
public DragPaneServices()
{
}
#endregion // Constructors
#region Public functions
/// <summary>
/// Registry as new drop surface
/// </summary>
/// <param name="surface">Drop suface object</param>
public void Register(IDropSurface surface)
{
if (!_surfaces.Contains(surface))
_surfaces.Add(surface);
}
/// <summary>
/// Unregistry as drop surface
/// </summary>
/// <param name="surface">Drop suface object</param>
public void Unregister(IDropSurface surface)
{
_surfaces.Remove(surface);
}
/// <summary>
/// Start drag routine
/// </summary>
/// <param name="wnd">Floating window to managed</param>
/// <param name="point">Current mouse position</param>
/// <param name="offset">Offset to be use to set floating window screen position</param>
public void StartDrag(FloatingWindow wnd, Point point, Point offset)
{
_wnd = wnd;
_offset = offset;
if (_wnd.Width <= _offset.X)
_offset.X = _wnd.Width / 2;
_wnd.Left = point.X - _offset.X;
_wnd.Top = point.Y - _offset.Y;
if (!_wnd.IsActive)
_wnd.Show();
foreach (IDropSurface surface in _surfaces)
{
if (surface.SurfaceRectangle.Contains(point))
{
_surfacesWithDragOver.Add(surface);
surface.OnDragEnter(point);
}
}
}
/// <summary>
/// Move drag routine
/// </summary>
/// <param name="point">Current mouse position</param>
public void MoveDrag(Point point)
{
if (null == _wnd)
return;
_wnd.Left = point.X - _offset.X;
_wnd.Top = point.Y - _offset.Y;
List<IDropSurface> enteringSurfaces = new List<IDropSurface>();
foreach (IDropSurface surface in _surfaces)
{
if (surface.SurfaceRectangle.Contains(point))
{
if (!_surfacesWithDragOver.Contains(surface))
enteringSurfaces.Add(surface);
else
surface.OnDragOver(point);
}
else if (_surfacesWithDragOver.Contains(surface))
{
_surfacesWithDragOver.Remove(surface);
surface.OnDragLeave(point);
}
}
foreach (IDropSurface surface in enteringSurfaces)
{
_surfacesWithDragOver.Add(surface);
surface.OnDragEnter(point);
}
}
/// <summary>
/// End drag routine
/// </summary>
/// <param name="point">Current mouse position</param>
public void EndDrag(Point point)
{
IDropSurface dropSufrace = null;
foreach (IDropSurface surface in _surfaces)
{
if (!surface.SurfaceRectangle.Contains(point))
continue;
if (surface.OnDrop(point))
{
dropSufrace = surface;
break;
}
}
foreach (IDropSurface surface in _surfacesWithDragOver)
{
if (surface != dropSufrace)
surface.OnDragLeave(point);
}
_surfacesWithDragOver.Clear();
if (null != dropSufrace)
_wnd.Close();
_wnd = null;
}
#endregion // Public functions
}
}
| 29.169591 | 96 | 0.4998 | [
"Apache-2.0"
] | Esri/route-planner-csharp | RoutePlanner_DeveloperTools/Source/ArcLogisticsApp/Controls/DockingLibrary/DragPaneServices.cs | 4,988 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.