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
using System.ComponentModel; using System.Runtime.CompilerServices; using System.Windows.Input; using Xamarin.Forms; using Xamarin.Forms.Internals; namespace smiqs.ViewModels.ErrorAndEmpty { /// <summary> /// ViewModel for something went wrong page. /// </summary> [Preserve(AllMembers = true)] public class SomethingWentWrongPageViewModel : BaseViewModel { #region Fields private string imagePath; private string header; private string content; #endregion #region Constructor /// <summary> /// Initializes a new instance for the <see cref="SomethingWentWrongPageViewModel" /> class. /// </summary> public SomethingWentWrongPageViewModel() { this.ImagePath = "SomethingWentWrong.svg"; this.Header = "SOMETHING WENT WRONG"; this.Content = "We’re not sure what happened, but we know an error occurred"; this.TryAgainCommand = new Command(this.TryAgain); } #endregion #region Commands /// <summary> /// Gets or sets the command that is executed when the TryAgain button is clicked. /// </summary> public ICommand TryAgainCommand { get; set; } #endregion #region Properties /// <summary> /// Gets or sets the ImagePath. /// </summary> public string ImagePath { get { return this.imagePath; } set { this.imagePath = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the Header. /// </summary> public string Header { get { return this.header; } set { this.header = value; this.NotifyPropertyChanged(); } } /// <summary> /// Gets or sets the Content. /// </summary> public string Content { get { return this.content; } set { this.content = value; this.NotifyPropertyChanged(); } } #endregion #region Methods /// <summary> /// Invoked when the TryAgain button is clicked. /// </summary> /// <param name="obj">The Object</param> private void TryAgain(object obj) { // Do something } #endregion } }
22.777778
100
0.500188
[ "MIT" ]
yehiaraslan85/SmiqsMobileApp
smiqs/smiqs/ViewModels/ErrorandEmpty/SomethingWentWrongPageViewModel.cs
2,669
C#
using UnityEngine; using System.Collections; using System; namespace RootMotion.Dynamics { // Switching and blending between Modes public partial class PuppetMaster: MonoBehaviour { /// <summary> /// Returns true if the PuppetMaster is in the middle of blending from a mode to mode. /// </summary> public bool isSwitchingMode { get; private set; } private Mode activeMode; private Mode lastMode; private float mappingBlend = 1f; /// <summary> /// Disables the Puppet immediately without waiting for normal mode switching procedures. /// </summary> public void DisableImmediately() { mappingBlend = 0f; isSwitchingMode = false; activeMode = mode; lastMode = mode; foreach (Muscle m in muscles) { m.rigidbody.gameObject.SetActive(false); } } // Master controller for switching modes. Mode switching is done by simply changing PuppetMaster.mode and can not be interrupted. protected virtual void SwitchModes() { if (!initiated) return; if (isKilling) mode = Mode.Active; if (!isAlive) mode = Mode.Active; foreach (BehaviourBase behaviour in behaviours) { if (behaviour.forceActive) { mode = Mode.Active; break; } } if (mode == lastMode) return; if (isSwitchingMode) return; if (isKilling && mode != Mode.Active) return; if (state != State.Alive && mode != Mode.Active) return; // Enable state switching here or else mapping won't be blended correctly isSwitchingMode = true; if (lastMode == Mode.Disabled) { if (mode == Mode.Kinematic) DisabledToKinematic(); else if (mode == Mode.Active) StartCoroutine(DisabledToActive()); } else if (lastMode == Mode.Kinematic) { if (mode == Mode.Disabled) KinematicToDisabled(); else if (mode == Mode.Active) StartCoroutine(KinematicToActive()); } else if (lastMode == Mode.Active) { if (mode == Mode.Disabled) StartCoroutine(ActiveToDisabled()); else if (mode == Mode.Kinematic) StartCoroutine(ActiveToKinematic()); } lastMode = mode; } // Switch from Disabled to Kinematic mode private void DisabledToKinematic() { foreach (Muscle m in muscles) { m.Reset(); } foreach (Muscle m in muscles) { m.rigidbody.gameObject.SetActive(true); m.rigidbody.isKinematic = true; } internalCollisionsEnabled = true; SetInternalCollisions(internalCollisions); foreach (Muscle m in muscles) { m.MoveToTarget(); } activeMode = Mode.Kinematic; isSwitchingMode = false; } // Blend from Disabled to Active mode private IEnumerator DisabledToActive() { foreach (Muscle m in muscles) { if (!m.rigidbody.gameObject.activeInHierarchy) m.Reset(); } foreach (Muscle m in muscles) { m.rigidbody.gameObject.SetActive(true); m.rigidbody.isKinematic = false; m.rigidbody.velocity = Vector3.zero; m.rigidbody.angularVelocity = Vector3.zero; } internalCollisionsEnabled = true; SetInternalCollisions(internalCollisions); Read(); foreach (Muscle m in muscles) { m.MoveToTarget(); } UpdateInternalCollisions(); while (mappingBlend < 1f) { mappingBlend = Mathf.Clamp(mappingBlend + Time.deltaTime / blendTime, 0f, 1f); yield return null; } activeMode = Mode.Active; isSwitchingMode = false; } // Switch from Kinematic to Disabled private void KinematicToDisabled() { foreach (Muscle m in muscles) { m.rigidbody.gameObject.SetActive(false); } activeMode = Mode.Disabled; isSwitchingMode = false; } // Blend from Kinematic to Active mode private IEnumerator KinematicToActive() { foreach (Muscle m in muscles) { m.rigidbody.isKinematic = false; m.rigidbody.velocity = Vector3.zero; m.rigidbody.angularVelocity = Vector3.zero; } Read(); foreach (Muscle m in muscles) { m.MoveToTarget(); } UpdateInternalCollisions(); while (mappingBlend < 1f) { mappingBlend = Mathf.Min(mappingBlend + Time.deltaTime / blendTime, 1f); yield return null; } activeMode = Mode.Active; isSwitchingMode = false; } // Blend from Active to Disabled mode private IEnumerator ActiveToDisabled() { while (mappingBlend > 0f) { mappingBlend = Mathf.Max(mappingBlend - Time.deltaTime / blendTime, 0f); yield return null; } foreach (Muscle m in muscles) { m.rigidbody.gameObject.SetActive(false); } activeMode = Mode.Disabled; isSwitchingMode = false; } // Blend from Active to Kinematic mode private IEnumerator ActiveToKinematic() { while (mappingBlend > 0f) { mappingBlend = Mathf.Max(mappingBlend - Time.deltaTime / blendTime, 0f); yield return null; } foreach (Muscle m in muscles) { m.rigidbody.isKinematic = true; } foreach (Muscle m in muscles) { m.MoveToTarget(); } activeMode = Mode.Kinematic; isSwitchingMode = false; } private void UpdateInternalCollisions() { if (!internalCollisions) { for (int i = 0; i < muscles.Length; i++) { for (int i2 = i; i2 < muscles.Length; i2++) { if (i != i2) { muscles[i].IgnoreCollisions(muscles[i2], true); } } } } } } }
24.861905
131
0.666347
[ "MIT" ]
eriksk/LD36
Assets/Plugins/RootMotion/PuppetMaster/Scripts/PuppetMasterModes.cs
5,223
C#
using System; using System.Collections.Generic; using System.Text; using UnityEngine; namespace HuaweiMobileServices.Utils { public class AndroidBitmapFactory : JavaObjectWrapper { private const string CLASS_NAME = "android.graphics.BitmapFactory"; private static AndroidJavaClass BitmapFactoryClass = new AndroidJavaClass(CLASS_NAME); public AndroidBitmapFactory(AndroidJavaObject javaObject) : base(javaObject) { } public static AndroidJavaObject DecodeFile (string fileName) => BitmapFactoryClass.CallStatic<AndroidJavaObject>("decodeFile", fileName); } }
30.9
145
0.757282
[ "MIT" ]
EvilMindDevs/hms-sdk-unity
hms-sdk-unity/HuaweiMobileServices/Utils/AndroidBitmapFactory.cs
620
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.ElasticLoadBalancingV2 { /// <summary> /// Provides a Load Balancer Listener Certificate resource. /// /// This resource is for additional certificates and does not replace the default certificate on the listener. /// /// &gt; **Note:** `aws.alb.ListenerCertificate` is known as `aws.lb.ListenerCertificate`. The functionality is identical. /// /// ## Example Usage /// /// /// /// ```csharp /// using Pulumi; /// using Aws = Pulumi.Aws; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var exampleCertificate = new Aws.Acm.Certificate("exampleCertificate", new Aws.Acm.CertificateArgs /// { /// }); /// var frontEndLoadBalancer = new Aws.LB.LoadBalancer("frontEndLoadBalancer", new Aws.LB.LoadBalancerArgs /// { /// }); /// var frontEndListener = new Aws.LB.Listener("frontEndListener", new Aws.LB.ListenerArgs /// { /// }); /// var exampleListenerCertificate = new Aws.LB.ListenerCertificate("exampleListenerCertificate", new Aws.LB.ListenerCertificateArgs /// { /// CertificateArn = exampleCertificate.Arn, /// ListenerArn = frontEndListener.Arn, /// }); /// } /// /// } /// ``` /// </summary> [Obsolete(@"aws.elasticloadbalancingv2.ListenerCertificate has been deprecated in favor of aws.lb.ListenerCertificate")] public partial class ListenerCertificate : Pulumi.CustomResource { /// <summary> /// The ARN of the certificate to attach to the listener. /// </summary> [Output("certificateArn")] public Output<string> CertificateArn { get; private set; } = null!; /// <summary> /// The ARN of the listener to which to attach the certificate. /// </summary> [Output("listenerArn")] public Output<string> ListenerArn { get; private set; } = null!; /// <summary> /// Create a ListenerCertificate resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public ListenerCertificate(string name, ListenerCertificateArgs args, CustomResourceOptions? options = null) : base("aws:elasticloadbalancingv2/listenerCertificate:ListenerCertificate", name, args ?? new ListenerCertificateArgs(), MakeResourceOptions(options, "")) { } private ListenerCertificate(string name, Input<string> id, ListenerCertificateState? state = null, CustomResourceOptions? options = null) : base("aws:elasticloadbalancingv2/listenerCertificate:ListenerCertificate", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing ListenerCertificate resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static ListenerCertificate Get(string name, Input<string> id, ListenerCertificateState? state = null, CustomResourceOptions? options = null) { return new ListenerCertificate(name, id, state, options); } } public sealed class ListenerCertificateArgs : Pulumi.ResourceArgs { /// <summary> /// The ARN of the certificate to attach to the listener. /// </summary> [Input("certificateArn", required: true)] public Input<string> CertificateArn { get; set; } = null!; /// <summary> /// The ARN of the listener to which to attach the certificate. /// </summary> [Input("listenerArn", required: true)] public Input<string> ListenerArn { get; set; } = null!; public ListenerCertificateArgs() { } } public sealed class ListenerCertificateState : Pulumi.ResourceArgs { /// <summary> /// The ARN of the certificate to attach to the listener. /// </summary> [Input("certificateArn")] public Input<string>? CertificateArn { get; set; } /// <summary> /// The ARN of the listener to which to attach the certificate. /// </summary> [Input("listenerArn")] public Input<string>? ListenerArn { get; set; } public ListenerCertificateState() { } } }
40.217687
167
0.612483
[ "ECL-2.0", "Apache-2.0" ]
JakeGinnivan/pulumi-aws
sdk/dotnet/ElasticLoadBalancingV2/ListenerCertificate.cs
5,912
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Net.Sockets; using System.Text; namespace System.Net { internal class IPAddressParser { internal const int IPv4AddressBytes = 4; internal const int IPv6AddressBytes = 16; internal const int INET_ADDRSTRLEN = 22; internal const int INET6_ADDRSTRLEN = 65; internal static IPAddress Parse(string ipString, bool tryParse) { if (ipString == null) { if (tryParse) { return null; } throw new ArgumentNullException("ipString"); } uint error = 0; // IPv6 Changes: Detect probable IPv6 addresses and use separate // parse method. if (ipString.IndexOf(':') != -1) { // If the address string contains the colon character // then it can only be an IPv6 address. Use a separate // parse method to unpick it all. Note: we don't support // port specification at the end of address and so can // make this decision. uint scope = 0; ushort port = 0; byte[] bytes = new byte[IPv6AddressBytes]; error = Interop.NtDll.RtlIpv6StringToAddressExW(ipString, bytes, out scope, out port); if (error == Interop.StatusOptions.STATUS_SUCCESS) { // AppCompat: .Net 4.5 ignores a correct port if the address was specified in brackes. // Will still throw for an incorrect port. return new IPAddress(bytes, (long)scope); } } else { ushort port = 0; byte[] bytes = new byte[IPv4AddressBytes]; error = Interop.NtDll.RtlIpv4StringToAddressExW(ipString, false, bytes, out port); if (error == 0) { if (port != 0) { throw new FormatException(SR.dns_bad_ip_address); } return new IPAddress(bytes); } } if (tryParse) { return null; } Exception e = new SocketException(NtStatusToSocketErrorAdapter(error)); throw new FormatException(SR.dns_bad_ip_address, e); } internal static string IPv4AddressToString(byte[] numbers) { uint errorCode = 0; StringBuilder sb = new StringBuilder(INET_ADDRSTRLEN); uint length = (uint)sb.Capacity; errorCode = Interop.NtDll.RtlIpv4AddressToStringExW(numbers, 0, sb, ref length); if (errorCode == Interop.StatusOptions.STATUS_SUCCESS) { return sb.ToString(); } else { throw new SocketException(NtStatusToSocketErrorAdapter(errorCode)); } } internal static string IPv6AddressToString(byte[] numbers, UInt32 scopeId) { uint errorCode = 0; StringBuilder sb = new StringBuilder(INET6_ADDRSTRLEN); uint length = (uint)sb.Capacity; errorCode = Interop.NtDll.RtlIpv6AddressToStringExW(numbers, scopeId, 0, sb, ref length); if (errorCode == Interop.StatusOptions.STATUS_SUCCESS) { return sb.ToString(); } else { throw new SocketException(NtStatusToSocketErrorAdapter(errorCode)); } } private static SocketError NtStatusToSocketErrorAdapter(uint status) { switch (status) { case Interop.StatusOptions.STATUS_SUCCESS: return SocketError.Success; case Interop.StatusOptions.STATUS_INVALID_PARAMETER: return SocketError.InvalidArgument; default: return (SocketError)status; } } } }
32.847328
106
0.525215
[ "MIT" ]
fffej/corefx
src/System.Net.Primitives/src/System/Net/IPAddressParser.cs
4,303
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.ML.Data; using System; using System.Collections.Generic; using System.Linq; namespace Microsoft.ML.AutoML.Test { public enum TaskType { Classification = 1, Regression = 2, Recommendation = 3, Ranking = 4 } /// <summary> /// make AutoFit and Score calls uniform across task types /// </summary> internal class TaskAgnosticAutoFit { private TaskType _taskType; private MLContext _context; internal interface IUniversalProgressHandler : IProgress<RunDetail<RegressionMetrics>>, IProgress<RunDetail<MulticlassClassificationMetrics>> { } internal TaskAgnosticAutoFit(TaskType taskType, MLContext context) { this._taskType = taskType; this._context = context; } internal IEnumerable<TaskAgnosticIterationResult> AutoFit( IDataView trainData, string label, int maxModels, uint maxExperimentTimeInSeconds, IDataView validationData = null, IEstimator<ITransformer> preFeaturizers = null, IEnumerable<(string, ColumnPurpose)> columnPurposes = null, IUniversalProgressHandler progressHandler = null) { var columnInformation = new ColumnInformation() { LabelColumnName = label }; switch (this._taskType) { case TaskType.Classification: var mcs = new MulticlassExperimentSettings { OptimizingMetric = MulticlassClassificationMetric.MicroAccuracy, MaxExperimentTimeInSeconds = maxExperimentTimeInSeconds, MaxModels = maxModels }; var classificationResult = this._context.Auto() .CreateMulticlassClassificationExperiment(mcs) .Execute( trainData, validationData, columnInformation, progressHandler: progressHandler); var iterationResults = classificationResult.RunDetails.Select(i => new TaskAgnosticIterationResult(i)).ToList(); return iterationResults; case TaskType.Regression: var rs = new RegressionExperimentSettings { OptimizingMetric = RegressionMetric.RSquared, MaxExperimentTimeInSeconds = maxExperimentTimeInSeconds, MaxModels = maxModels }; var regressionResult = this._context.Auto() .CreateRegressionExperiment(rs) .Execute( trainData, validationData, columnInformation, progressHandler: progressHandler); iterationResults = regressionResult.RunDetails.Select(i => new TaskAgnosticIterationResult(i)).ToList(); return iterationResults; case TaskType.Recommendation: var recommendationSettings = new RecommendationExperimentSettings { OptimizingMetric = RegressionMetric.RSquared, MaxExperimentTimeInSeconds = maxExperimentTimeInSeconds, MaxModels = maxModels }; var recommendationResult = this._context.Auto() .CreateRecommendationExperiment(recommendationSettings) .Execute( trainData, validationData, columnInformation, progressHandler: progressHandler); iterationResults = recommendationResult.RunDetails.Select(i => new TaskAgnosticIterationResult(i)).ToList(); return iterationResults; default: throw new ArgumentException($"Unknown task type {this._taskType}.", "TaskType"); } } internal struct ScoreResult { public IDataView ScoredTestData; public double PrimaryMetricResult; public Dictionary<string, double> Metrics; } internal ScoreResult Score( IDataView testData, ITransformer model, string label) { var result = new ScoreResult(); result.ScoredTestData = model.Transform(testData); switch (this._taskType) { case TaskType.Classification: var classificationMetrics = _context.MulticlassClassification.Evaluate(result.ScoredTestData, labelColumnName: label); //var classificationMetrics = context.MulticlassClassification.(scoredTestData, labelColumnName: label); result.PrimaryMetricResult = classificationMetrics.MicroAccuracy; // TODO: don't hardcode metric result.Metrics = TaskAgnosticIterationResult.MetricValuesToDictionary(classificationMetrics); break; case TaskType.Regression: var regressionMetrics = _context.Regression.Evaluate(result.ScoredTestData, labelColumnName: label); result.PrimaryMetricResult = regressionMetrics.RSquared; // TODO: don't hardcode metric result.Metrics = TaskAgnosticIterationResult.MetricValuesToDictionary(regressionMetrics); break; default: throw new ArgumentException($"Unknown task type {this._taskType}.", "TaskType"); } return result; } } }
36.449704
149
0.566558
[ "MIT" ]
1Crazymoney/machinelearning
test/Microsoft.ML.AutoML.Tests/Utils/TaskAgnosticAutoFit.cs
6,162
C#
using System.ComponentModel.DataAnnotations; using Helixbase.Foundation.Models.Mediators; namespace Helixbase.Foundation.Core.Services { public interface IMediatorService { MediatorResponse<T> GetMediatorResponse<T>(string code, T viewModel = default(T), ValidationResult validationResult = null, object parameters = null, string message = null); } }
32.083333
103
0.748052
[ "MIT" ]
Sitecore-Hackathon/2018-Debug-Starts-Here
src/Foundation/Core/code/Services/IMediatorService.cs
387
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the iot-2015-05-28.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.IoT.Model { /// <summary> /// Container for the parameters to the CreateDomainConfiguration operation. /// Creates a domain configuration. /// /// <note> /// <para> /// The domain configuration feature is in public preview and is subject to change. /// </para> /// </note> /// </summary> public partial class CreateDomainConfigurationRequest : AmazonIoTRequest { private AuthorizerConfig _authorizerConfig; private string _domainConfigurationName; private string _domainName; private List<string> _serverCertificateArns = new List<string>(); private ServiceType _serviceType; private List<Tag> _tags = new List<Tag>(); private string _validationCertificateArn; /// <summary> /// Gets and sets the property AuthorizerConfig. /// <para> /// An object that specifies the authorization service for a domain. /// </para> /// </summary> public AuthorizerConfig AuthorizerConfig { get { return this._authorizerConfig; } set { this._authorizerConfig = value; } } // Check to see if AuthorizerConfig property is set internal bool IsSetAuthorizerConfig() { return this._authorizerConfig != null; } /// <summary> /// Gets and sets the property DomainConfigurationName. /// <para> /// The name of the domain configuration. This value must be unique to a region. /// </para> /// </summary> [AWSProperty(Required=true, Min=1, Max=128)] public string DomainConfigurationName { get { return this._domainConfigurationName; } set { this._domainConfigurationName = value; } } // Check to see if DomainConfigurationName property is set internal bool IsSetDomainConfigurationName() { return this._domainConfigurationName != null; } /// <summary> /// Gets and sets the property DomainName. /// <para> /// The name of the domain. /// </para> /// </summary> [AWSProperty(Min=1, Max=253)] public string DomainName { get { return this._domainName; } set { this._domainName = value; } } // Check to see if DomainName property is set internal bool IsSetDomainName() { return this._domainName != null; } /// <summary> /// Gets and sets the property ServerCertificateArns. /// <para> /// The ARNs of the certificates that AWS IoT passes to the device during the TLS handshake. /// Currently you can specify only one certificate ARN. This value is not required for /// AWS-managed domains. /// </para> /// </summary> [AWSProperty(Min=0, Max=1)] public List<string> ServerCertificateArns { get { return this._serverCertificateArns; } set { this._serverCertificateArns = value; } } // Check to see if ServerCertificateArns property is set internal bool IsSetServerCertificateArns() { return this._serverCertificateArns != null && this._serverCertificateArns.Count > 0; } /// <summary> /// Gets and sets the property ServiceType. /// <para> /// The type of service delivered by the endpoint. /// </para> /// <note> /// <para> /// AWS IoT Core currently supports only the <code>DATA</code> service type. /// </para> /// </note> /// </summary> public ServiceType ServiceType { get { return this._serviceType; } set { this._serviceType = value; } } // Check to see if ServiceType property is set internal bool IsSetServiceType() { return this._serviceType != null; } /// <summary> /// Gets and sets the property Tags. /// <para> /// Metadata which can be used to manage the domain configuration. /// </para> /// <note> /// <para> /// For URI Request parameters use format: ...key1=value1&amp;key2=value2... /// </para> /// /// <para> /// For the CLI command-line parameter use format: &amp;&amp;tags "key1=value1&amp;key2=value2..." /// </para> /// /// <para> /// For the cli-input-json file use format: "tags": "key1=value1&amp;key2=value2..." /// </para> /// </note> /// </summary> public List<Tag> Tags { get { return this._tags; } set { this._tags = value; } } // Check to see if Tags property is set internal bool IsSetTags() { return this._tags != null && this._tags.Count > 0; } /// <summary> /// Gets and sets the property ValidationCertificateArn. /// <para> /// The certificate used to validate the server certificate and prove domain name ownership. /// This certificate must be signed by a public certificate authority. This value is not /// required for AWS-managed domains. /// </para> /// </summary> [AWSProperty(Min=1, Max=2048)] public string ValidationCertificateArn { get { return this._validationCertificateArn; } set { this._validationCertificateArn = value; } } // Check to see if ValidationCertificateArn property is set internal bool IsSetValidationCertificateArn() { return this._validationCertificateArn != null; } } }
33.014706
106
0.582777
[ "Apache-2.0" ]
KenHundley/aws-sdk-net
sdk/src/Services/IoT/Generated/Model/CreateDomainConfigurationRequest.cs
6,735
C#
// Copyright (c) Aaron Reynolds. All rights reserved. Licensed under the Apache License, Version 2.0. using Microsoft.Extensions.Options; namespace Educ8IT.AspNetCore.SimpleApi.Authentication.BearerScheme { /// <summary> /// /// </summary> public class BearerAuthenticationPostConfigureOptions : IPostConfigureOptions<BearerAuthenticationOptions> { /// <summary> /// /// </summary> /// <param name="name"></param> /// <param name="options"></param> public void PostConfigure(string name, BearerAuthenticationOptions options) { } } }
27.26087
110
0.642743
[ "Apache-2.0" ]
AaronReynoldsUK/Educ8IT.AspNetCore.SimpleApi
Educ8IT.AspNetCore.SimpleApi.Authentication/BearerScheme/BearerAuthenticationPostConfigureOptions.cs
629
C#
namespace Easy.Common.Extensions { using System; using System.Diagnostics; using System.IO; using System.Linq; using System.Reflection; using System.Runtime.Versioning; /// <summary> /// A set of extension methods for <see cref="Assembly"/>. /// </summary> public static class AssemblyExtensions { /// <summary> /// Obtains the .NET framework version against which the <paramref name="assembly"/> has been built. /// </summary> /// <param name="assembly">The assembly</param> /// <returns>The .NET framework version</returns> public static string GetFrameworkVersion(this Assembly assembly) { var targetFrameAttribute = assembly.GetCustomAttributes(true) .OfType<TargetFrameworkAttribute>().FirstOrDefault(); if (targetFrameAttribute is null) { return ".NET 2, 3 or 3.5"; } return targetFrameAttribute.FrameworkName; } /// <summary> /// Obtains the location from which the <paramref name="assembly"/> was loaded. /// <remarks> /// <para> /// The <c>CodeBase</c> is a URL to the place where the file was found, while the <c>Location</c> is /// the path from where it was actually loaded. For example, if the assembly was downloaded from the /// web, its <c>CodeBase</c> may start with “http://”, but its <c>Location</c> may start with “C:\”. /// If the file was shadow copied, the <c>Location</c> would be the path to the copy of the file in the /// shadow-copy directory. /// </para> /// <para> /// Note that the <c>CodeBase</c> is not guaranteed to be set for assemblies in the GAC. /// <c>Location</c> will always be set for assemblies loaded from disk however. /// </para> /// </remarks> /// </summary> /// <param name="assembly">The assembly for which location is returned</param> /// <returns>The location as <see cref="DirectoryInfo"/></returns> public static DirectoryInfo GetAssemblyLocation(this Assembly assembly) => // ReSharper disable once AssignNullToNotNullAttribute new DirectoryInfo(Path.GetDirectoryName(assembly.Location)); /// <summary> /// Obtains the location from which the <paramref name="assembly"/> was found. /// <remarks> /// <para> /// The <c>CodeBase</c> is a URL to the place where the file was found, while the <c>Location</c> is /// the path from where it was actually loaded. For example, if the assembly was downloaded from the /// web, its <c>CodeBase</c> may start with “http://”, but its <c>Location</c> may start with “C:\”. /// If the file was shadow copied, the <c>Location</c> would be the path to the copy of the file in the /// shadow-copy directory. /// </para> /// <para> /// Note that the <c>CodeBase</c> is not guaranteed to be set for assemblies in the GAC. /// <c>Location</c> will always be set for assemblies loaded from disk however. /// </para> /// </remarks> /// </summary> /// <param name="assembly">The assembly for which location is returned</param> /// <returns>The location as <see cref="DirectoryInfo"/></returns> public static DirectoryInfo GetAssemblyCodeBase(this Assembly assembly) { var uri = new Uri(assembly.CodeBase); // ReSharper disable once AssignNullToNotNullAttribute return new DirectoryInfo(Path.GetDirectoryName(uri.LocalPath)); } /// <summary> /// Determines whether the given <paramref name="assembly"/> has been compiled in <c>Release</c> mode. /// Credit to: <see href="http://www.hanselman.com/blog/HowToProgrammaticallyDetectIfAnAssemblyIsCompiledInDebugOrReleaseMode.aspx"/> /// </summary> /// <param name="assembly">The assembly to examine</param> /// <returns><c>True</c> if the <paramref name="assembly"/> is optimized otherwise <c>False</c></returns> public static bool IsOptimized(this Assembly assembly) { var attributes = assembly.GetCustomAttributes(typeof(DebuggableAttribute), false); if (attributes.Length == 0) { return true; } foreach (Attribute attr in attributes) { if (attr is DebuggableAttribute) { var d = attr as DebuggableAttribute; // FYI // "Run time Optimizer is enabled: " + !d.IsJITOptimizerDisabled // "Run time Tracking is enabled: " + d.IsJITTrackingEnabled if (d.IsJITOptimizerDisabled) { return false; } return true; } } return false; } /// <summary> /// Gets the flag indicating whether the given <paramref name="assembly"/> is <c>32-bit</c>. /// </summary> public static bool Is32Bit(this Assembly assembly) { Ensure.NotNull(assembly, nameof(assembly)); var location = assembly.Location; if (location.IsNullOrEmptyOrWhiteSpace()) { location = assembly.CodeBase; } var uri = new Uri(location); Ensure.That(uri.IsFile, "Assembly location is not a file."); var assemblyName = AssemblyName.GetAssemblyName(uri.LocalPath); return assemblyName.ProcessorArchitecture == ProcessorArchitecture.X86; } /// <summary> /// Queries the assembly's headers to find if it is <c>LARGEADDRESSAWARE</c>. /// <remarks>The method is equivalent to running <c>DumpBin</c> on the assembly.</remarks> /// </summary> public static bool IsAssemblyLargeAddressAware(this Assembly assembly) => ApplicationHelper.IsLargeAddressAware(assembly.Location); } }
47.393701
141
0.60226
[ "MIT" ]
felipebaltazar/Easy.Common
Easy.Common/Extensions/AssemblyExtensions.cs
6,037
C#
using System.Collections.Specialized; using System.ComponentModel; using System.Configuration; namespace SuperScript.Configuration { public class EmitterBundleElement : ConfigurationElement { private static readonly ConfigurationProperty CustomObjectElement = new ConfigurationProperty("customObject", typeof(CustomObjectElement), null, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty PostModifiersElement = new ConfigurationProperty("postModifiers", typeof (PostModifiersCollection), null, ConfigurationPropertyOptions.None); private static readonly ConfigurationProperty WritersElement = new ConfigurationProperty("writers", typeof (WritersCollection), null, ConfigurationPropertyOptions.None); [ConfigurationProperty("bundleKeys", IsRequired = true)] [TypeConverter(typeof (CommaDelimitedStringCollectionConverter))] public StringCollection BundleKeys { get { return (CommaDelimitedStringCollection) this["bundleKeys"]; } } [ConfigurationProperty("customObject", IsRequired = false)] public CustomObjectElement CustomObject { get { return (CustomObjectElement) this[CustomObjectElement]; } } [ConfigurationProperty("key", IsRequired = true)] public string Key { get { return (string) this["key"]; } } [ConfigurationProperty("postModifiers", IsRequired = false)] public PostModifiersCollection PostModifiers { get { return (PostModifiersCollection) this[PostModifiersElement]; } } [ConfigurationProperty("writers", IsRequired = true)] public WritersCollection Writers { get { return (WritersCollection) this[WritersElement]; } } } }
37.295455
189
0.789762
[ "MIT" ]
Supertext/SuperScript.Common
Configuration/Classes/ForEmitterBundles/EmitterBundleElement.cs
1,643
C#
using UnityEngine; namespace GameGlue { [CreateAssetMenu(fileName = "GameEventFloat", menuName = "GameGlue/GameEventFloat", order = 0)] public class GameEventFloat : GameEventBase<float> { } }
21
99
0.709524
[ "MIT" ]
Draudastic26/usefulkit
usefulkit-unity/Assets/UsefulKit/Runtime/GameGlue/Eventsystem/GameEventFloat.cs
210
C#
using Microsoft.EntityFrameworkCore.Migrations; using System; using System.Collections.Generic; namespace Monifier.Web.Migrations { public partial class ExpenseFlowVersion : Migration { protected override void Up(MigrationBuilder migrationBuilder) { migrationBuilder.AddColumn<int>( name: "Version", table: "ExpenseFlows", nullable: false, defaultValue: 0); } protected override void Down(MigrationBuilder migrationBuilder) { migrationBuilder.DropColumn( name: "Version", table: "ExpenseFlows"); } } }
27.307692
72
0.571831
[ "MIT" ]
Ivan-Proskurin/Monifier
Monifier.Web/Migrations/20180102083141_ExpenseFlowVersion.cs
712
C#
namespace Ocelot.Configuration.Validator { using Errors; using File; using FluentValidation; using Microsoft.Extensions.DependencyInjection; using Responses; using ServiceDiscovery; using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; public class FileConfigurationFluentValidator : AbstractValidator<FileConfiguration>, IConfigurationValidator { private readonly List<ServiceDiscoveryFinderDelegate> _serviceDiscoveryFinderDelegates; public FileConfigurationFluentValidator(IServiceProvider provider, ReRouteFluentValidator reRouteFluentValidator, FileGlobalConfigurationFluentValidator fileGlobalConfigurationFluentValidator) { _serviceDiscoveryFinderDelegates = provider .GetServices<ServiceDiscoveryFinderDelegate>() .ToList(); RuleFor(configuration => configuration.ReRoutes) .SetCollectionValidator(reRouteFluentValidator); RuleFor(configuration => configuration.GlobalConfiguration) .SetValidator(fileGlobalConfigurationFluentValidator); RuleForEach(configuration => configuration.ReRoutes) .Must((config, reRoute) => IsNotDuplicateIn(reRoute, config.ReRoutes)) .WithMessage((config, reRoute) => $"{nameof(reRoute)} {reRoute.UpstreamPathTemplate} has duplicate"); RuleForEach(configuration => configuration.ReRoutes) .Must((config, reRoute) => HaveServiceDiscoveryProviderRegistered(reRoute, config.GlobalConfiguration.ServiceDiscoveryProvider)) .WithMessage((config, reRoute) => $"Unable to start Ocelot, errors are: Unable to start Ocelot because either a ReRoute or GlobalConfiguration are using ServiceDiscoveryOptions but no ServiceDiscoveryFinderDelegate has been registered in dependency injection container. Are you missing a package like Ocelot.Provider.Consul and services.AddConsul() or Ocelot.Provider.Eureka and services.AddEureka()?"); RuleFor(configuration => configuration.GlobalConfiguration.ServiceDiscoveryProvider) .Must(HaveServiceDiscoveryProviderRegistered) .WithMessage((config, reRoute) => $"Unable to start Ocelot, errors are: Unable to start Ocelot because either a ReRoute or GlobalConfiguration are using ServiceDiscoveryOptions but no ServiceDiscoveryFinderDelegate has been registered in dependency injection container. Are you missing a package like Ocelot.Provider.Consul and services.AddConsul() or Ocelot.Provider.Eureka and services.AddEureka()?"); RuleForEach(configuration => configuration.ReRoutes) .Must((config, reRoute) => IsNotDuplicateIn(reRoute, config.Aggregates)) .WithMessage((config, reRoute) => $"{nameof(reRoute)} {reRoute.UpstreamPathTemplate} has duplicate aggregate"); RuleForEach(configuration => configuration.Aggregates) .Must((config, aggregateReRoute) => IsNotDuplicateIn(aggregateReRoute, config.Aggregates)) .WithMessage((config, aggregate) => $"{nameof(aggregate)} {aggregate.UpstreamPathTemplate} has duplicate aggregate"); RuleForEach(configuration => configuration.Aggregates) .Must((config, aggregateReRoute) => AllReRoutesForAggregateExist(aggregateReRoute, config.ReRoutes)) .WithMessage((config, aggregateReRoute) => $"ReRoutes for {nameof(aggregateReRoute)} {aggregateReRoute.UpstreamPathTemplate} either do not exist or do not have correct ServiceName property"); RuleForEach(configuration => configuration.Aggregates) .Must((config, aggregateReRoute) => DoesNotContainReRoutesWithSpecificRequestIdKeys(aggregateReRoute, config.ReRoutes)) .WithMessage((config, aggregateReRoute) => $"{nameof(aggregateReRoute)} {aggregateReRoute.UpstreamPathTemplate} contains ReRoute with specific RequestIdKey, this is not possible with Aggregates"); } private bool HaveServiceDiscoveryProviderRegistered(FileReRoute reRoute, FileServiceDiscoveryProvider serviceDiscoveryProvider) { if (string.IsNullOrEmpty(reRoute.ServiceName)) { return true; } if (serviceDiscoveryProvider?.Type?.ToLower() == "servicefabric") { return true; } return _serviceDiscoveryFinderDelegates.Any(); } private bool HaveServiceDiscoveryProviderRegistered(FileServiceDiscoveryProvider serviceDiscoveryProvider) { if (serviceDiscoveryProvider == null) { return true; } if (serviceDiscoveryProvider?.Type?.ToLower() == "servicefabric") { return true; } return string.IsNullOrEmpty(serviceDiscoveryProvider.Type) || _serviceDiscoveryFinderDelegates.Any(); } public async Task<Response<ConfigurationValidationResult>> IsValid(FileConfiguration configuration) { var validateResult = await ValidateAsync(configuration); if (validateResult.IsValid) { return new OkResponse<ConfigurationValidationResult>(new ConfigurationValidationResult(false)); } var errors = validateResult.Errors.Select(failure => new FileValidationFailedError(failure.ErrorMessage)); var result = new ConfigurationValidationResult(true, errors.Cast<Error>().ToList()); return new OkResponse<ConfigurationValidationResult>(result); } private bool AllReRoutesForAggregateExist(FileAggregateReRoute fileAggregateReRoute, List<FileReRoute> reRoutes) { var reRoutesForAggregate = reRoutes.Where(r => fileAggregateReRoute.ReRouteKeys.Contains(r.Key)); return reRoutesForAggregate.Count() == fileAggregateReRoute.ReRouteKeys.Count; } private static bool DoesNotContainReRoutesWithSpecificRequestIdKeys(FileAggregateReRoute fileAggregateReRoute, List<FileReRoute> reRoutes) { var reRoutesForAggregate = reRoutes.Where(r => fileAggregateReRoute.ReRouteKeys.Contains(r.Key)); return reRoutesForAggregate.All(r => string.IsNullOrEmpty(r.RequestIdKey)); } private static bool IsNotDuplicateIn(FileReRoute reRoute, List<FileReRoute> reRoutes) { var matchingReRoutes = reRoutes .Where(r => r.UpstreamPathTemplate == reRoute.UpstreamPathTemplate && (r.UpstreamHost == reRoute.UpstreamHost || reRoute.UpstreamHost == null)) .ToList(); if (matchingReRoutes.Count == 1) { return true; } var allowAllVerbs = matchingReRoutes.Any(x => x.UpstreamHttpMethod.Count == 0); var duplicateAllowAllVerbs = matchingReRoutes.Count(x => x.UpstreamHttpMethod.Count == 0) > 1; var specificVerbs = matchingReRoutes.Any(x => x.UpstreamHttpMethod.Count != 0); var duplicateSpecificVerbs = matchingReRoutes.SelectMany(x => x.UpstreamHttpMethod).GroupBy(x => x.ToLower()).SelectMany(x => x.Skip(1)).Any(); if (duplicateAllowAllVerbs || duplicateSpecificVerbs || (allowAllVerbs && specificVerbs)) { return false; } return true; } private static bool IsNotDuplicateIn(FileReRoute reRoute, List<FileAggregateReRoute> aggregateReRoutes) { var duplicate = aggregateReRoutes .Any(a => a.UpstreamPathTemplate == reRoute.UpstreamPathTemplate && a.UpstreamHost == reRoute.UpstreamHost && reRoute.UpstreamHttpMethod.Select(x => x.ToLower()).Contains("get")); return !duplicate; } private static bool IsNotDuplicateIn(FileAggregateReRoute reRoute, List<FileAggregateReRoute> aggregateReRoutes) { var matchingReRoutes = aggregateReRoutes .Where(r => r.UpstreamPathTemplate == reRoute.UpstreamPathTemplate && r.UpstreamHost == reRoute.UpstreamHost) .ToList(); return matchingReRoutes.Count <= 1; } } }
49.215116
419
0.671707
[ "MIT" ]
AliWieckowicz/Ocelot
src/Ocelot/Configuration/Validator/FileConfigurationFluentValidator.cs
8,467
C#
using System.Diagnostics; using FullStackTemplate.Facade.ViewModels.Shared; namespace FullStackTemplate.Facade.FeatureFacades { public class HomeFacade : IHomeFacade { public void Index() { } public void About() { } public void Contact() { } public ErrorViewModel Error(string currentActivityId, string traceIdentifier) { return new ErrorViewModel {RequestId = currentActivityId ?? traceIdentifier}; } } }
20.607143
89
0.561525
[ "MIT" ]
GaProgMan/FullStackTemplate
FullStackTemplate.Facade/FeatureFacades/HomeFacade.cs
579
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("09. SumOfNnumbers")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("09. SumOfNnumbers")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("2c90726c-180b-4be4-8246-2836604ea59f")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.027027
84
0.744136
[ "MIT" ]
sevdalin/Software-University-SoftUni
Programming-Basics/04. Console Input-Output/09. SumOfNnumbers/Properties/AssemblyInfo.cs
1,410
C#
using System; namespace AlbLib.Items { /// <summary> /// What item activates. /// </summary> [Serializable] public enum ItemActivates : byte { /// <summary>Compass activated.</summary> Compass = 0, /// <summary>Monster eye activated.</summary> MonsterEye = 1, /// <summary>Clock activated.</summary> Clock = 3 } }
19.588235
47
0.651652
[ "MIT" ]
IllidanS4/AlbLib
Items/ItemActivates.cs
335
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 = (IMethodSymbol)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.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.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); // https://github.com/dotnet/roslyn/issues/38509 // Assert.NotEqual(default, 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); // https://github.com/dotnet/roslyn/issues/38509 // Assert.NotEqual(default, 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.911321
1,332
0.631733
[ "Apache-2.0" ]
20chan/roslyn
src/Compilers/CSharp/Test/Semantic/Semantics/QueryTests.cs
297,289
C#
using InterviewPreparation.Exercises; using System.Collections.Generic; namespace InterviewPreparation.TrainExercises.DailyChallengesLC { class DeepestLeavesSum { public int Solve(TreeNode root) { if (root == null) { return 0; } var sum = 0; var queue = new Queue<TreeNode>(); queue.Enqueue(root); while (queue.Count > 0) { var queueSize = queue.Count; sum = 0; while (queueSize > 0) { var actual = queue.Dequeue(); queueSize--; sum += actual.val; if (actual.left != null) { queue.Enqueue(actual.left); } if (actual.right != null) { queue.Enqueue(actual.right); } } } return sum; } } }
22.416667
63
0.390335
[ "Unlicense" ]
joch0a/coding-exercises
InterviewPreparation/TrainExercises/DailyChallengesLC/DeepestLeavesSum.cs
1,078
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace NDS_Header_Reader { class Utility { public static string Binary(byte value) { return "B(" + Convert.ToString(value, 2) + ")"; } public static string GetNDSRegion(byte region) { switch(region) { case 0: return "NORMAL"; case 128: //80h return "CHINA"; case 64: //40h return "KOREA"; default: return "OTHER"; } } public static string GetUnitCode(byte unitCode) { switch(unitCode) { case 0: return "NDS"; case 2: return "NDS + DSi"; case 3: return "DSi"; default: return "UNKNOWN"; } } public static string CalculateDeviceCapacity(byte deviceCapacity) { return ((128000 << deviceCapacity) / 1000000.0).ToString("n2") + " MB"; } public static string GetHexFromBytes(byte[] bytes) { string completeHex = ""; foreach(byte b in bytes) { completeHex += $"{b:X}"; } return completeHex; } } }
23.603175
83
0.423672
[ "Apache-2.0" ]
Davidc96/NDS-Header-Reader
NDS Header Reader/Utility.cs
1,489
C#
//Copyright (c) 2018 Yardi Technology Limited. Http://www.kooboo.com //All rights reserved. using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Kooboo.Sites.FrontEvent { public enum enumEventType { RouteFinding = 0, RouteFound = 1, RouteNotFound = 2, ViewFinding = 3, ViewFound = 4, ViewNotFound = 5, PageFinding = 6, PageNotFound = 7, PageFound = 8 } }
19.923077
69
0.627413
[ "MIT" ]
VZhiLinCorp/Kooboo
Kooboo.Sites/FrontEvent/enumEventType.cs
518
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated from a template. // // Manual changes to this file may cause unexpected behavior in your application. // Manual changes to this file will be overwritten if the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace EntityFrameworkModels { using System; using System.Collections.Generic; public partial class WorkReport { public int WorkReportID { get; set; } public int EmployeeID { get; set; } public System.DateTime Date { get; set; } public string Task { get; set; } public int Hours { get; set; } public string Comments { get; set; } public virtual Employee Employee { get; set; } } }
33
84
0.527497
[ "MIT" ]
vic-alexiev/TelerikAcademy
Databases/Homework Assignments/8. Entity Framework Performance/00. EntityFrameworkModels/WorkReport.cs
891
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace Sdl.Community.GroupShareKit.Models.Response { public class ProjectAnalyseDetails { public string Name { get; set; } public string Number { get; set; } } }
20.733333
53
0.710611
[ "MIT" ]
ElvediAndreiSDL/groupsharekit.net
Sdl.Community.GroupShareKit/Models/Response/ProjectAnalyseDetails.cs
313
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Formats.Red.Records.Enums; namespace GameEstate.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class CMenuBackgroundEffectParam : IMenuDisplayParam { public CMenuBackgroundEffectParam(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static new CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CMenuBackgroundEffectParam(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
32.652174
138
0.756325
[ "MIT" ]
smorey2/GameEstate
src/GameEstate.Formats.Red/Formats/Red/W3/RTTIConvert/CMenuBackgroundEffectParam.cs
751
C#
using System.Text.Json.Serialization; namespace CVOSoftware.ValorantAPI.Dto { public sealed record AbilityDto { [JsonPropertyName("grenadeEffects")] public string GrenadeEffects { get; init; } [JsonPropertyName("ultimateEffects")] public string UltimateEffects { get; init; } [JsonPropertyName("ability1Effects")] public string Ability1Effects { get; init; } [JsonPropertyName("ability2Effects")] public string Ability2Effects { get; init; } } }
27.684211
52
0.669202
[ "Apache-2.0" ]
CVOSoftware/valorant-web-api
source/CVOSoftware.ValorantAPI/Dto/AbilityDto.cs
528
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. #nullable enable using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Http.Metadata; using Microsoft.AspNetCore.Routing; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Options; using Microsoft.Extensions.Primitives; namespace Microsoft.AspNetCore.Builder { public class DelegateEndpointRouteBuilderExtensionsTest { private ModelEndpointDataSource GetBuilderEndpointDataSource(IEndpointRouteBuilder endpointRouteBuilder) { return Assert.IsType<ModelEndpointDataSource>(Assert.Single(endpointRouteBuilder.DataSources)); } private RouteEndpointBuilder GetRouteEndpointBuilder(IEndpointRouteBuilder endpointRouteBuilder) { return Assert.IsType<RouteEndpointBuilder>(Assert.Single(GetBuilderEndpointDataSource(endpointRouteBuilder).EndpointBuilders)); } public static object[][] MapMethods { get { void MapGet(IEndpointRouteBuilder routes, string template, Delegate action) => routes.MapGet(template, action); void MapPost(IEndpointRouteBuilder routes, string template, Delegate action) => routes.MapPost(template, action); void MapPut(IEndpointRouteBuilder routes, string template, Delegate action) => routes.MapPut(template, action); void MapDelete(IEndpointRouteBuilder routes, string template, Delegate action) => routes.MapDelete(template, action); return new object[][] { new object[] { (Action<IEndpointRouteBuilder, string, Delegate>)MapGet, "GET" }, new object[] { (Action<IEndpointRouteBuilder, string, Delegate>)MapPost, "POST" }, new object[] { (Action<IEndpointRouteBuilder, string, Delegate>)MapPut, "PUT" }, new object[] { (Action<IEndpointRouteBuilder, string, Delegate>)MapDelete, "DELETE" }, }; } } [Fact] public void MapEndpoint_PrecedenceOfMetadata_BuilderMetadataReturned() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); [HttpMethod("ATTRIBUTE")] void TestAction() { } var endpointBuilder = builder.MapMethods("/", new[] { "METHOD" }, (Action)TestAction); endpointBuilder.WithMetadata(new HttpMethodMetadata(new[] { "BUILDER" })); var dataSource = Assert.Single(builder.DataSources); var endpoint = Assert.Single(dataSource.Endpoints); var metadataArray = endpoint.Metadata.OfType<IHttpMethodMetadata>().ToArray(); static string GetMethod(IHttpMethodMetadata metadata) => Assert.Single(metadata.HttpMethods); Assert.Equal(3, metadataArray.Length); Assert.Equal("ATTRIBUTE", GetMethod(metadataArray[0])); Assert.Equal("METHOD", GetMethod(metadataArray[1])); Assert.Equal("BUILDER", GetMethod(metadataArray[2])); Assert.Equal("BUILDER", endpoint.Metadata.GetMetadata<IHttpMethodMetadata>()!.HttpMethods.Single()); } [Fact] public void MapGet_BuildsEndpointWithCorrectMethod() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); _ = builder.MapGet("/", () => { }); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); Assert.NotNull(methodMetadata); var method = Assert.Single(methodMetadata!.HttpMethods); Assert.Equal("GET", method); var routeEndpointBuilder = GetRouteEndpointBuilder(builder); Assert.Equal("HTTP: GET /", routeEndpointBuilder.DisplayName); Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); } [Fact] public async Task MapGetWithRouteParameter_BuildsEndpointWithRouteSpecificBinding() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); _ = builder.MapGet("/{id}", (int? id, HttpContext httpContext) => { if (id is not null) { httpContext.Items["input"] = id; } }); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); Assert.NotNull(methodMetadata); var method = Assert.Single(methodMetadata!.HttpMethods); Assert.Equal("GET", method); var routeEndpointBuilder = GetRouteEndpointBuilder(builder); Assert.Equal("HTTP: GET /{id}", routeEndpointBuilder.DisplayName); Assert.Equal("/{id}", routeEndpointBuilder.RoutePattern.RawText); // Assert that we don't fallback to the query string var httpContext = new DefaultHttpContext(); httpContext.Request.Query = new QueryCollection(new Dictionary<string, StringValues> { ["id"] = "42" }); await endpoint.RequestDelegate!(httpContext); Assert.Null(httpContext.Items["input"]); } [Fact] public async Task MapGetWithoutRouteParameter_BuildsEndpointWithQuerySpecificBinding() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); _ = builder.MapGet("/", (int? id, HttpContext httpContext) => { if (id is not null) { httpContext.Items["input"] = id; } }); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); Assert.NotNull(methodMetadata); var method = Assert.Single(methodMetadata!.HttpMethods); Assert.Equal("GET", method); var routeEndpointBuilder = GetRouteEndpointBuilder(builder); Assert.Equal("HTTP: GET /", routeEndpointBuilder.DisplayName); Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); // Assert that we don't fallback to the route values var httpContext = new DefaultHttpContext(); httpContext.Request.Query = new QueryCollection(new Dictionary<string, StringValues>() { ["id"] = "41" }); httpContext.Request.RouteValues = new(); httpContext.Request.RouteValues["id"] = "42"; await endpoint.RequestDelegate!(httpContext); Assert.Equal(41, httpContext.Items["input"]); } [Theory] [MemberData(nameof(MapMethods))] public async Task MapVerbWithExplicitRouteParameterIsCaseInsensitive(Action<IEndpointRouteBuilder, string, Delegate> map, string expectedMethod) { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); map(builder, "/{ID}", ([FromRoute] int? id, HttpContext httpContext) => { if (id is not null) { httpContext.Items["input"] = id; } }); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); Assert.NotNull(methodMetadata); var method = Assert.Single(methodMetadata!.HttpMethods); Assert.Equal(expectedMethod, method); var routeEndpointBuilder = GetRouteEndpointBuilder(builder); Assert.Equal($"HTTP: {expectedMethod} /{{ID}}", routeEndpointBuilder.DisplayName); Assert.Equal($"/{{ID}}", routeEndpointBuilder.RoutePattern.RawText); var httpContext = new DefaultHttpContext(); httpContext.Request.RouteValues["id"] = "13"; await endpoint.RequestDelegate!(httpContext); Assert.Equal(13, httpContext.Items["input"]); } [Theory] [MemberData(nameof(MapMethods))] public async Task MapVerbWithRouteParameterDoesNotFallbackToQuery(Action<IEndpointRouteBuilder, string, Delegate> map, string expectedMethod) { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); map(builder, "/{ID}", (int? id, HttpContext httpContext) => { if (id is not null) { httpContext.Items["input"] = id; } }); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); Assert.NotNull(methodMetadata); var method = Assert.Single(methodMetadata!.HttpMethods); Assert.Equal(expectedMethod, method); var routeEndpointBuilder = GetRouteEndpointBuilder(builder); Assert.Equal($"HTTP: {expectedMethod} /{{ID}}", routeEndpointBuilder.DisplayName); Assert.Equal($"/{{ID}}", routeEndpointBuilder.RoutePattern.RawText); // Assert that we don't fallback to the query string var httpContext = new DefaultHttpContext(); httpContext.Request.Query = new QueryCollection(new Dictionary<string, StringValues> { ["id"] = "42" }); await endpoint.RequestDelegate!(httpContext); Assert.Null(httpContext.Items["input"]); } [Fact] public void MapGetWithRouteParameter_ThrowsIfRouteParameterDoesNotExist() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); var ex = Assert.Throws<InvalidOperationException>(() => builder.MapGet("/", ([FromRoute] int id) => { })); Assert.Equal("id is not a route paramter.", ex.Message); } [Fact] public void MapPost_BuildsEndpointWithCorrectMethod() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); _ = builder.MapPost("/", () => { }); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); Assert.NotNull(methodMetadata); var method = Assert.Single(methodMetadata!.HttpMethods); Assert.Equal("POST", method); var routeEndpointBuilder = GetRouteEndpointBuilder(builder); Assert.Equal("HTTP: POST /", routeEndpointBuilder.DisplayName); Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); } [Fact] public void MapPost_BuildsEndpointWithCorrectEndpointMetadata() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); _ = builder.MapPost("/", [TestConsumesAttribute(typeof(Todo), "application/xml")] (Todo todo) => { }); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var endpointMetadata = endpoint.Metadata.GetMetadata<IAcceptsMetadata>(); Assert.NotNull(endpointMetadata); Assert.False(endpointMetadata!.IsOptional); Assert.Equal(typeof(Todo), endpointMetadata.RequestType); Assert.Equal(new[] { "application/xml" }, endpointMetadata.ContentTypes); } [Fact] public void MapPut_BuildsEndpointWithCorrectMethod() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); _ = builder.MapPut("/", () => { }); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); Assert.NotNull(methodMetadata); var method = Assert.Single(methodMetadata!.HttpMethods); Assert.Equal("PUT", method); var routeEndpointBuilder = GetRouteEndpointBuilder(builder); Assert.Equal("HTTP: PUT /", routeEndpointBuilder.DisplayName); Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); } [Fact] public void MapDelete_BuildsEndpointWithCorrectMethod() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); _ = builder.MapDelete("/", () => { }); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var methodMetadata = endpoint.Metadata.GetMetadata<IHttpMethodMetadata>(); Assert.NotNull(methodMetadata); var method = Assert.Single(methodMetadata!.HttpMethods); Assert.Equal("DELETE", method); var routeEndpointBuilder = GetRouteEndpointBuilder(builder); Assert.Equal("HTTP: DELETE /", routeEndpointBuilder.DisplayName); Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); } [Fact] public void MapFallback_BuildsEndpointWithLowestRouteOrder() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); _ = builder.MapFallback("/", () => { }); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var routeEndpointBuilder = GetRouteEndpointBuilder(builder); Assert.Equal("Fallback /", routeEndpointBuilder.DisplayName); Assert.Equal("/", routeEndpointBuilder.RoutePattern.RawText); Assert.Equal(int.MaxValue, routeEndpointBuilder.Order); } [Fact] public void MapFallbackWithoutPath_BuildsEndpointWithLowestRouteOrder() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); _ = builder.MapFallback(() => { }); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var routeEndpointBuilder = GetRouteEndpointBuilder(builder); Assert.Equal("Fallback {*path:nonfile}", routeEndpointBuilder.DisplayName); Assert.Equal("{*path:nonfile}", routeEndpointBuilder.RoutePattern.RawText); Assert.Single(routeEndpointBuilder.RoutePattern.Parameters); Assert.True(routeEndpointBuilder.RoutePattern.Parameters[0].IsCatchAll); Assert.Equal(int.MaxValue, routeEndpointBuilder.Order); } [Fact] // This test scenario simulates methods defined in a top-level program // which are compiler generated. We currently do some manually parsing leveraging // code in Roslyn to support this scenario. More info at https://github.com/dotnet/roslyn/issues/55651. public void MapMethod_DoesNotEndpointNameForInnerMethod() { var name = "InnerGetString"; var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); string InnerGetString() => "TestString"; _ = builder.MapDelete("/", InnerGetString); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var endpointName = endpoint.Metadata.GetMetadata<IEndpointNameMetadata>(); var routeName = endpoint.Metadata.GetMetadata<IRouteNameMetadata>(); var routeEndpointBuilder = GetRouteEndpointBuilder(builder); Assert.Equal(name, endpointName?.EndpointName); Assert.Equal(name, routeName?.RouteName); Assert.Equal("HTTP: DELETE / => InnerGetString", routeEndpointBuilder.DisplayName); } [Fact] public void MapMethod_DoesNotEndpointNameForInnerMethodWithTarget() { var name = "InnerGetString"; var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); var testString = "TestString"; string InnerGetString() => testString; _ = builder.MapDelete("/", InnerGetString); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var endpointName = endpoint.Metadata.GetMetadata<IEndpointNameMetadata>(); var routeName = endpoint.Metadata.GetMetadata<IRouteNameMetadata>(); var routeEndpointBuilder = GetRouteEndpointBuilder(builder); Assert.Equal(name, endpointName?.EndpointName); Assert.Equal(name, routeName?.RouteName); Assert.Equal("HTTP: DELETE / => InnerGetString", routeEndpointBuilder.DisplayName); } [Fact] public void MapMethod_SetsEndpointNameForMethodGroup() { var name = "GetString"; var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); _ = builder.MapDelete("/", GetString); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var endpointName = endpoint.Metadata.GetMetadata<IEndpointNameMetadata>(); var routeName = endpoint.Metadata.GetMetadata<IRouteNameMetadata>(); var routeEndpointBuilder = GetRouteEndpointBuilder(builder); Assert.Equal(name, endpointName?.EndpointName); Assert.Equal(name, routeName?.RouteName); Assert.Equal("HTTP: DELETE / => GetString", routeEndpointBuilder.DisplayName); } [Fact] public void WithNameOverridesDefaultEndpointName() { var name = "SomeCustomName"; var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); _ = builder.MapDelete("/", GetString).WithName(name); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var endpointName = endpoint.Metadata.GetMetadata<IEndpointNameMetadata>(); var routeName = endpoint.Metadata.GetMetadata<IRouteNameMetadata>(); var routeEndpointBuilder = GetRouteEndpointBuilder(builder); Assert.Equal(name, endpointName?.EndpointName); Assert.Equal(name, routeName?.RouteName); // Will still use the original method name, not the custom endpoint name Assert.Equal("HTTP: DELETE / => GetString", routeEndpointBuilder.DisplayName); } private string GetString() => "TestString"; [Fact] public void MapMethod_DoesNotSetEndpointNameForLambda() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); _ = builder.MapDelete("/", () => { }); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var endpointName = endpoint.Metadata.GetMetadata<IEndpointNameMetadata>(); Assert.Null(endpointName); } [Fact] public void WithTags_CanSetTagsForEndpoint() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new EmptyServiceProvider())); _ = builder.MapDelete("/", GetString).WithTags("Some", "Test", "Tags"); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var tagsMetadata = endpoint.Metadata.GetMetadata<ITagsMetadata>(); Assert.Equal(new[] { "Some", "Test", "Tags" }, tagsMetadata?.Tags); } [Theory] [InlineData(true)] [InlineData(false)] public async Task MapMethod_FlowsThrowOnBadHttpRequest(bool throwOnBadRequest) { var serviceProvider = new EmptyServiceProvider(); serviceProvider.RouteHandlerOptions.ThrowOnBadRequest = throwOnBadRequest; var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(serviceProvider)); _ = builder.Map("/{id}", (int id) => { }); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var httpContext = new DefaultHttpContext(); httpContext.RequestServices = new ServiceCollection().AddLogging().BuildServiceProvider(); httpContext.Request.RouteValues["id"] = "invalid!"; if (throwOnBadRequest) { var ex = await Assert.ThrowsAsync<BadHttpRequestException>(() => endpoint.RequestDelegate!(httpContext)); Assert.Equal(400, ex.StatusCode); } else { await endpoint.RequestDelegate!(httpContext); Assert.Equal(400, httpContext.Response.StatusCode); } } [Fact] public async Task MapMethod_DefaultsToNotThrowOnBadHttpRequestIfItCannotResolveRouteHandlerOptions() { var builder = new DefaultEndpointRouteBuilder(new ApplicationBuilder(new ServiceCollection().BuildServiceProvider())); _ = builder.Map("/{id}", (int id) => { }); var dataSource = GetBuilderEndpointDataSource(builder); // Trigger Endpoint build by calling getter. var endpoint = Assert.Single(dataSource.Endpoints); var httpContext = new DefaultHttpContext(); httpContext.RequestServices = new ServiceCollection().AddLogging().BuildServiceProvider(); httpContext.Request.RouteValues["id"] = "invalid!"; await endpoint.RequestDelegate!(httpContext); Assert.Equal(400, httpContext.Response.StatusCode); } class FromRoute : Attribute, IFromRouteMetadata { public string? Name { get; set; } } class TestConsumesAttribute : Attribute, IAcceptsMetadata { public TestConsumesAttribute(Type requestType, string contentType, params string[] otherContentTypes) { if (contentType == null) { throw new ArgumentNullException(nameof(contentType)); } var contentTypes = new List<string>() { contentType }; for (var i = 0; i < otherContentTypes.Length; i++) { contentTypes.Add(otherContentTypes[i]); } _requestType = requestType; _contentTypes = contentTypes; } IReadOnlyList<string> IAcceptsMetadata.ContentTypes => _contentTypes; Type? IAcceptsMetadata.RequestType => _requestType; bool IAcceptsMetadata.IsOptional => false; Type? _requestType; List<string> _contentTypes = new(); } class Todo { } private class HttpMethodAttribute : Attribute, IHttpMethodMetadata { public bool AcceptCorsPreflight => false; public IReadOnlyList<string> HttpMethods { get; } public HttpMethodAttribute(params string[] httpMethods) { HttpMethods = httpMethods; } } private class EmptyServiceProvider : IServiceScope, IServiceProvider, IServiceScopeFactory { public IServiceProvider ServiceProvider => this; public RouteHandlerOptions RouteHandlerOptions { get; set; } = new RouteHandlerOptions(); public IServiceScope CreateScope() { return this; } public void Dispose() { } public object? GetService(Type serviceType) { if (serviceType == typeof(IServiceScopeFactory)) { return this; } else if (serviceType == typeof(IOptions<RouteHandlerOptions>)) { return Options.Create(RouteHandlerOptions); } return null; } } } }
42.456869
152
0.624464
[ "MIT" ]
Mika-net/AspNetCore
src/Http/Routing/test/UnitTests/Builder/DelegateEndpointRouteBuilderExtensionsTest.cs
26,578
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.Globalization; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Web.Http; using System.Xml; using DotNetNuke.Entities.Modules; using DotNetNuke.Modules.CoreMessaging.ViewModels; using DotNetNuke.Services.Exceptions; using DotNetNuke.Services.Localization; using DotNetNuke.Services.Social.Messaging; using DotNetNuke.Services.Social.Subscriptions; using DotNetNuke.Services.Social.Subscriptions.Entities; using DotNetNuke.Web.Api; namespace DotNetNuke.Modules.CoreMessaging.Services { [DnnAuthorize] public class SubscriptionsController : DnnApiController { private const string SharedResources = "~/DesktopModules/CoreMessaging/App_LocalResources/SharedResources.resx"; private const string ViewControlResources = "~/DesktopModules/CoreMessaging/App_LocalResources/View.ascx.resx"; #region Private Properties private string LocalizationFolder { get { return string.Format("~/DesktopModules/{0}/App_LocalResources/", DesktopModuleController.GetDesktopModuleByModuleName("DotNetNuke.Modules.CoreMessaging", PortalSettings.PortalId).FolderName); } } #endregion #region Public APIs /// <summary> /// Perform a search on Scoring Activities registered in the system. /// </summary> /// <param name="pageIndex">Page index to begin from (0, 1, 2)</param> /// <param name="pageSize">Number of records to return per page</param> /// <param name="sortExpression">The sort expression in the form [Description|SubscriptionType] [Asc|Desc]</param> /// <returns>The sorted and paged list of subscriptions</returns> [HttpGet] public HttpResponseMessage GetSubscriptions(int pageIndex, int pageSize, string sortExpression) { try { var subscriptions = from s in SubscriptionController.Instance.GetUserSubscriptions(UserInfo, PortalSettings.PortalId) select GetSubscriptionViewModel(s); List<SubscriptionViewModel> sortedList; if (string.IsNullOrEmpty(sortExpression)) { sortedList = subscriptions.ToList(); } else { var sort = sortExpression.Split(' '); var desc = sort.Length == 2 && sort[1] == "desc"; switch (sort[0]) { case "Description": sortedList = desc ? subscriptions.OrderByDescending(s => s.Description).ToList() : subscriptions.OrderBy(s => s.Description).ToList(); break; case "SubscriptionType": sortedList = desc ? subscriptions.OrderByDescending(s => s.SubscriptionType).ToList() : subscriptions.OrderBy(s => s.SubscriptionType).ToList(); break; default: sortedList = subscriptions.ToList(); break; } } var response = new { Success = true, Results = sortedList.Skip(pageIndex * pageSize).Take(pageSize).ToList(), TotalResults = sortedList.Count() }; return Request.CreateResponse(HttpStatusCode.OK, response); } catch (Exception ex) { Exceptions.LogException(ex); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message); } } [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage UpdateSystemSubscription(InboxSubscriptionViewModel post) { try { var userPreferencesController = UserPreferencesController.Instance; var userPreference = new UserPreference { PortalId = UserInfo.PortalID, UserId = UserInfo.UserID, MessagesEmailFrequency = (Frequency) post.MsgFreq, NotificationsEmailFrequency = (Frequency) post.NotifyFreq }; userPreferencesController.SetUserPreference(userPreference); return Request.CreateResponse(HttpStatusCode.OK, userPreferencesController.GetUserPreference(UserInfo)); } catch (Exception ex) { Exceptions.LogException(ex); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message); } } [HttpPost] [ValidateAntiForgeryToken] public HttpResponseMessage DeleteContentSubscription(Subscription subscription) { try { var sub = SubscriptionController.Instance.GetUserSubscriptions(UserInfo, PortalSettings.PortalId) .SingleOrDefault(s => s.SubscriptionId == subscription.SubscriptionId); if (sub != null) { SubscriptionController.Instance.DeleteSubscription(sub); } return Request.CreateResponse(HttpStatusCode.OK, "unsubscribed"); } catch (Exception ex) { Exceptions.LogException(ex); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex.Message); } } [HttpGet] [AllowAnonymous] public HttpResponseMessage GetLocalizationTable(string culture) { try { if (!string.IsNullOrEmpty(culture)) { Localization.SetThreadCultures(new CultureInfo(culture), PortalSettings); } var dictionary = new Dictionary<string, string>(); var resourcesPath = LocalizationFolder; var files = Directory.GetFiles(System.Web.HttpContext.Current.Server.MapPath(resourcesPath)).Select(x => new FileInfo(x).Name).Where(f => !IsLanguageSpecific(f)).ToList(); foreach (var kvp in files.SelectMany(f => GetLocalizationValues(resourcesPath, f, culture)).Where(kvp => !dictionary.ContainsKey(kvp.Key))) { dictionary.Add(kvp.Key, kvp.Value); } foreach (var kvp in GetLocalizationValues(SharedResources, culture).Where(kvp => !dictionary.ContainsKey(kvp.Key))) { dictionary.Add(kvp.Key, kvp.Value); } return Request.CreateResponse(HttpStatusCode.OK, new { Table = dictionary }); } catch (Exception ex) { Exceptions.LogException(ex); return Request.CreateErrorResponse(HttpStatusCode.InternalServerError, ex); } } #endregion #region Private Statics Methods private static SubscriptionViewModel GetSubscriptionViewModel(Subscription subscription) { var model = new SubscriptionViewModel { SubscriptionId = subscription.SubscriptionId, Description = subscription.Description, }; // localize the type name var subscriptionType = SubscriptionTypeController.Instance.GetSubscriptionType( t => t.SubscriptionTypeId == subscription.SubscriptionTypeId); if (subscriptionType != null) { var localizedName = Localization.GetString(subscriptionType.SubscriptionName, ViewControlResources); model.SubscriptionType = localizedName ?? subscriptionType.FriendlyName; } return model; } private static bool IsLanguageSpecific(string fileName) { var components = fileName.Split(new[] { '.' }, StringSplitOptions.RemoveEmptyEntries); if (components.Length > 1) { var language = components[components.Length - 2]; if (!string.IsNullOrEmpty(language)) { try { CultureInfo.GetCultureInfo(language); return true; } catch (CultureNotFoundException) { return false; } } } return false; } private static IEnumerable<KeyValuePair<string, string>> GetLocalizationValues(string path, string file, string culture) { return GetLocalizationValues(string.Format("{0}/{1}", path, file), culture); } private static IEnumerable<KeyValuePair<string, string>> GetLocalizationValues(string fullPath, string culture) { using (var stream = new FileStream(System.Web.HttpContext.Current.Server.MapPath(fullPath), FileMode.Open, FileAccess.Read)) { var document = new XmlDocument { XmlResolver = null }; document.Load(stream); // ReSharper disable AssignNullToNotNullAttribute var headers = document.SelectNodes(@"/root/resheader").Cast<XmlNode>().ToArray(); // ReSharper restore AssignNullToNotNullAttribute AssertHeaderValue(headers, "resmimetype", "text/microsoft-resx"); // ReSharper disable AssignNullToNotNullAttribute foreach (var xmlNode in document.SelectNodes("/root/data").Cast<XmlNode>()) // ReSharper restore AssignNullToNotNullAttribute { var name = GetNameAttribute(xmlNode).Replace(".Text", string.Empty); if (string.IsNullOrEmpty(name)) { continue; } var value = Localization.GetString(string.Format("{0}.Text", name), fullPath, culture); yield return new KeyValuePair<string, string>(name, value); } } } private static void AssertHeaderValue(IEnumerable<XmlNode> headers, string key, string value) { var header = headers.FirstOrDefault(x => GetNameAttribute(x).Equals(key, StringComparison.InvariantCultureIgnoreCase)); if (header != null) { if (!header.InnerText.Equals(value, StringComparison.InvariantCultureIgnoreCase)) { throw new ApplicationException(string.Format("Resource header '{0}' != '{1}'", key, value)); } } else { throw new ApplicationException(string.Format("Resource header '{0}' is missing", key)); } } private static string GetNameAttribute(XmlNode node) { if (node.Attributes != null) { var attribute = node.Attributes.GetNamedItem("name"); if (attribute != null) { return attribute.Value; } } return null; } #endregion } }
35.531148
164
0.615761
[ "MIT" ]
Tychodewaard/Dnn.Platform
DNN Platform/Modules/CoreMessaging/Services/SubscriptionsController.cs
10,839
C#
using NScan.Lib.Union3; namespace NScan.SharedKernel.RuleDtos.ProjectScoped { public class ProjectScopedRuleUnionDto : Union< CorrectNamespacesRuleComplementDto, HasAttributesOnRuleComplementDto, HasTargetFrameworkRuleComplementDto> { private readonly IUnionTransformingVisitor< CorrectNamespacesRuleComplementDto, HasAttributesOnRuleComplementDto, HasTargetFrameworkRuleComplementDto, string> _ruleNameExtractionVisitor = new ProjectScopedRuleNameExtractionVisitor(); public static ProjectScopedRuleUnionDto With(CorrectNamespacesRuleComplementDto dto) { return new ProjectScopedRuleUnionDto(dto); } public static ProjectScopedRuleUnionDto With(HasAttributesOnRuleComplementDto dto) { return new ProjectScopedRuleUnionDto(dto); } public static ProjectScopedRuleUnionDto With(HasTargetFrameworkRuleComplementDto dto) { return new ProjectScopedRuleUnionDto(dto); } public string RuleName => Accept(_ruleNameExtractionVisitor); private ProjectScopedRuleUnionDto(CorrectNamespacesRuleComplementDto o) : base(o) { } private ProjectScopedRuleUnionDto(HasAttributesOnRuleComplementDto dto) : base(dto) { } private ProjectScopedRuleUnionDto(HasTargetFrameworkRuleComplementDto dto) : base(dto) { } } }
29.911111
90
0.773403
[ "MIT" ]
pascalberger/nscan
src/NScan.SharedKernel/RuleDtos/ProjectScoped/ProjectScopedRuleUnionDto.cs
1,348
C#
using System; namespace BPaaSDTO { public class BpaasPayload { public dynamic BpaaSPayload { get; set; } public BpaasPayload(dynamic payload) { this.BpaaSPayload = payload; } } }
15.866667
49
0.57563
[ "Apache-2.0" ]
CDCgov/MicrobeTraceNext
webForm/BPaaSDTO/BpaaSPayload.cs
240
C#
using MAVN.Numerics; using MAVN.Service.PartnersIntegration.Client.Enums; namespace MAVN.Service.PartnersIntegration.Client.Models { /// <summary> /// Model representing a customer balance response /// </summary> public class CustomerBalanceResponseModel { /// <summary> /// The status of the retrieval /// </summary> public CustomerBalanceStatus Status { get; set; } /// <summary> /// The customer's tokens /// </summary> public Money18 Tokens { get; set; } /// <summary> /// Currency amount balance, calculated using the exchange rate for the selected currency /// </summary> public decimal FiatBalance { get; set; } /// <summary> /// Fiat currency for the fiat balance /// </summary> public string FiatCurrency { get; set; } } }
27.78125
97
0.5973
[ "MIT" ]
OpenMAVN/MAVN.Service.PartnersIntegration
client/MAVN.Service.PartnersIntegration.Client/Models/CustomerBalanceResponseModel.cs
889
C#
// <auto-generated> // 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. // </auto-generated> namespace Microsoft.Azure.Batch.Protocol.Models { using Newtonsoft.Json; using System.Linq; /// <summary> /// Options for rebooting a Compute Node. /// </summary> public partial class NodeRebootParameter { /// <summary> /// Initializes a new instance of the NodeRebootParameter class. /// </summary> public NodeRebootParameter() { CustomInit(); } /// <summary> /// Initializes a new instance of the NodeRebootParameter class. /// </summary> /// <param name="nodeRebootOption">When to reboot the Compute Node and /// what to do with currently running Tasks.</param> public NodeRebootParameter(ComputeNodeRebootOption? nodeRebootOption = default(ComputeNodeRebootOption?)) { NodeRebootOption = nodeRebootOption; CustomInit(); } /// <summary> /// An initialization method that performs custom operations like setting defaults /// </summary> partial void CustomInit(); /// <summary> /// Gets or sets when to reboot the Compute Node and what to do with /// currently running Tasks. /// </summary> /// <remarks> /// The default value is requeue. Possible values include: 'requeue', /// 'terminate', 'taskCompletion', 'retainedData' /// </remarks> [JsonProperty(PropertyName = "nodeRebootOption")] public ComputeNodeRebootOption? NodeRebootOption { get; set; } } }
32.896552
113
0.627358
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/batch/Microsoft.Azure.Batch/src/GeneratedProtocol/Models/NodeRebootParameter.cs
1,908
C#
using System; using System.Collections.Generic; using System.Text; using System.Linq; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using HuaweiCloud.SDK.Core; namespace HuaweiCloud.SDK.As.V1.Model { /// <summary> /// Response Object /// </summary> public class CreateScalingTagsResponse : SdkResponse { } }
18.190476
56
0.730366
[ "Apache-2.0" ]
Huaweicloud-SDK/huaweicloud-sdk-net-v3
Services/As/V1/Model/CreateScalingTagsResponse.cs
382
C#
using System.Threading.Tasks; using GraphQL.Types; namespace Backend.GraphQL.Helper.Schema.Base { public interface IGraphQLExecutor { Task<object> Resolve(ResolveFieldContext context); } }
19.181818
58
0.734597
[ "MIT" ]
Casperbart/Nordic-Camp-2019
src/Backend/GraphQL/Helper/Schema/Base/IGraphQLExecutor.cs
213
C#
/** * Copyright 2015 Canada Health Infoway, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * * Author: $LastChangedBy: tmcgrady $ * Last modified: $LastChangedDate: 2011-05-04 15:47:15 -0400 (Wed, 04 May 2011) $ * Revision: $LastChangedRevision: 2623 $ */ /* This class was auto-generated by the message builder generator tools. */ namespace Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Pharmacy.Porx_mt020070ca { using Ca.Infoway.Messagebuilder; using Ca.Infoway.Messagebuilder.Annotation; using Ca.Infoway.Messagebuilder.Datatype; using Ca.Infoway.Messagebuilder.Datatype.Impl; using Ca.Infoway.Messagebuilder.Datatype.Lang; using Ca.Infoway.Messagebuilder.Domainvalue; using Ca.Infoway.Messagebuilder.Model; using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Common.Coct_mt050303ca; using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Common.Coct_mt270010ca; using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Merged; using Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Pharmacy.Merged; using System.Collections.Generic; /** * <summary>Business Name: Prescription Dispense</summary> * * <p>Dispensing is an integral part of the overall medication * process.</p> <p>This is the detailed information about a * medication dispense that has been performed on behalf a * patient.</p> */ [Hl7PartTypeMappingAttribute(new string[] {"PORX_MT020070CA.MedicationDispense"})] public class PrescriptionDispense : MessagePartBean { private II id; private SET<CV, Code> confidentialityCode; private Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Common.Coct_mt050303ca.AnimalPatient subjectPatient; private Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Pharmacy.Merged.PrescriptionReference inFulfillmentOfSubstanceAdministrationRequest; private Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Pharmacy.Merged.Substitution component1SubstitutionMade; private IList<Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Common.Coct_mt270010ca.AdministrationInstructions> component2DosageInstruction; private Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Merged.Dispense component3SupplyEvent; private Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Merged.Includes subjectOf; public PrescriptionDispense() { this.id = new IIImpl(); this.confidentialityCode = new SETImpl<CV, Code>(typeof(CVImpl)); this.component2DosageInstruction = new List<Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Common.Coct_mt270010ca.AdministrationInstructions>(); } /** * <summary>Business Name: A:Local Dispense Id</summary> * * <remarks>Relationship: PORX_MT020070CA.MedicationDispense.id * Conformance/Cardinality: REQUIRED (0-1) <p>Allows formal * tracking of centrally recorded dispenses to local records * for audit and related purposes.</p> <p>Identifier assigned * by the dispensing facility.</p></remarks> */ [Hl7XmlMappingAttribute(new string[] {"id"})] public Identifier Id { get { return this.id.Value; } set { this.id.Value = value; } } /** * <summary>Business Name: E:Prescription Masking Indicators</summary> * * <remarks>Relationship: * PORX_MT020070CA.MedicationDispense.confidentialityCode * Conformance/Cardinality: OPTIONAL (0-2) <p>Can be used to * set a mask for a new dispense, if present in a new dispense * request.</p><p>Allows the patient to have discrete control * over access to their prescription data.</p><p>Taboo allows * the provider to request restricted access to patient or * their care giver.</p><p>Constraint: Can't have both normal * and one of the other codes simultaneously.</p><p>The * attribute is optional because not all systems will support * masking.</p> <p>If a dispense is masked, it implicitly masks * the prescription being dispensed. (There's no point in * masking a dispense if the prescription is unmasked.)</p> * <p>Communicates the intent that the dispense should be * masked if it is created; If the dispense is masked, this * makes the complete prescription and all dispenses * masked.</p><p>Provides support for additional * confidentiality constraint, giving patients a level of * control over their information.</p><p>Valid values are: 'N' * (normal - denotes 'Not Masked'); 'R' (restricted - denotes * 'Masked'); 'V' (very restricted - denotes very restricted * access as declared by the Privacy Officer of the record * holder) and 'T' (taboo - denotes 'Patient Access * Restricted').</p><p>The default is 'normal' signifying 'Not * Masked'.</p></remarks> */ [Hl7XmlMappingAttribute(new string[] {"confidentialityCode"})] public ICollection<x_BasicConfidentialityKind> ConfidentialityCode { get { return this.confidentialityCode.RawSet<x_BasicConfidentialityKind>(); } } /** * <summary>Relationship: PORX_MT020070CA.Subject8.patient</summary> * * <remarks>Conformance/Cardinality: REQUIRED (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"subject/patient"})] public Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Common.Coct_mt050303ca.AnimalPatient SubjectPatient { get { return this.subjectPatient; } set { this.subjectPatient = value; } } /** * <summary>Relationship: * PORX_MT020070CA.InFulfillmentOf1.substanceAdministrationRequest</summary> * * <remarks>Conformance/Cardinality: MANDATORY (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"inFulfillmentOf/substanceAdministrationRequest"})] public Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Pharmacy.Merged.PrescriptionReference InFulfillmentOfSubstanceAdministrationRequest { get { return this.inFulfillmentOfSubstanceAdministrationRequest; } set { this.inFulfillmentOfSubstanceAdministrationRequest = value; } } /** * <summary>Relationship: * PORX_MT020070CA.Component13.substitutionMade</summary> * * <remarks>Conformance/Cardinality: REQUIRED (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"component1/substitutionMade"})] public Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Pharmacy.Merged.Substitution Component1SubstitutionMade { get { return this.component1SubstitutionMade; } set { this.component1SubstitutionMade = value; } } /** * <summary>Relationship: * PORX_MT020070CA.Component11.dosageInstruction</summary> * * <remarks>Conformance/Cardinality: MANDATORY (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"component2/dosageInstruction"})] public IList<Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Common.Coct_mt270010ca.AdministrationInstructions> Component2DosageInstruction { get { return this.component2DosageInstruction; } } /** * <summary>Relationship: PORX_MT020070CA.Component.supplyEvent</summary> * * <remarks>Conformance/Cardinality: MANDATORY (1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"component3/supplyEvent"})] public Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Merged.Dispense Component3SupplyEvent { get { return this.component3SupplyEvent; } set { this.component3SupplyEvent = value; } } /** * <summary>Relationship: * PORX_MT020070CA.MedicationDispense.subjectOf</summary> * * <remarks>Conformance/Cardinality: REQUIRED (0-1)</remarks> */ [Hl7XmlMappingAttribute(new string[] {"subjectOf"})] public Ca.Infoway.Messagebuilder.Model.Pcs_mr2009_r02_04_03.Merged.Includes SubjectOf { get { return this.subjectOf; } set { this.subjectOf = value; } } } }
50.867403
163
0.670142
[ "ECL-2.0", "Apache-2.0" ]
CanadaHealthInfoway/message-builder-dotnet
message-builder-release-r02_04_03/Main/Ca/Infoway/Messagebuilder/Model/Pcs_mr2009_r02_04_03/Pharmacy/Porx_mt020070ca/PrescriptionDispense.cs
9,207
C#
using UnityEngine; namespace LowVisibility { public class ModConfig { // If true, extra logging will be used public bool Debug = false; public bool Trace = false; public class IconOpts { public string ElectronicWarfare = "lv_eye-shield"; // 00aad4ff public string SensorsDisabled = "lv_sight-disabled"; // ff0000ff public string VisionAndSensors = "lv_cyber-eye"; public string TargetSensorsMark = "lv_radar-sweep"; public string TargetVisualsMark = "lv_brass-eye"; public string TargetTaggedMark = "lv_target-laser"; public string TargetNarcedMark = "lv_radio-tower"; public string TargetStealthMark = "lv_robber-mask"; public string TargetMimeticMark = "lv_static"; public string TargetECMShieldedMark = "lv_eye-shield"; public string TargetActiveProbePingedMark = "lv_eye-target"; public float[] MarkColorPlayerPositive = new float[] { 1f, 0f, 0.062f, 1f }; public Color PlayerPositiveMarkColor; public float[] MarkColorPlayerNegative = new float[] { 0f, 0.901f, 0.098f, 1f }; public Color PlayerNegativeMarkColor; } public IconOpts Icons = new IconOpts(); public class ToggleOpts { public bool LogEffectsOnMove = false; public bool ShowNightVision = true; public bool MimeticUsesGhost = true; } public ToggleOpts Toggles = new ToggleOpts(); // The base range (in hexes) for a unit's sensors public class SensorRangeOpts { public int MechTypeRange = 12; public int VehicleTypeRange = 9; public int TurretTypeRange = 15; public int UnknownTypeRange = 6; // The minimum range for sensors, no matter the circumstances public int MinimumRangeHexes = 8; // If true, sensor checks always fail on the first turn of the game public bool SensorsOfflineAtSpawn = true; // The maximum penalty that ECM Shield + ECM Jamming should apply TO SENSOR DETAILS ONLY public int MaxECMDetailsPenalty = -8; // The minimum signature that we'll allow after all modifiers are applied public float MinSignature = 0.05f; public float MinimumSensorRange() { return this.MinimumRangeHexes * 30.0f; } } public SensorRangeOpts Sensors = new SensorRangeOpts(); // The base range (in hexes) for a unit's vision public class VisionRangeOpts { public int BaseRangeBright = 15; public int BaseRangeDim = 11; public int BaseRangeDark = 7; // The multiplier used for weather effects public float RangeMultiRainSnow = 0.8f; public float RangeMultiLightFog = 0.66f; public float RangeMultiHeavyFog = 0.33f; // The minium range for vision, no matter the circumstances public int MinimumRangeHexes = 3; // The range (in hexes) from which you can identify some elements of a unit public int ScanRangeHexes = 7; public float MinimumVisionRange() { return this.MinimumRangeHexes * 30.0f; } } public VisionRangeOpts Vision = new VisionRangeOpts(); public class FogOfWarOpts { // If true, fog of war will be redrawn on each unit's activation public bool RedrawFogOfWarOnActivation = false; // If true, terrain is visible outside of the immediate fog of war boundaires public bool ShowTerrainThroughFogOfWar = true; } public FogOfWarOpts FogOfWar = new FogOfWarOpts(); public class AttackOpts { public int NoVisualsPenalty = 5; public int NoSensorsPenalty = 5; public int FiringBlindPenalty = 13; public float ShieldedMulti = 1.0f; public float JammedMulti = 1.0f; } public AttackOpts Attack = new AttackOpts(); public class ProbabilityOpts { // The inflection point of the probability distribution function. public int Sigma = 4; // The inflection point of the probability distribution function. public int Mu = -1; } public ProbabilityOpts Probability = new ProbabilityOpts(); public void LogConfig() { Mod.Log.Info?.Write("=== MOD CONFIG BEGIN ==="); Mod.Log.Info?.Write($" DEBUG:{this.Debug} Trace:{this.Trace}"); Mod.Log.Info?.Write($" == Probability =="); Mod.Log.Info?.Write($"ProbabilitySigma:{Probability.Sigma}, ProbabilityMu:{Probability.Mu}"); Mod.Log.Info?.Write($" == Sensors =="); Mod.Log.Info?.Write($"Type Ranges - Mech: {Sensors.MechTypeRange} Vehicle: {Sensors.VehicleTypeRange} Turret: {Sensors.TurretTypeRange} UnknownType: {Sensors.UnknownTypeRange}"); Mod.Log.Info?.Write($"MinimumRange: {Sensors.MinimumRangeHexes} FirstTurnForceFailedChecks: {Sensors.SensorsOfflineAtSpawn} MaxECMDetailsPenalty: {Sensors.MaxECMDetailsPenalty}"); Mod.Log.Info?.Write($" == Vision =="); Mod.Log.Info?.Write($"Vision Ranges - Bright: {Vision.BaseRangeBright} Dim:{Vision.BaseRangeDim} Dark:{Vision.BaseRangeDark}"); Mod.Log.Info?.Write($"Range Multis - Rain/Snow: x{Vision.RangeMultiRainSnow} Light Fog: x{Vision.RangeMultiLightFog} HeavyFog: x{Vision.RangeMultiHeavyFog}"); Mod.Log.Info?.Write($"Minimum range: {Vision.MinimumRangeHexes} ScanRange: {Vision.ScanRangeHexes}"); Mod.Log.Info?.Write($" == FogOfWar =="); Mod.Log.Info?.Write($"RedrawFogOfWarOnActivation: {FogOfWar.RedrawFogOfWarOnActivation} ShowTerrainThroughFogOfWar: {FogOfWar.ShowTerrainThroughFogOfWar}"); Mod.Log.Info?.Write($" == Attacking =="); //Mod.Log.Info?.Write($"Penalties - NoSensors:{Attack.NoSensorInfoPenalty} NoVisuals:{Attack.NoVisualsPenalty} BlindFire:{Attack.BlindFirePenalty}"); //Mod.Log.Info?.Write($"Criticals Penalty - NoSensors:{Attack.NoSensorsCriticalPenalty} NoVisuals:{Attack.NoVisualsCriticalPenalty}"); //Mod.Log.Info?.Write($"HeatVisionMaxBonus: {Attack.MaxHeatVisionBonus}"); Mod.Log.Info?.Write("=== MOD CONFIG END ==="); } public void Init() { this.Icons.PlayerPositiveMarkColor = new Color(this.Icons.MarkColorPlayerPositive[0], this.Icons.MarkColorPlayerPositive[1], this.Icons.MarkColorPlayerPositive[2], this.Icons.MarkColorPlayerPositive[3]); this.Icons.PlayerNegativeMarkColor = new Color(this.Icons.MarkColorPlayerNegative[0], this.Icons.MarkColorPlayerNegative[1], this.Icons.MarkColorPlayerNegative[2], this.Icons.MarkColorPlayerNegative[3]); } } }
47.944828
215
0.640823
[ "MIT" ]
RaimoTorbouc/LowVisibility
LowVisibility/LowVisibility/ModConfig.cs
6,954
C#
namespace AbpCoreMvcIdentiyServer.Sessions.Dto { public class GetCurrentLoginInformationsOutput { public ApplicationInfoDto Application { get; set; } public UserLoginInfoDto User { get; set; } public TenantLoginInfoDto Tenant { get; set; } } }
23.583333
59
0.69258
[ "Apache-2.0" ]
staneee/AbpCoreMvcIdentiyServer
src/AbpCoreMvcIdentiyServer.Application/Sessions/Dto/GetCurrentLoginInformationsOutput.cs
285
C#
using System; using System.Collections.Generic; using System.Text; namespace DotNetOutdated.Core.Extensions { static class DictionaryExtensions { /// <summary> /// Tries to get a value in a dictionary identified by its key, otherwise returns default value for passed-in type. /// </summary> /// <remarks>Once this library is upgraded to .NET Standard 2.1, this method will become obsolete as it's already built in there</remarks> public static TValue GetValueOrDefault<TKey, TValue>(this IReadOnlyDictionary<TKey, TValue> dict, TKey key) => dict.TryGetValue(key, out var value) ? value : default(TValue); } }
39.705882
146
0.694815
[ "MIT" ]
Adityanr/dotnet-outdated
src/DotNetOutdated.Core/Extensions/DictionaryExtensions.cs
677
C#
using System; using System.Diagnostics; using System.Linq; using System.Text; namespace SEDC.Adv.Class13.SB { class Program { static void Main(string[] args) { var data = Enumerable.Repeat("abcdefg", 80000); Console.WriteLine(data.Count()); Stopwatch stopwatch = Stopwatch.StartNew(); Console.WriteLine("Using concatenation"); var result = string.Empty; foreach (var word in data) { result += word; } stopwatch.Stop(); Console.WriteLine(result.Length); Console.WriteLine("Duration: {0} ms", stopwatch.ElapsedMilliseconds); Console.WriteLine("Using string builder"); stopwatch = Stopwatch.StartNew(); var result2 = new StringBuilder(); foreach (var word in data) { result2.Append(word); } stopwatch.Stop(); var stringResult = result2.ToString(); Console.WriteLine(stringResult.Length); Console.WriteLine("Duration: {0} ms", stopwatch.ElapsedMilliseconds); Console.ReadLine(); } } }
26.826087
81
0.542139
[ "MIT" ]
sedc-codecademy/skwd8-06-csharpadv
g6/Class13/SEDC.Adv.Class13/SEDC.Adv.Class13.SB/Program.cs
1,236
C#
#region License /* * Copyright 2002-2010 the original author or authors. * * 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. */ #endregion using Spring.Messaging.Core; namespace Spring.Messaging.Support.Converters { /// <summary> /// Delegate for creating IMessageConverter instance. Used by <see cref="DefaultMessageQueueFactory"/> /// to register a creation function with a given name. /// </summary> public delegate IMessageConverter MessageConverterCreatorDelegate(); }
34.533333
108
0.720077
[ "Apache-2.0" ]
Magicianred/spring-net
src/Spring/Spring.Messaging/Messaging/Support/Converters/MessageConverterCreatorDelegate.cs
1,036
C#
// Camera Path // Available on the Unity3D Asset Store // Copyright (c) 2013 Jasper Stocker http://camerapath.jasperstocker.com // // THIS CODE AND INFORMATION ARE PROVIDED "AS IS" WITHOUT WARRANTY OF ANY // KIND, EITHER EXPRESSED OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE // IMPLIED WARRANTIES OF MERCHANTABILITY AND/OR FITNESS FOR A // PARTICULAR PURPOSE. using UnityEditor; using UnityEngine; using System.Collections; [CanEditMultipleObjects] [CustomEditor(typeof(CameraPathBezier))] public class CameraPathBezierEditor : Editor { Vector2 scrollPosition; private CameraPathBezierControlPoint bezierControlPoint; public void OnSceneGUI() { CameraPathBezier bezier = (CameraPathBezier)target; if(GUI.changed){ bezier.RecalculateStoredValues(); EditorUtility.SetDirty(bezier); } } public override void OnInspectorGUI() { CameraPathBezier bezier = (CameraPathBezier)target; int numberOfControlPoints = bezier.numberOfControlPoints; if(numberOfControlPoints>0) { if(numberOfControlPoints>1){ GUILayout.Space(10); bezier.lineColour = EditorGUILayout.ColorField("Line Colour",bezier.lineColour); GUILayout.Space(5); bezier.mode = (CameraPathBezier.viewmodes)EditorGUILayout.EnumPopup("Camera Mode", bezier.mode); GUILayout.Space(5); if(bezier.mode == CameraPathBezier.viewmodes.target){ if(bezier.target==null) EditorGUILayout.HelpBox("No target has been specified in the bezier path",MessageType.Warning); EditorGUILayout.BeginHorizontal(); EditorGUILayout.LabelField("Look at Target"); bezier.target = (Transform)EditorGUILayout.ObjectField(bezier.target, typeof(Transform),true); EditorGUILayout.EndHorizontal(); GUILayout.Space(5); } bool newValue = EditorGUILayout.Toggle("Loop",bezier.loop); if(newValue != bezier.loop){ Undo.RegisterUndo(bezier,"Set Loop"); bezier.loop = newValue; bezier.RecalculateStoredValues(); } }else{ if(numberOfControlPoints==1) EditorGUILayout.HelpBox("Click Add New Point to add additional points, you need at least two points to make a path.",MessageType.Info); } GUILayout.Space(5); if(GUILayout.Button("Reset Path")){ if(EditorUtility.DisplayDialog("Resetting path?", "Are you sure you want to delete all control points?", "Delete", "Cancel")){ Undo.RegisterSceneUndo("Reset Camera Path"); bezier.ResetPath(); return; } } GUILayout.Space(10); GUILayout.Box(EditorGUIUtility.whiteTexture, GUILayout.Height(2), GUILayout.Width(Screen.width-20)); GUILayout.Space(3); //scrollPosition = EditorGUILayout.BeginScrollView(scrollPosition); for(int i=0; i<numberOfControlPoints; i++) { CameraPathBezierControlPoint go = bezier.controlPoints[i]; if(go==null) go = (CameraPathBezierControlPoint)EditorGUILayout.ObjectField(null,typeof( CameraPathBezierControlPoint ), true); else go = (CameraPathBezierControlPoint)EditorGUILayout.ObjectField( go.name, go, typeof( CameraPathBezierControlPoint ), true); EditorGUILayout.BeginHorizontal(); if(GUILayout.Button("Delete")){ Undo.RegisterSceneUndo("Delete Camera Path point"); bezier.DeletePoint(i,true); numberOfControlPoints = bezier.numberOfControlPoints; EditorUtility.SetDirty(bezier); return; } if(i==numberOfControlPoints-1){ if(GUILayout.Button("Add New Point At End")){ Undo.RegisterSceneUndo("Create a new Camera Path point"); bezier.AddNewPoint(i+1); EditorUtility.SetDirty(bezier); } }else{ if(GUILayout.Button("Add New Point Between")){ Undo.RegisterSceneUndo("Create a new Camera Path point"); bezier.AddNewPoint(i+1); EditorUtility.SetDirty(bezier); } } EditorGUILayout.EndHorizontal(); GUILayout.Space(7); GUILayout.Box(EditorGUIUtility.whiteTexture, GUILayout.Height(2), GUILayout.Width(Screen.width-25)); GUILayout.Space(7); } //EditorGUILayout.EndScrollView(); }else{ if(GUILayout.Button("Add New Point At End")) { Undo.RegisterSceneUndo("Create a new Camera Path point"); bezier.AddNewPoint(); EditorUtility.SetDirty(bezier); } EditorGUILayout.HelpBox("Click Add New Point to add points and begin the path, you will need two points to create a path.",MessageType.Info); } if(GUI.changed) { bezier.RecalculateStoredValues(); EditorUtility.SetDirty(bezier); } } }
32.768116
144
0.711632
[ "MIT" ]
GEngine-JP/chessgame
Assets/Scripts/Common/CameraPath/CameraPath2/Editor/CameraPathBezierEditor.cs
4,522
C#
// <auto-generated> // This file was automatically generated by Biohazrd and should not be modified by hand! // </auto-generated> #nullable enable using System.Runtime.InteropServices; [StructLayout(LayoutKind.Explicit, Size = 32)] public unsafe partial struct ImDrawCmdHeader { [FieldOffset(0)] public ImVec4 ClipRect; [FieldOffset(16)] public void* TextureId; [FieldOffset(24)] public uint VtxOffset; }
26.25
88
0.752381
[ "MIT" ]
PathogenPlayground/InfectedImGui
InfectedImGui/#Generated/ImDrawCmdHeader.cs
420
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Toastmasters.Web.Models; namespace Toastmasters.Web.Controllers { public class HomeController : Controller { public IActionResult Index() { return View(); } public IActionResult About() { ViewData["Message"] = ""; return View(); } public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
22.2
112
0.617117
[ "MIT" ]
bsstahl/ToastmastersAgenda
src/Toastmasters.Web/Controllers/HomeController.cs
668
C#
/* * Copyright (C) 2014 Google Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Collections; using GooglePlayGames.BasicApi; using GooglePlayGames.BasicApi.Multiplayer; using GooglePlayGames.BasicApi.SavedGame; namespace GooglePlayGames.UnitTests { class BaseMockPlayGamesClient : IPlayGamesClient { internal bool Authenticated { get; set; } internal BaseMockPlayGamesClient() { Authenticated = true; } public virtual void Authenticate(System.Action<bool> callback, bool silent) { throw new NotSupportedException("unsupported"); } public bool IsAuthenticated() { return Authenticated; } public virtual void SignOut() { throw new NotSupportedException("unsupported"); } public virtual string GetUserId() { throw new NotSupportedException("unsupported"); } public virtual string GetUserDisplayName() { throw new NotSupportedException("unsupported"); } public string GetUserImageUrl() { throw new NotImplementedException("unsupported"); } public List<Achievement> GetAchievements() { throw new NotSupportedException("unsupported"); } public virtual Achievement GetAchievement(string achId) { throw new NotSupportedException("unsupported"); } public virtual void UnlockAchievement(string achId, Action<bool> callback) { throw new NotSupportedException("unsupported"); } public virtual void RevealAchievement(string achId, Action<bool> callback) { throw new NotSupportedException("unsupported"); } public virtual void IncrementAchievement(string achId, int steps, Action<bool> callback) { throw new NotSupportedException("unsupported"); } public virtual void ShowAchievementsUI() { throw new NotSupportedException("unsupported"); } public virtual void ShowLeaderboardUI(string lbId) { throw new NotSupportedException("unsupported"); } public virtual void SubmitScore(string lbId, long score, Action<bool> callback) { throw new NotSupportedException("unsupported"); } public virtual void LoadState(int slot, OnStateLoadedListener listener) { throw new NotSupportedException("unsupported"); } public virtual void UpdateState(int slot, byte[] data, OnStateLoadedListener listener) { throw new NotSupportedException("unsupported"); } public BasicApi.Multiplayer.IRealTimeMultiplayerClient GetRtmpClient() { throw new NotSupportedException("unsupported"); } public BasicApi.Multiplayer.ITurnBasedMultiplayerClient GetTbmpClient() { throw new NotSupportedException("unsupported"); } public BasicApi.SavedGame.ISavedGameClient GetSavedGameClient() { throw new NotSupportedException("unsupported"); } public void RegisterInvitationDelegate(InvitationReceivedDelegate deleg) { throw new NotSupportedException("unsupported"); } public Invitation GetInvitationFromNotification() { throw new NotSupportedException("unsupported"); } public bool HasInvitationFromNotification() { throw new NotSupportedException("unsupported"); } static void NotSupported() { throw new NotSupportedException("unsupported"); } } }
30.637795
94
0.716525
[ "Apache-2.0" ]
3dln/play-games-plugin-for-unity
source/PluginDev.UnitTests/GooglePlayGames/ISocialPlatform/BaseMockPlayGamesClient.cs
3,891
C#
using Microsoft.EntityFrameworkCore; using Webcom.Entidades; namespace Webcom { public class MyWebAppContext : DbContext { public DbSet<Produto> Produtos { get; set; } public DbSet<Pedido> Pedidos{ get; set; } public DbSet<ItemPedido> Itens { get; set; } public MyWebAppContext(DbContextOptions<MyWebAppContext> options) : base(options) { } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity<Produto>().HasKey(p => p.Id); modelBuilder.Entity<Pedido>().HasKey(p => p.Id); modelBuilder.Entity<ItemPedido>().HasKey(p => p.Id); base.OnModelCreating(modelBuilder); } public override int SaveChanges() { ChangeTracker.DetectChanges(); return base.SaveChanges(); } } }
26.909091
90
0.608108
[ "MIT" ]
alvaroutfpr/Visual_Studio
Webcom/Webcom/AcessoDados/MyWebAppContext.cs
890
C#
// Copyright (c) AlphaSierraPapa for the SharpDevelop Team (for details please see \doc\copyright.txt) // This code is distributed under MIT X11 license (for details please see \doc\license.txt) using System.Linq; using System.Text; namespace ICSharpCode.NRefactory.VB.Ast { /// <summary> /// Description of QualifiedType. /// </summary> public class QualifiedType : AstType { public static readonly Role<AstType> TargetRole = new Role<AstType>("Target", AstType.Null); public AstType Target { get { return GetChildByRole(TargetRole); } set { SetChildByRole(TargetRole, value); } } public string Name { get { return GetChildByRole (Roles.Identifier).Name; } // set { // SetChildByRole (Roles.Identifier, new Identifier (TextToken.Default, value, TextLocation.Empty)); // } } public Identifier NameToken { get { return GetChildByRole (Roles.Identifier); } } public QualifiedType(AstType target, Identifier name) { Target = target; SetChildByRole(Roles.Identifier, name); } public AstNodeCollection<AstType> TypeArguments { get { return GetChildrenByRole (Roles.TypeArgument); } } public override S AcceptVisitor<T, S> (IAstVisitor<T, S> visitor, T data) { return visitor.VisitQualifiedType(this, data); } protected internal override bool DoMatch(AstNode other, PatternMatching.Match match) { var o = other as QualifiedType; return o != null && MatchString(this.Name, o.Name) && this.Target.DoMatch(o.Target, match); } public override string ToString() { StringBuilder b = new StringBuilder(); b.Append(this.Target); b.Append('.'); b.Append(this.Name); if (this.TypeArguments.Any()) { b.Append('('); b.Append(string.Join(", ", this.TypeArguments)); b.Append(')'); } return b.ToString(); } } }
26.724638
104
0.684382
[ "MIT" ]
dnSpyEx/ILSpy
NRefactory.VB/ICSharpCode.NRefactory.VB/Ast/TypeName/QualifiedType.cs
1,847
C#
// <auto-generated /> namespace Redskap { using System.Diagnostics; using System.Runtime.CompilerServices; [CompilerGenerated] [DebuggerNonUserCode] internal static class FemaleNames { public static readonly string[] All = { "Aagot", "Aase", "Aashild", "Aasta", "Abigail", "Ada", "Adele", "Adelen", "Adelina", "Adriana", "Agata", "Agathe", "Agne", "Agnes", "Agnete", "Agnethe", "Agnieszka", "Aida", "Aileen", "Ailin", "Aina", "Aisha", "Alba", "Aleksandra", "Alette", "Alexandra", "Alfhild", "Alice", "Alicia", "Alicja", "Alida", "Alina", "Aline", "Alisa", "Alise", "Alma", "Alva", "Alvhild", "Alvilde", "Amal", "Amalia", "Amalie", "Amanda", "Amelia", "Amelie", "Amina", "Amira", "Amna", "Amy", "Ana", "Anastasia", "Anbjørg", "Andrea", "Andrine", "Ane", "Aneta", "Anett", "Anette", "Angela", "Angelica", "Angelika", "Angelina", "Anine", "Anisa", "Anita", "Anja", "Anlaug", "Ann", "Ann-Christin", "Ann-Helen", "Ann-Karin", "Ann-Kristin", "Ann-Mari", "Anna", "Annabelle", "Annbjørg", "Anne", "Anne-Berit", "Anne-Brit", "Anne-Britt", "Anne-Grete", "Anne-Grethe", "Anne-Kari", "Anne-Karin", "Anne-Kristin", "Anne-Lene", "Anne-Lise", "Anne-Mari", "Anne-Marie", "Anne-Marit", "Anne-Mette", "Anne-Sofie", "Anneli", "Annelise", "Annette", "Anni", "Annie", "Annika", "Anniken", "Annlaug", "Anny", "Antonia", "Aria", "Ariana", "Ariel", "Arna", "Arnhild", "Asbjørg", "Asha", "Aslaug", "Asma", "Asta", "Astri", "Astrid", "Aud", "Audhild", "Audny", "Aurora", "Ausra", "Ava", "Aya", "Ayan", "Ayla", "Aylin", "Ayse", "Azra", "Barbara", "Barbro", "Beata", "Beate", "Beathe", "Beatrice", "Belinda", "Bella", "Benedicte", "Benedikte", "Bente", "Benthe", "Bergit", "Bergliot", "Bergljot", "Berit", "Berta", "Bertha", "Bertine", "Betina", "Bettina", "Betty", "Bianca", "Birgit", "Birgith", "Birgitta", "Birgitte", "Birte", "Birthe", "Bjørg", "Bodil", "Borghild", "Borgny", "Bozena", "Brit", "Brita", "Brith", "Britt", "Britta", "Brynhild", "Bushra", "Camilla", "Carina", "Carine", "Carla", "Carmen", "Carolina", "Caroline", "Cassandra", "Catharina", "Catherine", "Cathrin", "Cathrine", "Catrine", "Cecilia", "Cecilie", "Celia", "Celina", "Celine", "Cesilie", "Charlotte", "Christel", "Christiane", "Christin", "Christina", "Christine", "Cicilie", "Cindy", "Clara", "Claudia", "Connie", "Cornelia", "Cristina", "Dagfrid", "Dagmar", "Dagny", "Dagrun", "Daiva", "Dalia", "Dana", "Daniela", "Daniella", "Danuta", "Daria", "Deborah", "Desiree", "Diana", "Dina", "Dominika", "Dordi", "Doris", "Dorota", "Dorthe", "Dorthea", "Ea", "Ebba", "Edda", "Edel", "Eden", "Edit", "Edita", "Edith", "Edle", "Edna", "Edny", "Edyta", "Egle", "Eileen", "Eilen", "Eilin", "Eir", "Eira", "Eiril", "Eirill", "Eirin", "Eivor", "Ekaterina", "Elbjørg", "Eldbjørg", "Eldrid", "Elea", "Eleah", "Elen", "Elena", "Elfrid", "Eli", "Eliana", "Elida", "Elin", "Elina", "Eline", "Elinor", "Elisa", "Elisabet", "Elisabeth", "Elise", "Eliza", "Elizabeth", "Ella", "Elle", "Ellen", "Ellie", "Ellinor", "Elly", "Elma", "Elna", "Elsa", "Else", "Else-Marie", "Elsie", "Elvira", "Elzbieta", "Ema", "Embla", "Emelie", "Emely", "Emilia", "Emilie", "Emilija", "Emily", "Emina", "Emine", "Emma", "Emmeli", "Emmeline", "Emmy", "Enya", "Erica", "Erika", "Erle", "Erna", "Ester", "Esther", "Eva", "Evelina", "Evelyn", "Evy", "Ewa", "Ewelina", "Fadumo", "Fanny", "Farah", "Fatemeh", "Fatima", "Fatma", "Felicia", "Filippa", "Fiona", "Fredrikke", "Freya", "Frid", "Frida", "Fride", "Frøya", "Frøydis", "Gabriela", "Gabriele", "Gabriella", "Gabrielle", "Galina", "Gerd", "Gerda", "Gina", "Gine", "Gintare", "Gitte", "Gjertrud", "Gloria", "Grace", "Grazyna", "Greta", "Grete", "Gretha", "Grethe", "Gro", "Gry", "Gudny", "Gudrun", "Gudveig", "Gun", "Gunda", "Gunhild", "Gunlaug", "Gunn", "Gunnbjørg", "Gunnhild", "Gunnlaug", "Gunnvor", "Gunvor", "Guri", "Guro", "Gyda", "Gøril", "Hafsa", "Hala", "Haldis", "Halima", "Halldis", "Hamdi", "Hana", "Hanan", "Hanna", "Hannah", "Hanne", "Harriet", "Hatice", "Hedda", "Hedvig", "Hege", "Heidi", "Helen", "Helena", "Helene", "Helga", "Helin", "Helle", "Hennie", "Henny", "Henriette", "Henrikke", "Herborg", "Herdis", "Hermine", "Hiba", "Hild", "Hilda", "Hilde", "Hildegunn", "Hildur", "Hjørdis", "Hodan", "Hong", "Huda", "Hulda", "Iben", "Ida", "Idun", "Idunn", "Ieva", "Ilona", "Iman", "Ina", "Ine", "Ines", "Inga", "Inge", "Ingebjørg", "Ingeborg", "Ingelin", "Inger", "Inger-Johanne", "Inger-Lise", "Inger-Marie", "Ingerid", "Ingfrid", "Inghild", "Ingjerd", "Ingri", "Ingrid", "Ingrida", "Ingun", "Ingunn", "Ingvil", "Ingvild", "Ingvill", "Iqra", "Iren", "Irena", "Irene", "Irina", "Iris", "Irma", "Irmelin", "Iryna", "Isa", "Isabel", "Isabell", "Isabella", "Isabelle", "Iselin", "Ivana", "Iwona", "Izabela", "Jacqueline", "Jamila", "Jana", "Jane", "Janet", "Janicke", "Janina", "Janita", "Janne", "Janniche", "Jannicke", "Jannike", "Jasmin", "Jasmina", "Jasmine", "Jeanett", "Jeanette", "Jelena", "Jenni", "Jennie", "Jennifer", "Jenny", "Jessica", "Jette", "Jill", "Joan", "Joanna", "Jofrid", "Johanna", "Johanne", "Jolanta", "Jorid", "Jorun", "Jorunn", "Josefine", "Josephine", "Judit", "Judith", "Julia", "Juliana", "Juliane", "Julianne", "Julie", "June", "Juni", "Jurgita", "Justyna", "Kaia", "Kaisa", "Kaja", "Kajsa", "Kamila", "Kamilla", "Karen", "Kari", "Kari-Anne", "Karianne", "Karin", "Karina", "Karine", "Karla", "Karolina", "Karoline", "Katarina", "Katarzyna", "Kate", "Katharina", "Kathe", "Katherine", "Kathinka", "Kathrin", "Kathrine", "Katinka", "Katja", "Katrin", "Katrina", "Katrine", "Kelly", "Kerstin", "Khadija", "Kim", "Kine", "Kinga", "Kira", "Kirsten", "Kirsti", "Kitty", "Kjellaug", "Kjellfrid", "Kjellrun", "Kjersti", "Kjerstin", "Klara", "Klaudia", "Kornelia", "Kristel", "Kristi", "Kristiane", "Kristin", "Kristina", "Kristine", "Krystyna", "Laila", "Lajla", "Lana", "Lara", "Larisa", "Laura", "Lea", "Leah", "Leikny", "Leila", "Lena", "Lene", "Leni", "Leona", "Leonora", "Leyla", "Liana", "Lidia", "Lilian", "Liliana", "Lilja", "Lill", "Lilli", "Lillian", "Lilly", "Lily", "Lin", "Lina", "Linda", "Lindis", "Line", "Linea", "Linn", "Linnea", "Lisa", "Lisbet", "Lisbeth", "Lise", "Liss", "Liv", "Liva", "Live", "Livia", "Liz", "Liza", "Lone", "Lotta", "Lotte", "Louise", "Lovise", "Lucia", "Lucy", "Luna", "Lydia", "Lykke", "Ma", "Madeleine", "Madelen", "Madelene", "Magda", "Magdalena", "Magna", "Magnhild", "Magni", "Magny", "Mai", "Mai-Britt", "Maia", "Maiken", "Maj", "Maja", "Malak", "Malena", "Malene", "Malgorzata", "Mali", "Malika", "Malin", "Maren", "Margaret", "Margareth", "Margarita", "Margit", "Margot", "Margrete", "Margrethe", "Margun", "Margunn", "Mari", "Mari-Ann", "Maria", "Mariam", "Marian", "Mariana", "Mariann", "Marianne", "Marie", "Mariel", "Mariell", "Marielle", "Marija", "Marina", "Marion", "Marit", "Marita", "Marlen", "Marlene", "Marry", "Marta", "Marte", "Martha", "Marthe", "Marthine", "Martina", "Martine", "Martyna", "Marwa", "Mary", "Mary-Ann", "Maryam", "Maryan", "Marzena", "Mathea", "Mathilda", "Mathilde", "Matilda", "Matilde", "Maud", "May", "May-Britt", "May-Liss", "Maya", "Maylen", "Medina", "Melanie", "Melina", "Melinda", "Melissa", "Merete", "Merethe", "Mette", "Mia", "Michaela", "Michelle", "Mie", "Mila", "Mildrid", "Milena", "Milla", "Mille", "Mimmi", "Mina", "Mira", "Miranda", "Miriam", "Mirjam", "Molly", "Mona", "Monica", "Monika", "Muna", "My", "Møyfrid", "Målfrid", "Nada", "Nadia", "Nadine", "Nadja", "Naima", "Najma", "Nancy", "Nanna", "Naomi", "Natalia", "Natalie", "Natasha", "Nathalie", "Nellie", "Nelly", "Ngoc", "Nicole", "Nicoline", "Nikola", "Nikoline", "Nina", "Ninni", "Noor", "Nora", "Norah", "Norma", "Norunn", "Nour", "Nova", "Oda", "Oddbjørg", "Oddfrid", "Oddlaug", "Oddny", "Oddrun", "Oddveig", "Oksana", "Olaug", "Olava", "Olea", "Olena", "Olga", "Oline", "Olivia", "Oliwia", "Othilie", "Otilie", "Patricia", "Patrycja", "Paula", "Paulina", "Pauline", "Peggy", "Pernille", "Petra", "Phuong", "Pia", "Rabia", "Rachel", "Ragna", "Ragne", "Ragnhild", "Ragni", "Rahel", "Rahma", "Rakel", "Ramona", "Rana", "Randi", "Rania", "Rannveig", "Ranveig", "Rasa", "Rebecca", "Rebecka", "Rebekka", "Regina", "Regine", "Reidun", "Reidunn", "Renata", "Renate", "Renathe", "Renee", "Rigmor", "Rikke", "Rina", "Rita", "Ronja", "Rosa", "Rose", "Runa", "Rut", "Ruta", "Ruth", "Rønnaug", "Saba", "Sabina", "Sabine", "Sabrina", "Sadia", "Safia", "Saga", "Sahar", "Sahra", "Saima", "Salma", "Samantha", "Samira", "Sana", "Sandra", "Sanja", "Sanna", "Sanne", "Sara", "Sarah", "Savannah", "Selam", "Selina", "Seline", "Selma", "Senait", "Serina", "Serine", "Sharon", "Sheila", "Shirin", "Sidra", "Sidsel", "Sienna", "Sigfrid", "Signe", "Signy", "Sigrid", "Sigrun", "Sigrunn", "Siham", "Silja", "Silje", "Silvia", "Simona", "Simone", "Sina", "Sine", "Siren", "Siri", "Siril", "Sissel", "Siv", "Siw", "Snefrid", "Sofia", "Sofie", "Sofija", "Sol", "Solbjørg", "Solfrid", "Solgunn", "Solrun", "Solveig", "Solvor", "Solvår", "Sonia", "Sonja", "Sophia", "Sophie", "Stella", "Stephanie", "Stina", "Stine", "Sumaya", "Sunniva", "Susan", "Susann", "Susanna", "Susanne", "Suzanne", "Svanhild", "Svetlana", "Sylvi", "Sylvia", "Sylwia", "Synne", "Synnøve", "Synøve", "Sølvi", "Tale", "Tamara", "Tanja", "Tanya", "Tara", "Tatiana", "Tatjana", "Tea", "Teresa", "Terese", "Thale", "Thanh", "Thea", "Thelma", "Theresa", "Therese", "Thi", "Thilde", "Thora", "Thordis", "Thu", "Thuy", "Tia", "Tilde", "Tilla", "Tina", "Tine", "Tiril", "Tirill", "Tomine", "Tone", "Tonje", "Tora", "Torbjørg", "Tordis", "Torgunn", "Torhild", "Toril", "Torild", "Torill", "Torun", "Torunn", "Tove", "Trine", "Trine-Lise", "Trude", "Turi", "Turid", "Tuva", "Tyra", "Ulla", "Ulrikke", "Una", "Une", "Unn", "Unni", "Urszula", "Vaida", "Valborg", "Valentina", "Valeria", "Vanessa", "Vanja", "Venche", "Venke", "Vera", "Veronica", "Veronika", "Veslemøy", "Vibecke", "Vibeke", "Victoria", "Vida", "Vigdis", "Viktoria", "Viktorija", "Vilde", "Vilja", "Vilje", "Vilma", "Viola", "Violeta", "Vivi", "Vivian", "Vår", "Vårin", "Wanja", "Wenche", "Wencke", "Wendy", "Wenke", "Weronika", "Wigdis", "Wiktoria", "Wilma", "Yasmin", "Ylva", "Yngvild", "Yvonne", "Zahra", "Zainab", "Zara", "Zeinab", "Zoe", "Zofia", "Zuzanna", "Ågot", "Åsa", "Åse", "Åshild", "Åslaug", "Åsne", "Åsta", }; } }
21.731329
45
0.269717
[ "MIT" ]
khellang/Redskap
src/Redskap/FemaleNames.cs
22,439
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Net; using System.Net.Sockets; using System.Threading; using System.Threading.Tasks; using Microsoft.Extensions.DependencyInjection; using NBitcoin; using NBitcoin.DataEncoders; using NBitcoin.Protocol; using NBitcoin.RPC; using Stratis.Bitcoin.Configuration; using Stratis.Bitcoin.Configuration.Logging; using Stratis.Bitcoin.Features.MemoryPool; using Stratis.Bitcoin.Features.Miner; using Stratis.Bitcoin.Features.Miner.Interfaces; using Stratis.Bitcoin.Interfaces; using Stratis.Bitcoin.P2P; using Stratis.Bitcoin.P2P.Peer; using Stratis.Bitcoin.P2P.Protocol.Payloads; using Stratis.Bitcoin.Utilities; using static Stratis.Bitcoin.BlockPulling.BlockPuller; namespace Stratis.Bitcoin.IntegrationTests.Common.EnvironmentMockUpHelpers { public class CoreNode { /// <summary>Factory for creating P2P network peers.</summary> private readonly INetworkPeerFactory networkPeerFactory; private int[] ports; private NodeRunner runner; private readonly NetworkCredential creds; private List<Transaction> transactions = new List<Transaction>(); private HashSet<OutPoint> locked = new HashSet<OutPoint>(); private Money fee = Money.Coins(0.0001m); private object lockObject = new object(); /// <summary>Location of the data directory for the node.</summary> public string DataFolder { get { return this.runner.DataFolder; } } public IPEndPoint Endpoint { get { return new IPEndPoint(IPAddress.Parse("127.0.0.1"), this.ports[0]); } } public string Config { get; } public NodeConfigParameters ConfigParameters { get; } = new NodeConfigParameters(); public bool CookieAuth { get; set; } public CoreNode(NodeRunner runner, NodeBuilder builder, Network network, string configfile) { this.runner = runner; this.State = CoreNodeState.Stopped; var pass = Encoders.Hex.EncodeData(RandomUtils.GetBytes(20)); this.creds = new NetworkCredential(pass, pass); this.Config = Path.Combine(this.runner.DataFolder, configfile); this.ConfigParameters.Import(builder.ConfigParameters); this.ports = new int[2]; this.FindPorts(this.ports); var loggerFactory = new ExtendedLoggerFactory(); loggerFactory.AddConsoleWithFilters(); this.networkPeerFactory = new NetworkPeerFactory(network, DateTimeProvider.Default, loggerFactory, new PayloadProvider().DiscoverPayloads(), new SelfEndpointTracker(), NodeSettings.Default()); } /// <summary>Get stratis full node if possible.</summary> public FullNode FullNode { get { return this.runner.FullNode; } } public void Sync(CoreNode node, bool keepConnection = false) { var rpc = this.CreateRPCClient(); var rpc1 = node.CreateRPCClient(); rpc.AddNode(node.Endpoint, true); while (rpc.GetBestBlockHash() != rpc1.GetBestBlockHash()) { Thread.Sleep(200); } if (!keepConnection) rpc.RemoveNode(node.Endpoint); } public CoreNodeState State { get; private set; } public int ProtocolPort { get { return this.ports[0]; } } private string GetRPCAuth() { if (!CookieAuth) return creds.UserName + ":" + creds.Password; else return "cookiefile=" + Path.Combine(this.runner.DataFolder, "regtest", ".cookie"); } public void NotInIBD() { (this.FullNode.NodeService<IInitialBlockDownloadState>() as InitialBlockDownloadStateMock).SetIsInitialBlockDownload(false, DateTime.UtcNow.AddMinutes(5)); } public RPCClient CreateRPCClient() { return new RPCClient(this.GetRPCAuth(), new Uri("http://127.0.0.1:" + this.ports[1].ToString() + "/"), Network.RegTest); } public RestClient CreateRESTClient() { return new RestClient(new Uri("http://127.0.0.1:" + this.ports[1].ToString() + "/")); } public INetworkPeer CreateNetworkPeerClient() { return this.networkPeerFactory.CreateConnectedNetworkPeerAsync("127.0.0.1:" + this.ports[0].ToString()).GetAwaiter().GetResult(); } public void Start() { Directory.CreateDirectory(this.runner.DataFolder); var config = new NodeConfigParameters(); config.Add("regtest", "1"); config.Add("rest", "1"); config.Add("server", "1"); config.Add("txindex", "1"); if (!CookieAuth) { config.Add("rpcuser", creds.UserName); config.Add("rpcpassword", creds.Password); } config.Add("port", this.ports[0].ToString()); config.Add("rpcport", this.ports[1].ToString()); config.Add("printtoconsole", "1"); config.Add("keypool", "10"); config.Add("agentprefix", "node" + this.ports[0].ToString()); config.Import(this.ConfigParameters); File.WriteAllText(this.Config, config.ToString()); lock (this.lockObject) { this.runner.Start(); this.State = CoreNodeState.Starting; } if (this.runner is BitcoinCoreRunner) StartBitcoinCoreRunner(); else StartStratisRunner(); this.State = CoreNodeState.Running; } public void Restart() { this.Kill(); this.Start(); } private void StartBitcoinCoreRunner() { while (true) { try { CreateRPCClient().GetBlockHashAsync(0).GetAwaiter().GetResult(); this.State = CoreNodeState.Running; break; } catch { } Task.Delay(200); } } private void StartStratisRunner() { while (true) { if (this.runner.FullNode == null) { Thread.Sleep(100); continue; } if (this.runner.FullNode.State == FullNodeState.Started) break; else Thread.Sleep(200); } } private void FindPorts(int[] ports) { int i = 0; while (i < ports.Length) { var port = RandomUtils.GetUInt32() % 4000; port = port + 10000; if (ports.Any(p => p == port)) continue; try { TcpListener l = new TcpListener(IPAddress.Loopback, (int)port); l.Start(); l.Stop(); ports[i] = (int)port; i++; } catch (SocketException) { } } } public void Broadcast(Transaction transaction) { using (INetworkPeer peer = this.CreateNetworkPeerClient()) { peer.VersionHandshakeAsync().GetAwaiter().GetResult(); peer.SendMessageAsync(new InvPayload(transaction)).GetAwaiter().GetResult(); peer.SendMessageAsync(new TxPayload(transaction)).GetAwaiter().GetResult(); this.PingPongAsync(peer).GetAwaiter().GetResult(); } } /// <summary> /// Emit a ping and wait the pong. /// </summary> /// <param name="cancellation"></param> /// <param name="peer"></param> /// <returns>Latency.</returns> public async Task<TimeSpan> PingPongAsync(INetworkPeer peer, CancellationToken cancellation = default(CancellationToken)) { using (var listener = new NetworkPeerListener(peer)) { var ping = new PingPayload() { Nonce = RandomUtils.GetUInt64() }; DateTimeOffset before = DateTimeOffset.UtcNow; await peer.SendMessageAsync(ping); while ((await listener.ReceivePayloadAsync<PongPayload>(cancellation).ConfigureAwait(false)).Nonce != ping.Nonce) { } DateTimeOffset after = DateTimeOffset.UtcNow; return after - before; } } public void SelectMempoolTransactions() { var rpc = this.CreateRPCClient(); var txs = rpc.GetRawMempool(); var tasks = txs.Select(t => rpc.GetRawTransactionAsync(t)).ToArray(); Task.WaitAll(tasks); this.transactions.AddRange(tasks.Select(t => t.Result).ToArray()); } public void Split(Money amount, int parts) { var rpc = this.CreateRPCClient(); TransactionBuilder builder = new TransactionBuilder(this.FullNode.Network); builder.AddKeys(rpc.ListSecrets().OfType<ISecret>().ToArray()); builder.AddCoins(rpc.ListUnspent().Select(c => c.AsCoin())); var secret = this.GetFirstSecret(rpc); foreach (var part in (amount - this.fee).Split(parts)) { builder.Send(secret, part); } builder.SendFees(this.fee); builder.SetChange(secret); var tx = builder.BuildTransaction(true); this.Broadcast(tx); } public void Kill() { lock (this.lockObject) { this.runner.Kill(); this.State = CoreNodeState.Killed; } } public DateTimeOffset? MockTime { get; set; } public void SetMinerSecret(BitcoinSecret secret) { this.CreateRPCClient().ImportPrivKey(secret); this.MinerSecret = secret; } public void SetDummyMinerSecret(BitcoinSecret secret) { this.MinerSecret = secret; } public BitcoinSecret MinerSecret { get; private set; } public async Task<Block[]> GenerateAsync(int blockCount, bool includeUnbroadcasted = true, bool broadcast = true) { var rpc = this.CreateRPCClient(); BitcoinSecret dest = this.GetFirstSecret(rpc); var bestBlock = rpc.GetBestBlockHash(); ConcurrentChain chain = null; List<Block> blocks = new List<Block>(); DateTimeOffset now = this.MockTime == null ? DateTimeOffset.UtcNow : this.MockTime.Value; using (INetworkPeer peer = this.CreateNetworkPeerClient()) { peer.VersionHandshakeAsync().GetAwaiter().GetResult(); chain = bestBlock == peer.Network.GenesisHash ? new ConcurrentChain(peer.Network) : this.GetChain(peer); for (int i = 0; i < blockCount; i++) { uint nonce = 0; Block block = new Block(); block.Header.HashPrevBlock = chain.Tip.HashBlock; block.Header.Bits = block.Header.GetWorkRequired(rpc.Network, chain.Tip); block.Header.UpdateTime(now, rpc.Network, chain.Tip); var coinbase = new Transaction(); coinbase.AddInput(TxIn.CreateCoinbase(chain.Height + 1)); coinbase.AddOutput(new TxOut(rpc.Network.GetReward(chain.Height + 1), dest.GetAddress())); block.AddTransaction(coinbase); if (includeUnbroadcasted) { this.transactions = this.Reorder(this.transactions); block.Transactions.AddRange(this.transactions); this.transactions.Clear(); } block.UpdateMerkleRoot(); while (!block.CheckProofOfWork(rpc.Network.Consensus)) block.Header.Nonce = ++nonce; blocks.Add(block); chain.SetTip(block.Header); } if (broadcast) await this.BroadcastBlocksAsync(blocks.ToArray(), peer); } return blocks.ToArray(); } /// <summary> /// Get the chain of headers from the peer (thread safe). /// </summary> /// <param name="peer">Peer to get chain from.</param> /// <param name="hashStop">The highest block wanted.</param> /// <param name="cancellationToken"></param> /// <returns>The chain of headers.</returns> private ConcurrentChain GetChain(INetworkPeer peer, uint256 hashStop = null, CancellationToken cancellationToken = default(CancellationToken)) { ConcurrentChain chain = new ConcurrentChain(peer.Network); this.SynchronizeChain(peer, chain, hashStop, cancellationToken); return chain; } /// <summary> /// Synchronize a given Chain to the tip of the given node if its height is higher. (Thread safe). /// </summary> /// <param name="peer">Node to synchronize the chain for.</param> /// <param name="chain">The chain to synchronize.</param> /// <param name="hashStop">The location until which it synchronize.</param> /// <param name="cancellationToken"></param> /// <returns></returns> private IEnumerable<ChainedHeader> SynchronizeChain(INetworkPeer peer, ChainBase chain, uint256 hashStop = null, CancellationToken cancellationToken = default(CancellationToken)) { ChainedHeader oldTip = chain.Tip; List<ChainedHeader> headers = this.GetHeadersFromFork(peer, oldTip, hashStop, cancellationToken).ToList(); if (headers.Count == 0) return new ChainedHeader[0]; ChainedHeader newTip = headers[headers.Count - 1]; if (newTip.Height <= oldTip.Height) throw new ProtocolException("No tip should have been recieved older than the local one"); foreach (ChainedHeader header in headers) { if (!header.Validate(peer.Network)) { throw new ProtocolException("A header which does not pass proof of work verification has been received"); } } chain.SetTip(newTip); return headers; } private async Task AssertStateAsync(INetworkPeer peer, NetworkPeerState peerState, CancellationToken cancellationToken = default(CancellationToken)) { if ((peerState == NetworkPeerState.HandShaked) && (peer.State == NetworkPeerState.Connected)) await peer.VersionHandshakeAsync(cancellationToken); if (peerState != peer.State) throw new InvalidOperationException("Invalid Node state, needed=" + peerState + ", current= " + this.State); } public IEnumerable<ChainedHeader> GetHeadersFromFork(INetworkPeer peer, ChainedHeader currentTip, uint256 hashStop = null, CancellationToken cancellationToken = default(CancellationToken)) { this.AssertStateAsync(peer, NetworkPeerState.HandShaked, cancellationToken).GetAwaiter().GetResult(); using (var listener = new NetworkPeerListener(peer)) { int acceptMaxReorgDepth = 0; while (true) { // Get before last so, at the end, we should only receive 1 header equals to this one (so we will not have race problems with concurrent GetChains). BlockLocator awaited = currentTip.Previous == null ? currentTip.GetLocator() : currentTip.Previous.GetLocator(); peer.SendMessageAsync(new GetHeadersPayload() { BlockLocators = awaited, HashStop = hashStop }).GetAwaiter().GetResult(); while (true) { bool isOurs = false; HeadersPayload headers = null; using (var headersCancel = CancellationTokenSource.CreateLinkedTokenSource(cancellationToken)) { headersCancel.CancelAfter(TimeSpan.FromMinutes(1.0)); try { headers = listener.ReceivePayloadAsync<HeadersPayload>(headersCancel.Token).GetAwaiter().GetResult(); } catch (OperationCanceledException) { acceptMaxReorgDepth += 6; if (cancellationToken.IsCancellationRequested) throw; // Send a new GetHeaders. break; } } // In the special case where the remote node is at height 0 as well as us, then the headers count will be 0. if ((headers.Headers.Count == 0) && (peer.PeerVersion.StartHeight == 0) && (currentTip.HashBlock == peer.Network.GenesisHash)) yield break; if ((headers.Headers.Count == 1) && (headers.Headers[0].GetHash() == currentTip.HashBlock)) yield break; foreach (BlockHeader header in headers.Headers) { uint256 hash = header.GetHash(); if (hash == currentTip.HashBlock) continue; // The previous headers request timeout, this can arrive in case of big reorg. if (header.HashPrevBlock != currentTip.HashBlock) { int reorgDepth = 0; ChainedHeader tempCurrentTip = currentTip; while (reorgDepth != acceptMaxReorgDepth && tempCurrentTip != null && header.HashPrevBlock != tempCurrentTip.HashBlock) { reorgDepth++; tempCurrentTip = tempCurrentTip.Previous; } if (reorgDepth != acceptMaxReorgDepth && tempCurrentTip != null) currentTip = tempCurrentTip; } if (header.HashPrevBlock == currentTip.HashBlock) { isOurs = true; currentTip = new ChainedHeader(header, hash, currentTip); yield return currentTip; if (currentTip.HashBlock == hashStop) yield break; } else break; // Not our headers, continue receive. } if (isOurs) break; //Go ask for next header. } } } } public bool AddToStratisMempool(Transaction trx) { var fullNode = (this.runner as StratisBitcoinPowRunner).FullNode; var state = new MempoolValidationState(true); return fullNode.MempoolManager().Validator.AcceptToMemoryPool(state, trx).Result; } public List<uint256> GenerateStratisWithMiner(int blockCount) { return this.FullNode.Services.ServiceProvider.GetService<IPowMining>().GenerateBlocks(new ReserveScript { ReserveFullNodeScript = this.MinerSecret.ScriptPubKey }, (ulong)blockCount, uint.MaxValue); } [Obsolete("Please use GenerateStratisWithMiner instead.")] public Block[] GenerateStratis(int blockCount, List<Transaction> passedTransactions = null, bool broadcast = true) { var fullNode = (this.runner as StratisBitcoinPowRunner).FullNode; BitcoinSecret dest = this.MinerSecret; List<Block> blocks = new List<Block>(); DateTimeOffset now = this.MockTime == null ? DateTimeOffset.UtcNow : this.MockTime.Value; #if !NOSOCKET for (int i = 0; i < blockCount; i++) { uint nonce = 0; Block block = new Block(); block.Header.HashPrevBlock = fullNode.Chain.Tip.HashBlock; block.Header.Bits = block.Header.GetWorkRequired(fullNode.Network, fullNode.Chain.Tip); block.Header.UpdateTime(now, fullNode.Network, fullNode.Chain.Tip); var coinbase = new Transaction(); coinbase.AddInput(TxIn.CreateCoinbase(fullNode.Chain.Height + 1)); coinbase.AddOutput(new TxOut(fullNode.Network.GetReward(fullNode.Chain.Height + 1), dest.GetAddress())); block.AddTransaction(coinbase); if (passedTransactions?.Any() ?? false) { passedTransactions = this.Reorder(passedTransactions); block.Transactions.AddRange(passedTransactions); } block.UpdateMerkleRoot(); while (!block.CheckProofOfWork(fullNode.Network.Consensus)) block.Header.Nonce = ++nonce; blocks.Add(block); if (broadcast) { uint256 blockHash = block.GetHash(); var newChain = new ChainedHeader(block.Header, blockHash, fullNode.Chain.Tip); var oldTip = fullNode.Chain.SetTip(newChain); fullNode.ConsensusLoop().Puller.InjectBlock(blockHash, new DownloadedBlock { Length = block.GetSerializedSize(), Block = block }, CancellationToken.None); //try //{ // var blockResult = new BlockResult { Block = block }; // fullNode.ConsensusLoop.AcceptBlock(blockResult); // // similar logic to what's in the full node code // if (blockResult.Error == null) // { // fullNode.ChainBehaviorState.ConsensusTip = fullNode.ConsensusLoop.Tip; // //if (fullNode.Chain.Tip.HashBlock == blockResult.ChainedHeader.HashBlock) // //{ // // var unused = cache.FlushAsync(); // //} // fullNode.Signals.Blocks.Broadcast(block); // } //} //catch (ConsensusErrorException) //{ // // set back the old tip // fullNode.Chain.SetTip(oldTip); //} } } return blocks.ToArray(); #endif } public async Task BroadcastBlocksAsync(Block[] blocks) { using (INetworkPeer peer = this.CreateNetworkPeerClient()) { await peer.VersionHandshakeAsync(); await this.BroadcastBlocksAsync(blocks, peer); } } public async Task BroadcastBlocksAsync(Block[] blocks, INetworkPeer peer) { foreach (var block in blocks) { await peer.SendMessageAsync(new InvPayload(block)); await peer.SendMessageAsync(new BlockPayload(block)); } await this.PingPongAsync(peer); } public Block[] FindBlock(int blockCount = 1, bool includeMempool = true) { this.SelectMempoolTransactions(); return this.GenerateAsync(blockCount, includeMempool).GetAwaiter().GetResult(); } private class TransactionNode { public uint256 Hash = null; public Transaction Transaction = null; public List<TransactionNode> DependsOn = new List<TransactionNode>(); public TransactionNode(Transaction tx) { this.Transaction = tx; this.Hash = tx.GetHash(); } } private List<Transaction> Reorder(List<Transaction> transactions) { if (transactions.Count == 0) return transactions; var result = new List<Transaction>(); var dictionary = transactions.ToDictionary(t => t.GetHash(), t => new TransactionNode(t)); foreach (var transaction in dictionary.Select(d => d.Value)) { foreach (var input in transaction.Transaction.Inputs) { var node = dictionary.TryGet(input.PrevOut.Hash); if (node != null) { transaction.DependsOn.Add(node); } } } while (dictionary.Count != 0) { foreach (var node in dictionary.Select(d => d.Value).ToList()) { foreach (var parent in node.DependsOn.ToList()) { if (!dictionary.ContainsKey(parent.Hash)) node.DependsOn.Remove(parent); } if (node.DependsOn.Count == 0) { result.Add(node.Transaction); dictionary.Remove(node.Hash); } } } return result; } private BitcoinSecret GetFirstSecret(RPCClient rpc) { if (this.MinerSecret != null) return this.MinerSecret; var dest = rpc.ListSecrets().FirstOrDefault(); if (dest == null) { var address = rpc.GetNewAddress(); dest = rpc.DumpPrivKey(address); } return dest; } } }
39.811573
209
0.529721
[ "MIT" ]
zorbtech/zorbit-core
src/Stratis.Bitcoin.IntegrationTests.Common/EnvironmentMockUpHelpers/CoreNode.cs
26,835
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.Network.V20200801 { /// <summary> /// Bastion Host resource. /// </summary> [AzureNativeResourceType("azure-native:network/v20200801:BastionHost")] public partial class BastionHost : Pulumi.CustomResource { /// <summary> /// FQDN for the endpoint on which bastion host is accessible. /// </summary> [Output("dnsName")] public Output<string?> DnsName { get; private set; } = null!; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> [Output("etag")] public Output<string> Etag { get; private set; } = null!; /// <summary> /// IP configuration of the Bastion Host resource. /// </summary> [Output("ipConfigurations")] public Output<ImmutableArray<Outputs.BastionHostIPConfigurationResponse>> IpConfigurations { get; private set; } = null!; /// <summary> /// Resource location. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// Resource name. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// The provisioning state of the bastion host resource. /// </summary> [Output("provisioningState")] public Output<string> ProvisioningState { get; private set; } = null!; /// <summary> /// Resource tags. /// </summary> [Output("tags")] public Output<ImmutableDictionary<string, string>?> Tags { get; private set; } = null!; /// <summary> /// Resource type. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a BastionHost resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public BastionHost(string name, BastionHostArgs args, CustomResourceOptions? options = null) : base("azure-native:network/v20200801:BastionHost", name, args ?? new BastionHostArgs(), MakeResourceOptions(options, "")) { } private BastionHost(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-native:network/v20200801:BastionHost", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:network/v20200801:BastionHost"}, new Pulumi.Alias { Type = "azure-native:network:BastionHost"}, new Pulumi.Alias { Type = "azure-nextgen:network:BastionHost"}, new Pulumi.Alias { Type = "azure-native:network/latest:BastionHost"}, new Pulumi.Alias { Type = "azure-nextgen:network/latest:BastionHost"}, new Pulumi.Alias { Type = "azure-native:network/v20190401:BastionHost"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190401:BastionHost"}, new Pulumi.Alias { Type = "azure-native:network/v20190601:BastionHost"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190601:BastionHost"}, new Pulumi.Alias { Type = "azure-native:network/v20190701:BastionHost"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190701:BastionHost"}, new Pulumi.Alias { Type = "azure-native:network/v20190801:BastionHost"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190801:BastionHost"}, new Pulumi.Alias { Type = "azure-native:network/v20190901:BastionHost"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20190901:BastionHost"}, new Pulumi.Alias { Type = "azure-native:network/v20191101:BastionHost"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191101:BastionHost"}, new Pulumi.Alias { Type = "azure-native:network/v20191201:BastionHost"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20191201:BastionHost"}, new Pulumi.Alias { Type = "azure-native:network/v20200301:BastionHost"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200301:BastionHost"}, new Pulumi.Alias { Type = "azure-native:network/v20200401:BastionHost"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200401:BastionHost"}, new Pulumi.Alias { Type = "azure-native:network/v20200501:BastionHost"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200501:BastionHost"}, new Pulumi.Alias { Type = "azure-native:network/v20200601:BastionHost"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200601:BastionHost"}, new Pulumi.Alias { Type = "azure-native:network/v20200701:BastionHost"}, new Pulumi.Alias { Type = "azure-nextgen:network/v20200701:BastionHost"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing BastionHost resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static BastionHost Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new BastionHost(name, id, options); } } public sealed class BastionHostArgs : Pulumi.ResourceArgs { /// <summary> /// The name of the Bastion Host. /// </summary> [Input("bastionHostName")] public Input<string>? BastionHostName { get; set; } /// <summary> /// FQDN for the endpoint on which bastion host is accessible. /// </summary> [Input("dnsName")] public Input<string>? DnsName { get; set; } /// <summary> /// Resource ID. /// </summary> [Input("id")] public Input<string>? Id { get; set; } [Input("ipConfigurations")] private InputList<Inputs.BastionHostIPConfigurationArgs>? _ipConfigurations; /// <summary> /// IP configuration of the Bastion Host resource. /// </summary> public InputList<Inputs.BastionHostIPConfigurationArgs> IpConfigurations { get => _ipConfigurations ?? (_ipConfigurations = new InputList<Inputs.BastionHostIPConfigurationArgs>()); set => _ipConfigurations = value; } /// <summary> /// Resource location. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; [Input("tags")] private InputMap<string>? _tags; /// <summary> /// Resource tags. /// </summary> public InputMap<string> Tags { get => _tags ?? (_tags = new InputMap<string>()); set => _tags = value; } public BastionHostArgs() { } } }
43.69802
135
0.586723
[ "Apache-2.0" ]
pulumi-bot/pulumi-azure-native
sdk/dotnet/Network/V20200801/BastionHost.cs
8,827
C#
using System; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Text; using System.Xml; /// <summary> /// Information about a Workbook in a Server's site /// </summary> class SiteWorkbook : SiteDocumentBase, IEditDataConnectionsSet { public readonly bool ShowTabs; //Note: [2015-10-28] Datasources presently don't return this information, so we need to make this workbook specific public readonly string ContentUrl; public readonly string DefaultViewId; /// <summary> /// If set, contains the set of data connections embedded in this workbooks /// </summary> private List<SiteConnection> _dataConnections; public ReadOnlyCollection<SiteConnection> DataConnections { get { var dataConnections = _dataConnections; if (dataConnections == null) return null; return dataConnections.AsReadOnly(); } } /// <summary> /// Constructor /// </summary> /// <param name="xmlWorkbookNode"></param> public SiteWorkbook(XmlNode xmlWorkbookNode) : base(xmlWorkbookNode) { if(xmlWorkbookNode.Name.ToLower() != "workbook") { AppDiagnostics.Assert(false, "Not a workbook"); throw new Exception("Unexpected content - not workbook"); } //Note: [2015-10-28] Datasources presently don't return this information, so we need to make this workbook specific this.ContentUrl = xmlWorkbookNode.Attributes["contentUrl"].Value; //Get the default view for the workbook this.DefaultViewId = XmlHelper.GetAttributeIfExists(xmlWorkbookNode, "defaultViewId"); //Do we have tabs? this.ShowTabs = XmlHelper.SafeParseXmlAttribute_Boolean(xmlWorkbookNode, "showTabs", false); } /// <summary> /// Friendly text /// </summary> /// <returns></returns> public override string ToString() { return "Workbook: " + Name + "/" + ContentUrl + "/" + Id + ", Proj: " + ProjectId; } /// <summary> /// Interface for inserting the set of data connections associated with this content /// </summary> /// <param name="connections"></param> void IEditDataConnectionsSet.SetDataConnections(IEnumerable<SiteConnection> connections) { if(connections == null) { _dataConnections = null; } _dataConnections = new List<SiteConnection>(connections); } }
32.064935
123
0.653301
[ "MIT" ]
tableau/TabProvision
src/ServerData/SiteWorkbook.cs
2,471
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.S3Outposts")] [assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - Amazon S3 on Outposts. Amazon S3 on Outposts expands object storage to on-premises AWS Outposts environments, enabling you to store and retrieve objects using S3 APIs and features.")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyProduct("Amazon Web Services SDK for .NET")] [assembly: AssemblyCompany("Amazon.com, Inc")] [assembly: AssemblyCopyright("Copyright 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.5.0.37")]
47.625
260
0.752625
[ "Apache-2.0" ]
rczwojdrak/aws-sdk-net
sdk/code-analysis/ServiceAnalysis/S3Outposts/Properties/AssemblyInfo.cs
1,524
C#
// // Socks5ClientTests.cs // // Author: Jeffrey Stedfast <jestedfa@microsoft.com> // // Copyright (c) 2013-2021 .NET Foundation and Contributors // // 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. // // Note: Find Socks5 proxy list here: http://www.gatherproxy.com/sockslist/country/?c=United%20States using System; using System.IO; using System.Net; using System.Net.Sockets; using System.Threading.Tasks; using NUnit.Framework; using MailKit.Security; using MailKit.Net.Proxy; namespace UnitTests.Net.Proxy { [TestFixture] public class Socks5ClientTests { public static readonly string[] Socks5ProxyList = { "98.174.90.36", "198.12.157.31", "72.210.252.134" }; public static readonly int[] Socks5ProxyPorts = { 1080, 46906, 46164 }; const int ConnectTimeout = 5 * 1000; // 5 seconds [Test] public void TestArgumentExceptions () { var credentials = new NetworkCredential ("user", "password"); var socks = new Socks5Client ("socks5.proxy.com", 0, credentials); Assert.Throws<ArgumentNullException> (() => new Socks4Client (null, 1080)); Assert.Throws<ArgumentException> (() => new Socks4Client (string.Empty, 1080)); Assert.Throws<ArgumentOutOfRangeException> (() => new Socks4Client (socks.ProxyHost, -1)); Assert.Throws<ArgumentNullException> (() => new Socks4Client (socks.ProxyHost, 1080, null)); Assert.AreEqual (5, socks.SocksVersion); Assert.AreEqual (1080, socks.ProxyPort); Assert.AreEqual ("socks5.proxy.com", socks.ProxyHost); Assert.AreEqual (credentials, socks.ProxyCredentials); Assert.Throws<ArgumentNullException> (() => socks.Connect (null, 80)); Assert.Throws<ArgumentNullException> (() => socks.Connect (null, 80, ConnectTimeout)); Assert.ThrowsAsync<ArgumentNullException> (async () => await socks.ConnectAsync (null, 80)); Assert.ThrowsAsync<ArgumentNullException> (async () => await socks.ConnectAsync (null, 80, ConnectTimeout)); Assert.Throws<ArgumentException> (() => socks.Connect (string.Empty, 80)); Assert.Throws<ArgumentException> (() => socks.Connect (string.Empty, 80, 100000)); Assert.ThrowsAsync<ArgumentException> (async () => await socks.ConnectAsync (string.Empty, 80)); Assert.ThrowsAsync<ArgumentException> (async () => await socks.ConnectAsync (string.Empty, 80, ConnectTimeout)); Assert.Throws<ArgumentOutOfRangeException> (() => socks.Connect ("www.google.com", 0)); Assert.Throws<ArgumentOutOfRangeException> (() => socks.Connect ("www.google.com", 0, ConnectTimeout)); Assert.ThrowsAsync<ArgumentOutOfRangeException> (async () => await socks.ConnectAsync ("www.google.com", 0)); Assert.ThrowsAsync<ArgumentOutOfRangeException> (async () => await socks.ConnectAsync ("www.google.com", 0, ConnectTimeout)); Assert.Throws<ArgumentOutOfRangeException> (() => socks.Connect ("www.google.com", 80, -ConnectTimeout)); Assert.ThrowsAsync<ArgumentOutOfRangeException> (async () => await socks.ConnectAsync ("www.google.com", 80, -ConnectTimeout)); } static string ResolveIPv4 (string host) { var ipAddresses = Dns.GetHostAddresses (host); for (int i = 0; i < ipAddresses.Length; i++) { if (ipAddresses[i].AddressFamily == AddressFamily.InterNetwork) return ipAddresses[i].ToString (); } return null; } static string ResolveIPv6 (string host) { var ipAddresses = Dns.GetHostAddresses (host); for (int i = 0; i < ipAddresses.Length; i++) { if (ipAddresses[i].AddressFamily == AddressFamily.InterNetworkV6) return ipAddresses[i].ToString (); } return null; } [Test] public void TestGetAddressType () { const string host = "www.google.com"; const string ipv6 = "2607:f8b0:400e:c03::69"; const string ipv4 = "74.125.197.99"; IPAddress ip; Assert.AreEqual (Socks5Client.Socks5AddressType.Domain, Socks5Client.GetAddressType (host, out ip)); Assert.AreEqual (Socks5Client.Socks5AddressType.IPv4, Socks5Client.GetAddressType (ipv4, out ip)); Assert.AreEqual (Socks5Client.Socks5AddressType.IPv6, Socks5Client.GetAddressType (ipv6, out ip)); } [Test] public void TestGetFailureReason () { for (byte i = 1; i < 10; i++) { var reason = Socks5Client.GetFailureReason (i); if (i > 8) Assert.IsTrue (reason.StartsWith ("Unknown error", StringComparison.Ordinal)); } } [Test] public void TestConnectAnonymous () { using (var proxy = new Socks5ProxyListener ()) { proxy.Start (IPAddress.Loopback, 0); var socks = new Socks5Client (proxy.IPAddress.ToString (), proxy.Port); Stream stream = null; try { stream = socks.Connect ("www.google.com", 80, ConnectTimeout); } catch (TimeoutException) { Assert.Inconclusive ("Timed out."); } catch (Exception ex) { Assert.Fail (ex.Message); } finally { stream?.Dispose (); } } } [Test] public async Task TestConnectAnonymousAsync () { using (var proxy = new Socks5ProxyListener ()) { proxy.Start (IPAddress.Loopback, 0); var socks = new Socks5Client (proxy.IPAddress.ToString (), proxy.Port); Stream stream = null; try { stream = await socks.ConnectAsync ("www.google.com", 80, ConnectTimeout); } catch (TimeoutException) { Assert.Inconclusive ("Timed out."); } catch (Exception ex) { Assert.Fail (ex.Message); } finally { stream?.Dispose (); } } } [Test] public void TestConnectWithCredentials () { using (var proxy = new Socks5ProxyListener ()) { proxy.Start (IPAddress.Loopback, 0); var credentials = new NetworkCredential ("username", "password"); var socks = new Socks5Client (proxy.IPAddress.ToString (), proxy.Port, credentials); Stream stream = null; try { stream = socks.Connect ("www.google.com", 80, ConnectTimeout); } catch (AuthenticationException) { // this is what we expect to get Assert.Pass ("Got an AuthenticationException just as expected"); } catch (TimeoutException) { Assert.Inconclusive ("Timed out."); } catch (Exception ex) { Assert.Fail (ex.Message); } finally { stream?.Dispose (); } } } [Test] public async Task TestConnectWithCredentialsAsync () { using (var proxy = new Socks5ProxyListener ()) { proxy.Start (IPAddress.Loopback, 0); var credentials = new NetworkCredential ("username", "password"); var socks = new Socks5Client (proxy.IPAddress.ToString (), proxy.Port, credentials); Stream stream = null; try { stream = await socks.ConnectAsync ("www.google.com", 80, ConnectTimeout); } catch (AuthenticationException) { // this is what we expect to get Assert.Pass ("Got an AuthenticationException just as expected"); } catch (TimeoutException) { Assert.Inconclusive ("Timed out."); } catch (Exception ex) { Assert.Fail (ex.Message); } finally { stream?.Dispose (); } } } [Test] public void TestConnectWithBadCredentials () { using (var proxy = new Socks5ProxyListener ()) { proxy.Start (IPAddress.Loopback, 0); var credentials = new NetworkCredential ("username", "bad"); var socks = new Socks5Client (proxy.IPAddress.ToString (), proxy.Port, credentials); Stream stream = null; try { stream = socks.Connect ("www.google.com", 80, ConnectTimeout); Assert.Fail ("Expected AuthenticationException"); } catch (AuthenticationException) { // this is what we expect to get Assert.Pass ("Got an AuthenticationException just as expected"); } catch (TimeoutException) { Assert.Inconclusive ("Timed out."); } catch (Exception ex) { Assert.Fail (ex.Message); } finally { stream?.Dispose (); } } } [Test] public async Task TestConnectWithBadCredentialsAsync () { using (var proxy = new Socks5ProxyListener ()) { proxy.Start (IPAddress.Loopback, 0); var credentials = new NetworkCredential ("username", "bad"); var socks = new Socks5Client (proxy.IPAddress.ToString (), proxy.Port, credentials); Stream stream = null; try { stream = await socks.ConnectAsync ("www.google.com", 80, ConnectTimeout); Assert.Fail ("Expected AuthenticationException"); } catch (AuthenticationException) { // this is what we expect to get Assert.Pass ("Got an AuthenticationException just as expected"); } catch (TimeoutException) { Assert.Inconclusive ("Timed out."); } catch (Exception ex) { Assert.Fail (ex.Message); } finally { stream?.Dispose (); } } } [Test] public void TestConnectByIPv4 () { using (var proxy = new Socks5ProxyListener ()) { proxy.Start (IPAddress.Loopback, 0); var socks = new Socks5Client (proxy.IPAddress.ToString (), proxy.Port); var host = "74.125.197.99"; // ResolveIPv4 ("www.google.com"); Stream stream = null; if (host == null) return; try { stream = socks.Connect (host, 80, ConnectTimeout); } catch (TimeoutException) { Assert.Inconclusive ("Timed out."); } catch (Exception ex) { Assert.Fail (ex.Message); } finally { stream?.Dispose (); } } } [Test] public async Task TestConnectByIPv4Async () { using (var proxy = new Socks5ProxyListener ()) { proxy.Start (IPAddress.Loopback, 0); var socks = new Socks5Client (proxy.IPAddress.ToString (), proxy.Port); var host = "74.125.197.99"; // ResolveIPv4 ("www.google.com"); Stream stream = null; if (host == null) return; try { stream = await socks.ConnectAsync (host, 80, ConnectTimeout); } catch (TimeoutException) { Assert.Inconclusive ("Timed out."); } catch (Exception ex) { Assert.Fail (ex.Message); } finally { stream?.Dispose (); } } } [Test] public void TestConnectByIPv6 () { using (var proxy = new Socks5ProxyListener ()) { proxy.Start (IPAddress.Loopback, 0); var socks = new Socks5Client (proxy.IPAddress.ToString (), proxy.Port); var host = "2607:f8b0:400e:c03::69"; // ResolveIPv6 ("www.google.com"); Stream stream = null; if (host == null) return; try { stream = socks.Connect (host, 80, ConnectTimeout); } catch (ProxyProtocolException ex) { Assert.IsTrue (ex.Message.StartsWith ($"Failed to connect to {host}:80: ", StringComparison.Ordinal), ex.Message); Assert.Inconclusive (ex.Message); } catch (TimeoutException) { Assert.Inconclusive ("Timed out."); } catch (Exception ex) { Assert.Fail (ex.Message); } finally { stream?.Dispose (); } } } [Test] public async Task TestConnectByIPv6Async () { using (var proxy = new Socks5ProxyListener ()) { proxy.Start (IPAddress.Loopback, 0); var socks = new Socks5Client (proxy.IPAddress.ToString (), proxy.Port); var host = "2607:f8b0:400e:c03::69"; // ResolveIPv6 ("www.google.com"); Stream stream = null; if (host == null) return; try { stream = await socks.ConnectAsync (host, 80, ConnectTimeout); } catch (ProxyProtocolException ex) { Assert.IsTrue (ex.Message.StartsWith ($"Failed to connect to {host}:80: ", StringComparison.Ordinal), ex.Message); Assert.Inconclusive (ex.Message); } catch (TimeoutException) { Assert.Inconclusive ("Timed out."); } catch (Exception ex) { Assert.Fail (ex.Message); } finally { stream?.Dispose (); } } } [Test] public async Task TestTimeoutException () { using (var proxy = new Socks5ProxyListener ()) { proxy.Start (IPAddress.Loopback, 0); var socks = new Socks5Client (proxy.IPAddress.ToString (), proxy.Port); Stream stream = null; try { stream = await socks.ConnectAsync ("example.com", 25, 1000); } catch (TimeoutException) { Assert.Pass (); } catch (Exception ex) { Assert.Fail (ex.Message); } finally { stream?.Dispose (); } } } } }
32.126551
130
0.670812
[ "MIT" ]
Bartizan/MailKit
UnitTests/Net/Proxy/Socks5ClientTests.cs
12,949
C#
using ElGuerre.Microservices.Billing.Api.Domain.Events; using ElGuerre.Microservices.Billing.Api.Domain.Interfaces; using ElGuerre.Microservices.Billing.Api.Infrastructure.Repositories; using ElGuerre.Microservices.Messages; using ElGuerre.Microservices.Shared.Infrastructure; using MediatR; using Microsoft.Extensions.Logging; using System; using System.Collections.Generic; using System.Linq; using System.Threading; using System.Threading.Tasks; namespace ElGuerre.Microservices.Billing.Api.Application.Commands { public class OrderReadyToBillCommandHandler : IRequestHandler<OrderReadyToBillCommand, bool> { private readonly ILogger _logger; private readonly IMediator _mediator; private readonly IPayRepository _repository; private readonly IIntegrationService _integrationService; public OrderReadyToBillCommandHandler(ILogger<OrderReadyToBillCommand> logger, IMediator mediator, IPayRepository repository, IIntegrationService integrationService) { _logger = logger; _mediator = mediator; _repository = repository; _integrationService = integrationService; } public async Task<bool> Handle(OrderReadyToBillCommand request, CancellationToken cancellationToken) { return await Task.FromResult(true); } } }
32.153846
167
0.827751
[ "MIT" ]
juanluelguerre/Microservices
src/ElGuerre.Microservices.Billing.Api/Application/Commands/OrderReadyToBillCommandHandler.cs
1,256
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SuspensionHeight : MonoBehaviour,IModSystemSlot { public void PartAdded(string Type, string Part) { try { if (Type == "SuspensionHeight") { float height = 0.20f; switch (Part) { case "HighHeight": height = 0.30f; break; case "LowHeight": height = 0.14f; break; default: break; } foreach (var item in GetComponentsInChildren<WheelCollider>()) { item.suspensionDistance = height; } } } catch (System.Exception e) { Debug.LogError(e); } } public void PartNulled(string Type) { } }
23.604651
78
0.417734
[ "MIT" ]
sowa705/openchase
Assets/Scripts/SuspensionHeight.cs
1,017
C#
using Final_Fantasy_Tryout.Units.PlayerInfo; namespace Final_Fantasy_Tryout.Inventory { public class Bag : PlayerInventory { private const string name = "Bag"; private const int capacity = 50; public Bag() { this.Name = name; this.Capacity = capacity; } } }
21
45
0.589286
[ "MIT" ]
TnS101/Final-Fantasy-Tryout
src/Final Fantasy Tryout/Inventory/Bag.cs
338
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. using System; using FASTER.core; using FASTER.server; namespace FASTER.remote.test { internal static class TestUtils { /// <summary> /// Address /// </summary> public static string Address = "127.0.0.1"; /// <summary> /// Port /// </summary> public static int Port = 33278; /// <summary> /// Create VarLenServer /// </summary> public static FixedLenServer<long, long, long, long, SimpleFunctions<long, long, long>> CreateFixedLenServer(string logDir, Func<long, long, long> merger, bool enablePubSub = true, bool tryRecover = false) { ServerOptions opts = new() { LogDir = logDir, Address = Address, Port = Port, EnablePubSub = enablePubSub, Recover = tryRecover, IndexSize = "1m", }; return new FixedLenServer<long, long, long, long, SimpleFunctions<long, long, long>>(opts, e => new SimpleFunctions<long, long, long>(merger)); } /// <summary> /// Create VarLenServer /// </summary> public static VarLenServer CreateVarLenServer(string logDir, bool enablePubSub = true, bool tryRecover = false) { ServerOptions opts = new() { LogDir = logDir, Address = Address, Port = Port, EnablePubSub = enablePubSub, Recover = tryRecover, IndexSize = "1m", }; return new VarLenServer(opts); } } }
31.178571
213
0.530355
[ "MIT" ]
TedHartMS/FASTER
cs/remote/test/FASTER.remote.test/TestUtils.cs
1,748
C#
using StoreModels; using System.Collections.Generic; namespace StoreMVC.Models { public interface IMapper { Customer cast2Customer(CustomerCRVM customer2BCasted); CustomerIndexVM cast2CustomerIndexVM(Customer customer2BCasted); CustomerCRVM cast2CustomerCRVM(Customer customer); CustomerEditVM cast2CustomerEditVM(Customer customer); Customer cast2Customer(CustomerEditVM customer2bCasted); // bool verifyPW(string pwHash, string newPW); // Manager cast2Manager(ManagerCRVM manager2BCasted); ManagerIndexVM cast2ManagerIndexVM(Manager manager2BCasted); ManagerCRVM cast2ManagerCRVM(Manager manager); ManagerEditVM cast2ManagerEditVM(Manager manager); Manager cast2Manager(ManagerEditVM manager2bCasted); // Location cast2Location(LocCRVM location2BCasted); LocIndexVM cast2LocationIndexVM(Location location2BCasted); LocCRVM cast2LocationCRVM(Location location); LocEditVM cast2LocationEditVM(Location location); Location cast2Location(LocEditVM location2bCasted); // Product cast2Product(ProductCRVM product2BCasted); ProductIndexVM cast2ProductIndexVM(Product product2BCasted); ProductCRVM cast2ProductCRVM(Product product); ProductEditVM cast2ProductEditVM(Product product); Product cast2Product(ProductEditVM product2bCasted); // InventoryLineItem cast2InventoryLineItem(InvLineItemCRVM inventoryLineItem2BCasted); InvLineItemIndexVM cast2InventoryLineItemIndexVM(InventoryLineItem inventoryLineItem2BCasted, Product product); InvLineItemCRVM cast2InventoryLineItemCRVM(InventoryLineItem inventoryLineItem); InvLineItemEditVM cast2InventoryLineItemEditVM(InventoryLineItem inventoryLineItem, Product product); InventoryLineItem cast2InventoryLineItem(InvLineItemEditVM inventoryLineItem2BCasted); // CustomerOrderLineItem cast2OrderLineItem(OrderItemVM orderItem2BCasted); OrderItemVM cast2OrderItemVM(InventoryLineItem inventoryLineItem2BCasted, Product product); // CustomerCart cast2Cart(CartCRVM cart2BCasted, int orderID); CartIndexVM cast2CartIndexVM(CustomerOrderLineItem coli2BCasted, Product product2BCasted); CartCRVM cast2CartCRVM(CustomerCart cart); CartEditVM cast2CartEditVM(CustomerCart cart); CustomerCart cast2Cart(CartEditVM cart2bCasted, int orderID); // CustomerOrderHistory cast2OrderHistory(OrderHistoryCRVM orderHistory2BCasted); OrderHistoryIndexVM cast2OrderHistoryIndexVM(CustomerOrderHistory orderHistory2BCasted, Location loc, List<CartIndexVM> cart2BCasted); OrderHistoryCRVM cast2OrderHistoryCRVM(CustomerOrderHistory orderHistory); } }
52.685185
142
0.766257
[ "MIT" ]
rjhakes/Rich_Hakes-P1
StoreApp/StoreMVC/Models/IMapper.cs
2,847
C#
namespace DocoptNet { public partial class DocoptArgumentsAttribute { } }
15.6
53
0.769231
[ "MIT" ]
GerHobbelt/docopt.net
src/DocoptNet/CodeGeneration/Public.cs
78
C#
using System; using System.Collections.Generic; using System.Linq; using WebApp.Models; namespace WebApp { public class ArticleRepository { private List<Article> articles = new List<Article> { new Article { Id = 1, Title = "What is Lorem Ipsum?", Author= "Gaurav Gahlot", PublishedOn = new DateTime(2019, 01, 20), Content = "Lorem Ipsum is simply dummy text of the printing and typesetting industry." }, new Article { Id = 2, Title = "Why do we use it?", Author= "Gaurav Gahlot", PublishedOn = new DateTime(2019, 01, 21), Content = "It is a long established fact that a reader will be distracted by the readable content of a page when looking at its layout." }, new Article { Id = 3, Title = "Where does it come from?", Author= "Gaurav Gahlot", PublishedOn = new DateTime(2019, 01, 22), Content = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old." }, new Article { Id = 4, Title = "Yet another article", Author= "Gaurav Gahlot", PublishedOn = new DateTime(2019, 03, 27), Content = "Contrary to popular belief, Lorem Ipsum is not simply random text. It has roots in a piece of classical Latin literature from 45 BC, making it over 2000 years old." }, }; public Article GetArticle(int id) { var article = articles.FirstOrDefault(a => a.Id == id); if (article == null) { article = new Article(); } return article; } public List<Article> GetLatest() { return articles; } } }
33.777778
191
0.508459
[ "MIT" ]
Ramakant-07/webapp
WebApp/ArticleRepository.cs
2,130
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Microsoft.Extensions.DependencyInjection; using Microsoft.Extensions.Logging; using NuGet.Jobs.Validation; namespace NuGet.Services.Validation.Orchestrator { public class ValidatorProvider : IValidatorProvider { /// <summary> /// This is a cache of all of the <see cref="INuGetValidator"/> and <see cref="INuGetProcessor"/> implementations /// available. /// </summary> private static EvaluatedTypes _evaluatedTypes; private static object _evaluatedTypesLock = new object(); private readonly IServiceProvider _serviceProvider; private readonly ILogger<ValidatorProvider> _logger; public ValidatorProvider(IServiceProvider serviceProvider, ILogger<ValidatorProvider> logger) { _serviceProvider = serviceProvider ?? throw new ArgumentNullException(nameof(serviceProvider)); _logger = logger ?? throw new ArgumentNullException(nameof(logger)); InitializeEvaluatedTypes(Assembly.GetCallingAssembly()); } /// <summary> /// Discovers all <see cref="INuGetValidator"/> and <see cref="INuGetProcessor"/> types available and caches the result. /// </summary> private void InitializeEvaluatedTypes(Assembly callingAssembly) { if (_evaluatedTypes != null) { return; } lock (_evaluatedTypesLock) { if (_evaluatedTypes != null) { return; } using (_logger.BeginScope($"Enumerating all {nameof(INuGetValidator)} implementations")) { _logger.LogTrace("Before enumeration"); IEnumerable<Type> candidateTypes = GetCandidateTypes(callingAssembly); var nugetValidatorTypes = candidateTypes .Where(type => typeof(INuGetValidator).IsAssignableFrom(type) && type != typeof(INuGetValidator) && type != typeof(INuGetProcessor) && ValidatorUtility.HasValidatorNameAttribute(type)) .ToDictionary(ValidatorUtility.GetValidatorName); var nugetProcessorTypes = nugetValidatorTypes .Values .Where(IsProcessorType) .ToDictionary(ValidatorUtility.GetValidatorName); _logger.LogTrace("After enumeration, got {NumImplementations} implementations: {TypeNames}", nugetValidatorTypes.Count, nugetValidatorTypes.Keys); _evaluatedTypes = new EvaluatedTypes(nugetValidatorTypes, nugetProcessorTypes); } } } public bool IsNuGetValidator(string validatorName) { validatorName = validatorName ?? throw new ArgumentNullException(nameof(validatorName)); return _evaluatedTypes.NuGetValidatorTypes.ContainsKey(validatorName); } public bool IsNuGetProcessor(string validatorName) { validatorName = validatorName ?? throw new ArgumentNullException(nameof(validatorName)); return _evaluatedTypes.NuGetProcessorTypes.ContainsKey(validatorName); } public INuGetValidator GetNuGetValidator(string validatorName) { validatorName = validatorName ?? throw new ArgumentNullException(nameof(validatorName)); if (_evaluatedTypes.NuGetValidatorTypes.TryGetValue(validatorName, out Type validatorType)) { return (INuGetValidator)_serviceProvider.GetRequiredService(validatorType); } throw new ArgumentException($"Unknown validator name: {validatorName}", nameof(validatorName)); } private static IEnumerable<Type> GetCandidateTypes(Assembly callingAssembly) { var executingAssembly = Assembly.GetExecutingAssembly(); IEnumerable<Type> candidateTypes = executingAssembly.GetTypes(); if (callingAssembly != executingAssembly) { candidateTypes = candidateTypes.Concat(callingAssembly.GetTypes()); } return candidateTypes; } private static bool IsProcessorType(Type type) { return typeof(INuGetProcessor).IsAssignableFrom(type); } private class EvaluatedTypes { public EvaluatedTypes( IReadOnlyDictionary<string, Type> nugetValidatorTypes, IReadOnlyDictionary<string, Type> nugetProcessorTypes) { NuGetValidatorTypes = nugetValidatorTypes ?? throw new ArgumentNullException(nameof(nugetValidatorTypes)); NuGetProcessorTypes = nugetProcessorTypes ?? throw new ArgumentNullException(nameof(nugetProcessorTypes)); } public IReadOnlyDictionary<string, Type> NuGetValidatorTypes { get; } public IReadOnlyDictionary<string, Type> NuGetProcessorTypes { get; } } } }
40.333333
128
0.626997
[ "Apache-2.0" ]
CyberAndrii/NuGet.Jobs
src/NuGet.Services.Validation.Orchestrator/ValidatorProvider.cs
5,447
C#
using System; using System.Collections.Generic; using System.Text.RegularExpressions; namespace IntelliTect.TestTools.Console { /// <summary> /// Useful string extensions for performing assertions. /// </summary> public static class StringExtensions { /// <summary> /// Returns true if the string matches the given pattern (case-insensitive). /// </summary> /// <param name="s">The string to match</param> /// <param name="pattern">The pattern to match it against.</param> /// <returns></returns> public static bool IsLikeRegEx(this string s, string pattern) => new Regex(pattern, RegexOptions.IgnoreCase).IsMatch(s); /// <summary> /// Implement's VB's Like operator logic. /// </summary> // Provided in addition to IsLike that takes an escape character // even though a default escapeCharacter is provided as it // is hopefully simpler to use this one because no thinking // about escapeCharacter is required. public static bool IsLike(this string text, string pattern) => new WildcardPattern(pattern).IsMatch(text); /// <summary> /// Implement's VB's Like operator logic. /// </summary> public static bool IsLike(this string text, string pattern, char escapeCharacter) => new WildcardPattern(pattern, escapeCharacter).IsMatch(text); /// <summary> /// Converts a string of characters to a HashSet of characters. If the string /// contains character ranges, such as A-Z, all characters in the range are /// also added to the returned set of characters. /// </summary> /// <param name="charList">Character list string</param> private static HashSet<char> CharListToSet(string charList) { HashSet<char> set = new HashSet<char>(); for (int i = 0; i < charList.Length; i++) { if ((i + 1) < charList.Length && charList[i + 1] == '-') { // Character range char startChar = charList[i++]; i++; // Hyphen char endChar = (char)0; if (i < charList.Length) endChar = charList[i++]; for (int j = startChar; j <= endChar; j++) set.Add((char)j); } else { set.Add(charList[i]); } } return set; } } }
38.014493
92
0.543652
[ "MIT" ]
COsborn2/TestTools
IntelliTect.TestTools.Console/StringExtensions.cs
2,625
C#
 using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using P01_BillsPaymentSystem.Data.Models; namespace P01_BillsPaymentSystem.Data.Models.Configurations { public class UserConfiguration : IEntityTypeConfiguration<User> { public void Configure(EntityTypeBuilder<User> builder) { builder.HasKey(e => e.UserId); builder.Property(e => e.FirstName) .IsRequired() .HasMaxLength(50); builder.Property(e => e.LastName) .IsRequired() .HasMaxLength(50); builder.Property(e => e.Email) .IsRequired() .IsUnicode(false) .HasMaxLength(80); builder.Property(e => e.Password) .IsRequired() .IsUnicode(false) .HasMaxLength(25); } } }
29.30303
68
0.549121
[ "MIT" ]
LyuboslavKrastev/Databases-Advanced---Entity-Framework-
05. DB-Advanced-EF-Core-Advanced-Relations-Exercises/Bills PaymentSolution/P01_BillsPaymentSystem.Data/Models/Configurations/UserConfiguration.cs
969
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; // The Blank Page item template is documented at http://go.microsoft.com/fwlink/?LinkId=391641 namespace ObservableLogger.WinPhone81 { /// <summary> /// An empty page that can be used on its own or navigated to within a Frame. /// </summary> public sealed partial class MainPage : Xamarin.Forms.Platform.WinRT.WindowsPhonePage { public MainPage() { this.InitializeComponent(); this.NavigationCacheMode = NavigationCacheMode.Required; LoadApplication(new ObservableLogger.App()); } /// <summary> /// Invoked when this page is about to be displayed in a Frame. /// </summary> /// <param name="e">Event data that describes how this page was reached. /// This parameter is typically used to configure the page.</param> protected override void OnNavigatedTo(NavigationEventArgs e) { // TODO: Prepare page for display here. // TODO: If your application contains multiple pages, ensure that you are // handling the hardware Back button by registering for the // Windows.Phone.UI.Input.HardwareButtons.BackPressed event. // If you are using the NavigationHelper provided by some templates, // this event is handled for you. } } }
34.666667
94
0.682127
[ "Apache-2.0" ]
NoleHealth/xamarin-forms-book-preview-2
Chapter19/ObservableLogger/ObservableLogger/ObservableLogger.WinPhone81/MainPage.xaml.cs
1,770
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace NextpvrtoVlc.Model { class vlcM3U { public static String coverted (String _name, String _freq, String _programm) { StringBuilder vlc = new StringBuilder(); vlc.Append("#EXTINF:0,").AppendLine(_name); vlc.Append("#EXTVLCOPT:program=").AppendLine(_programm); vlc.Append("dvb-t://frequency=").Append(_freq).AppendLine(":bandwidth=0"); return vlc.ToString(); } } }
27.904762
86
0.634812
[ "MIT" ]
totolook/NextPVRtoVLCM3u
NextpvrtoVlc/Model/vlcM3U.cs
588
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="SmartPanelRemoveOrderLineActionPresenter.cs" company="Sitecore Corporation"> // Copyright (c) Sitecore Corporation 1999-2015 // </copyright> // <summary> // Defines the smart panel remove order line action presenter class. // </summary> // -------------------------------------------------------------------------------------------------------------------- // Copyright 2015 Sitecore Corporation A/S // Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file // except in compliance with the License. You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software distributed under the // License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, // either express or implied. See the License for the specific language governing permissions // and limitations under the License. // ------------------------------------------------------------------------------------------- namespace Sitecore.Ecommerce.Apps.OrderManagement.Presenters { using ContextStrategies; using Diagnostics; using Ecommerce.OrderManagement.Orders; using Views; /// <summary> /// Defines the smart panel remove order line action presenter class. /// </summary> public class SmartPanelRemoveOrderLineActionPresenter : RemoveOrderLineActionPresenter { /// <summary> /// The resolving strategy /// </summary> private UblEntityResolvingStrategy resolvingStrategy; /// <summary> /// Initializes a new instance of the <see cref="SmartPanelRemoveOrderLineActionPresenter"/> class. /// </summary> /// <param name="view">The view.</param> public SmartPanelRemoveOrderLineActionPresenter([NotNull] IRemoveOrderLineActionView view) : base(view) { Assert.ArgumentNotNull(view, "view"); } /// <summary> /// Gets or sets the resolving strategy. /// </summary> /// <value> /// The resolving strategy. /// </value> public override UblEntityResolvingStrategy ResolvingStrategy { get { return this.resolvingStrategy ?? (this.resolvingStrategy = new OnSmartPanelOrderLineStrategy()); } set { Assert.ArgumentNotNull(value, "value"); this.resolvingStrategy = value; } } /// <summary> /// Gets the order. /// </summary> /// <returns>The order.</returns> protected override Order GetOrder() { var orderLine = this.GetOrderLine(); return orderLine.Order; } /// <summary> /// Gets the order line. /// </summary> /// <returns>The order line.</returns> [NotNull] protected override OrderLine GetOrderLine() { var orderLine = this.ResolvingStrategy.GetEntity(this.ActionContext) as OrderLine; Assert.IsNotNull(orderLine, "Unable to initialize action. OrderLine cannot be null."); return orderLine; } } }
34.731183
121
0.59195
[ "Apache-2.0" ]
HydAu/sitecore8ecommerce
code/OrderManager/Sitecore.Ecommerce.Apps/OrderManagement/Presenters/SmartPanelRemoveOrderLineActionPresenter.cs
3,232
C#
using SQEX.Luminous.GraphicsLoad; namespace SQEX.Luminous.Math { public class LmVector3 { public float X { get; } public float Y { get; } public float Z { get; } public LmVector3(float x, float y, float z) { this.X = x; this.Y = y; this.Z = z; } public static LmVector3 Unpack(LmMsgPck msg) { var x = msg.ReadFloat(); var y = msg.ReadFloat(); var z = msg.ReadFloat(); return new LmVector3(x, y, z); } } }
21.37037
52
0.480069
[ "MIT" ]
Gurrimo/Luminaire
Assets/Editor/SQEX/Luminous/Math/LmVector3.cs
579
C#
// <copyright> // Copyright Southeast Christian Church // // Licensed under the Southeast Christian Church License (the "License"); // you may not use this file except in compliance with the License. // A copy of the License shoud be included with this file. // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // </copyright> // using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Xml.Serialization; using org.secc.Purchasing.DataLayer; using org.secc.Purchasing.Enums; using org.secc.Purchasing.Accounting; using Rock.Model; namespace org.secc.Purchasing { public class RequisitionItem : PurchasingBase { #region Fields private Requisition mRequisition; private Person mCreatedBy; private Person mModifiedBy; private Account mAccount; private List<PurchaseOrderItem> mPOItems; private Guid ShippingTypeLTGuid = new Guid("DFAC2EB7-97D0-4318-ACF3-554ADC2272F3"); private Guid SubmittedToPurchasingLUGuid = new Guid("22026706-A51D-44D7-8072-945AAB64A364"); #endregion #region Properties public int ItemID { get; set; } public int RequisitionID { get; set; } public int Quantity { get; set; } public string ItemNumber { get; set; } public string Description { get; set; } public DateTime DateNeeded { get; set; } public int CompanyID { get; set; } public int FundID { get; set; } public int DepartmentID { get; set; } public int AccountID { get; set; } public DateTime FYStartDate { get; set; } public string CreatedByUserID { get; set; } public string ModifiedByUserID { get; set; } public DateTime DateCreated { get; set; } public DateTime DateModified { get; set; } public bool Active { get; set; } public decimal Price { get; set; } public bool IsExpeditiedShippingAllowed { get; set; } [XmlIgnore] public Requisition Requisition { get { if (mRequisition == null && RequisitionID > 0) mRequisition = new Requisition(RequisitionID); return mRequisition; } } [XmlIgnore] public Person CreatedBy { get { if (mCreatedBy == null && !String.IsNullOrEmpty(CreatedByUserID)) mCreatedBy = userLoginService.GetByUserName(CreatedByUserID).Person; return mCreatedBy; } } [XmlIgnore] public Person ModifiedBy { get { if (mModifiedBy == null && !String.IsNullOrEmpty(ModifiedByUserID)) mModifiedBy = userLoginService.GetByUserName(ModifiedByUserID).Person; return mModifiedBy; } } [XmlIgnore] public Account Account { get { if(CompanyID > 0 && FundID > 0 && DepartmentID > 0 && AccountID > 0 && FYStartDate > DateTime.MinValue) mAccount = new Account(CompanyID, FundID, DepartmentID, AccountID, FYStartDate); return mAccount; } } [XmlIgnore] public List<PurchaseOrderItem> POItems { get { if (mPOItems == null && ItemID > 0) mPOItems = PurchaseOrderItem.LoadByRequistionItem(ItemID); return mPOItems; } } #endregion #region Constructors public RequisitionItem() { Init(); } public RequisitionItem(int itemID) { Load(itemID); } public RequisitionItem(RequisitionItemData d) { Load(d); } #endregion #region Public public bool CanBeDeleted() { bool Deleteable = true; if (Deleteable && POItems.Where(poi => poi.Active == true).Where(poi => poi.PurchaseOrder.Active).Where(poi => poi.PurchaseOrder.StatusLUID != PurchaseOrder.PurchaseOrderStatusCancelledLUID()).Count() > 0) Deleteable = false; return Deleteable; } public bool HasChanged() { bool Changed = false; RequisitionItem Original = new RequisitionItem(ItemID); if (this.GetHashCode() != Original.GetHashCode()) { if (RequisitionID != Original.RequisitionID) Changed = true; if (!Changed && Quantity != Original.Quantity) Changed = true; if (!Changed && Description != Original.Description) Changed = true; if (!Changed && DateNeeded != Original.DateNeeded) Changed = true; if (!Changed && CompanyID != Original.CompanyID) Changed = true; if (!Changed && FundID != Original.FundID) Changed = true; if (!Changed && DepartmentID != Original.DepartmentID) Changed = true; if (!Changed && AccountID != Original.AccountID) Changed = true; if (!Changed && FYStartDate != Original.FYStartDate) Changed = true; if (!Changed && Active != Original.Active) Changed = true; if (!Changed && Price != Original.Price) Changed = true; if (!Changed && IsExpeditiedShippingAllowed != Original.IsExpeditiedShippingAllowed) Changed = true; } return Changed; } public int GetQuantityReceived() { return POItems .Where(x => x.Active) .Where(x => x.PurchaseOrder.Active) .Where(x => x.PurchaseOrder.StatusLUID != PurchaseOrder.PurchaseOrderStatusCancelledLUID()) .Select(x => x.ReceiptItems.Where(ri => ri.Active).Where(ri=> ri.Receipt.Active).Select(ri => ri.QuantityReceived).Sum()).Sum(); } public void Save(string uid) { try { RequisitionItem Original = null; Enums.HistoryType ChangeType; Dictionary<string, string> ValErrors = Validate(); if (ValErrors.Count > 0) throw new RequisitionNotValidException("The requested item is not valid.", ValErrors); using (PurchasingContext Context = ContextHelper.GetDBContext()) { RequisitionItemData data; if (ItemID > 0) { data = Context.RequisitionItemDatas.FirstOrDefault(x => x.requisition_item_id == ItemID); ChangeType = HistoryType.UPDATE; Original = new RequisitionItem(data); } else { data = new RequisitionItemData(); data.created_by = uid; data.date_created = DateTime.Now; ChangeType = HistoryType.ADD; } data.date_modified = DateTime.Now; data.modified_by = uid; data.requisition_id = RequisitionID; data.quantity = Quantity; data.description = Description; if(DateNeeded != DateTime.MinValue) data.date_needed = DateNeeded; if (!String.IsNullOrEmpty(ItemNumber)) data.item_number = ItemNumber; else data.item_number = null; data.company_id = CompanyID; data.fund_id = FundID; data.department_id = DepartmentID; data.account_id = AccountID; data.active = Active; data.fiscal_year_start = FYStartDate; data.is_expedited_shipping_allowed = IsExpeditiedShippingAllowed; if ( Price != 0 ) { data.price = Price; } else { data.price = null; } if (ItemID == 0) Context.RequisitionItemDatas.InsertOnSubmit(data); Context.SubmitChanges(); Load(data); SaveHistory(ChangeType, Original, uid); } } catch (Exception ex) { throw new RequisitionException("An error has occurred while saving requisition item.", ex); } } public void SaveHistory(HistoryType ht, RequisitionItem orig, string uid) { History h = new History(); h.ObjectTypeName = this.GetType().ToString(); h.Identifier = ItemID; h.ChangeType = ht; switch (ht) { case HistoryType.ADD: h.OriginalXML = null; h.UpdatedXML = base.Serialize(this); break; case HistoryType.UPDATE: h.OriginalXML = base.Serialize(orig); h.UpdatedXML = base.Serialize(this); break; case HistoryType.DELETE: h.OriginalXML = base.Serialize(this); break; } h.OrganizationID = Requisition.OrganizationID; h.Active = true; h.Save(uid); } public void SoftDelete(string uid) { Active = false; Save(uid); } #endregion #region Private private void Init() { ItemID = 0; RequisitionID = 0; Quantity = 0; Description = String.Empty; DateNeeded = DateTime.MinValue; ItemNumber = String.Empty; CompanyID = 0; FundID = 0; DepartmentID = 0; AccountID = 0; FYStartDate = new DateTime(DateTime.Now.Year, 1, 1); CreatedByUserID = String.Empty; ModifiedByUserID = String.Empty; DateCreated = DateTime.MinValue; DateModified = DateTime.MinValue; Active = true; Price = 0; IsExpeditiedShippingAllowed = false; mRequisition = null; mCreatedBy = null; mModifiedBy = null; } private void Load(RequisitionItemData data) { Init(); if (data != null) { ItemID = data.requisition_item_id; RequisitionID = data.requisition_id; Quantity = data.quantity; Description = data.description; if (data.date_needed != null) DateNeeded = (DateTime)data.date_needed; if (data.item_number != null) ItemNumber = data.item_number; CompanyID = data.company_id; FundID = data.fund_id; DepartmentID = data.department_id; AccountID = data.account_id; CreatedByUserID = data.created_by; ModifiedByUserID = data.modified_by; DateCreated = data.date_created; DateModified = (DateTime)data.date_modified; IsExpeditiedShippingAllowed = data.is_expedited_shipping_allowed; if(data.fiscal_year_start != null) FYStartDate = (DateTime)data.fiscal_year_start; if (data.price == null) Price = 0; else Price = (decimal)data.price; Active = data.active; } } private void Load(int requisitionItemId) { using (PurchasingContext Context = ContextHelper.GetDBContext()) { Load( Context.RequisitionItemDatas.FirstOrDefault( ri => ri.requisition_item_id == requisitionItemId ) ); } } private Dictionary<string, string> Validate() { Dictionary<string, string> ValErrors = new Dictionary<string, string>(); if (ItemID <= 0) { if (DateNeeded != DateTime.MinValue && DateNeeded < DateTime.Now.Date) ValErrors.Add("Date Needed", "Date Needed can not be in the past."); } else { RequisitionItem Original = new RequisitionItem(ItemID); if (Original.Quantity != Quantity) { if (Quantity < POItems.Where(poi => poi.Active).Select(poi => (int?)poi.Quantity ?? 0).Sum()) { ValErrors.Add("Quantity", "Quantity is less than the quantity assigned to purchase orders."); } } } if(Quantity <= 0) ValErrors.Add("Quantity", "Quantity must be greater than 0."); if(String.IsNullOrEmpty(Description)) ValErrors.Add("Description", "Description must be provided."); if (CompanyID <= 0 || FundID <= 0 || DepartmentID <= 0 || AccountID <= 0 || FYStartDate == DateTime.MinValue) { ValErrors.Add("Account", "Please select a valid account"); } else if (Account == null || Account.AccountID <= 0) { ValErrors.Add("Account", "Account not found."); } if (ItemID <= 0 && FYStartDate.Year < DateTime.Now.Year) ValErrors.Add("Fiscal Year", "Fiscal year can not be in the past."); //if (Price < 0) // ValErrors.Add("Estimated Cost", "Estimated cost can not be negative."); return ValErrors; } #endregion } public class RequisitionItemListItem { public int ItemID { get; set; } public int Quantity { get; set; } public int QuantityReceived { get; set; } public string ItemNumber { get; set; } public string Description { get; set; } public DateTime? DateNeeded { get; set; } public bool ExpeditedShipping { get; set; } public string AccountNumber { get; set; } public List<int> PONumbers { get; set; } public decimal? EstimatedCost { get; set; } public decimal? LineItemCost { get; set; } public bool Active { get; set; } } }
35.687783
218
0.498732
[ "ECL-2.0" ]
engineeringdrew/RockPlugins
Plugins/org.secc.Purchasing/App_Code/RequisitionItem.cs
15,774
C#
using System.Linq; using Detectors.Redis.Configuration; using Detectors.Redis.Util; using Microsoft.AspNetCore.Mvc; namespace Detectors.Redis.Controllers { [Route("redis/connection/{connectionId}")] [Route("redis/connection/{connectionId}/server/{hostAndPort}")] public class RedisServerController : Controller { private readonly RedisConnectionConfigCollection _configuration; public RedisServerController(RedisConnectionConfigCollection configuration) { _configuration = configuration; } [HttpGet("ping")] [HttpGet("ping.{format}")] public IActionResult GetPingResponse(string connectionId, string hostAndPort = null) { using (var redis = _configuration.BuildMultiplexer(connectionId)) { var server = redis.GetServerOrDefault(hostAndPort); if (server == null) return NotFound(); var response = server.Ping(); return Ok(response.TotalSeconds); } } [HttpGet("echo/{message}")] [HttpGet("echo/{message}.{format}")] public IActionResult GetEchoResponse(string connectionId, string message, string hostAndPort = null) { using (var redis = _configuration.BuildMultiplexer(connectionId)) { var server = redis.GetServerOrDefault(hostAndPort); if (server == null) return NotFound(); var response = server.Echo(message); return Ok(response.ToString()); } } [HttpGet("client-list")] [HttpGet("client-list.{format}")] public IActionResult GetClientList(string connectionId, string hostAndPort = null) { using (var redis = _configuration.BuildMultiplexer(connectionId)) { var server = redis.GetServerOrDefault(hostAndPort); if (server == null) return NotFound(); var clientList = server.ClientList(); var result = clientList.Select(c => new { c.Id, c.Name, Address = c.Address.ToString(), Type = c.ClientType.ToString(), c.AgeSeconds, c.IdleSeconds, Flags = c.FlagsRaw, c.LastCommand, SubCount = c.SubscriptionCount, TxCmdLength = c.TransactionCommandLength }).ToList(); return Ok(result); } } [HttpGet("raw-client-list")] [HttpGet("raw-client-list.{format}")] public IActionResult GetRawClientList(string connectionId, string hostAndPort = null) { using (var redis = _configuration.BuildMultiplexer(connectionId)) { var server = redis.GetServerOrDefault(hostAndPort); if (server == null) return NotFound(); var clientList = server.ClientList(); return Ok(clientList.Select(c => c.Raw).ToList()); } } [HttpGet("config")] [HttpGet("config.{format}")] public IActionResult GetConfig(string connectionId, string pattern = null, string hostAndPort = null) { using (var redis = _configuration.BuildMultiplexer(connectionId)) { var server = redis.GetServerOrDefault(hostAndPort); if (server == null) return NotFound(); var response = string.IsNullOrWhiteSpace(pattern) ? server.ConfigGet() : server.ConfigGet(pattern); return Ok(response); } } [HttpGet("info/{section?}")] [HttpGet("info/{section}.{format}")] [HttpGet("info.{format}")] public IActionResult GetInfo(string connectionId, string section = null, string hostAndPort = null) { using (var redis = _configuration.BuildMultiplexer(connectionId)) { var server = redis.GetServerOrDefault(hostAndPort); if (server == null) return NotFound(); var info = server.Info(section); var result = info.SelectMany(g => g.Select(gg => new { Group = g.Key, gg.Key, gg.Value })).ToList(); return Ok(result); } } [HttpGet("lastsave")] [HttpGet("lastsave.{format}")] public IActionResult GetLastSave(string connectionId, string hostAndPort = null) { using (var redis = _configuration.BuildMultiplexer(connectionId)) { var server = redis.GetServerOrDefault(hostAndPort); if (server == null) return NotFound(); var response = server.LastSave(); return Ok(response.ToString("O")); } } [HttpGet("lastsave/elapsed")] [HttpGet("lastsave/elapsed.{format}")] public IActionResult GetElapsedSinceLastSave(string connectionId, string hostAndPort = null) { using (var redis = _configuration.BuildMultiplexer(connectionId)) { var server = redis.GetServerOrDefault(hostAndPort); if (server == null) return NotFound(); var lastSave = server.LastSave(); var time = server.Time(); return Ok((time - lastSave).TotalSeconds); } } [HttpGet("slowlog")] [HttpGet("slowlog.{format}")] public IActionResult GetSlowLog(string connectionId, int count = 10, string hostAndPort = null) { using (var redis = _configuration.BuildMultiplexer(connectionId)) { var server = redis.GetServerOrDefault(hostAndPort); if (server == null) return NotFound(); var slowLog = server.SlowlogGet(count); var result = slowLog.Select(l => new { l.UniqueId, Time = l.Time.ToString("O"), Duration = l.Duration.TotalSeconds, Command = string.Join(" ", l.Arguments.Select(a => a.ToString())).Truncate(40) }).ToList(); return Ok(result); } } [HttpGet("time")] [HttpGet("time.{format}")] public IActionResult GetTime(string connectionId, string hostAndPort = null) { using (var redis = _configuration.BuildMultiplexer(connectionId)) { var server = redis.GetServerOrDefault(hostAndPort); if (server == null) return NotFound(); var response = server.Time(); return Ok(response.ToString("O")); } } } }
36.393939
115
0.523175
[ "MIT" ]
ghs86/detectors
src/Redis/Controllers/RedisServerController.cs
7,208
C#
/* * Licensed to the Apache Software Foundation (ASF) under one * or more contributor license agreements. See the NOTICE file * distributed with this work for additional information * regarding copyright ownership. The ASF licenses this file * to you under the Apache License, Version 2.0 (the * "License"); you may not use this file except in compliance * with the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ using System; using System.Collections.Generic; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Cdn.Model.V20180510; namespace Aliyun.Acs.Cdn.Transform.V20180510 { public class UntagResourcesResponseUnmarshaller { public static UntagResourcesResponse Unmarshall(UnmarshallerContext _ctx) { UntagResourcesResponse untagResourcesResponse = new UntagResourcesResponse(); untagResourcesResponse.HttpResponse = _ctx.HttpResponse; untagResourcesResponse.RequestId = _ctx.StringValue("UntagResources.RequestId"); return untagResourcesResponse; } } }
35.475
83
0.755462
[ "Apache-2.0" ]
AxiosCros/aliyun-openapi-net-sdk
aliyun-net-sdk-cdn/Cdn/Transform/V20180510/UntagResourcesResponseUnmarshaller.cs
1,419
C#
// Copyright (c) 2017-2020 Ubisoft Entertainment // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System; using System.Collections.Generic; using System.Collections.Concurrent; using System.ComponentModel; using System.IO; using System.Linq; using System.Reflection; using System.Text; using Sharpmake.Generators.VisualStudio; namespace Sharpmake.Generators.Apple { public partial class XCodeProj : IProjectGenerator { public const string ProjectExtension = ".xcodeproj"; private const string ProjectFileName = "project.pbxproj"; private const string ProjectSchemeExtension = ".xcscheme"; private const int ProjectArchiveVersion = 1; private const int ProjectObjectVersion = 46; public const string RemoveLineTag = FileGeneratorUtilities.RemoveLineTag; public static readonly char FolderSeparator; private class XCodeGenerationContext : IGenerationContext { #region IGenerationContext implementation public Builder Builder { get; } public Project Project { get; } public Project.Configuration Configuration { get; internal set; } public string ProjectDirectory { get; } public DevEnv DevelopmentEnvironment => Configuration.Compiler; public Options.ExplicitOptions Options { get; set; } = new Options.ExplicitOptions(); public IDictionary<string, string> CommandLineOptions { get; set; } = new VisualStudio.ProjectOptionsGenerator.VcxprojCmdLineOptions(); public string ProjectDirectoryCapitalized { get; } public string ProjectSourceCapitalized { get; } public bool PlainOutput => true; public void SelectOption(params Options.OptionAction[] options) { Sharpmake.Options.SelectOption(Configuration, options); } public void SelectOptionWithFallback(Action fallbackAction, params Options.OptionAction[] options) { Sharpmake.Options.SelectOptionWithFallback(Configuration, fallbackAction, options); } #endregion public XCodeGenerationContext(Builder builder, string projectPath, Project project) { Builder = builder; ProjectDirectory = projectPath; Project = project; ProjectDirectoryCapitalized = Util.GetCapitalizedPath(ProjectDirectory); ProjectSourceCapitalized = Util.GetCapitalizedPath(project.SourceRootPath); } } private readonly HashSet<ProjectItem> _projectItems = new HashSet<ProjectItem>(); private ProjectFolder _mainGroup = null; private ProjectFolder _productsGroup = null; private ProjectFolder _frameworksFolder = null; private Dictionary<string, ProjectTarget> _nativeOrLegacyTargets = null; private Dictionary<string, ProjectResourcesBuildPhase> _resourcesBuildPhases = null; private Dictionary<string, ProjectSourcesBuildPhase> _sourcesBuildPhases = null; private Dictionary<string, ProjectFrameworksBuildPhase> _frameworksBuildPhases = null; private Dictionary<string, UniqueList<ProjectShellScriptBuildPhase>> _shellScriptPreBuildPhases = null; private Dictionary<string, UniqueList<ProjectShellScriptBuildPhase>> _shellScriptPostBuildPhases = null; private Dictionary<string, List<ProjectTargetDependency>> _targetDependencies = null; private Dictionary<ProjectFolder, ProjectReference> _projectReferencesGroups = null; private ProjectMain _projectMain = null; private Dictionary<Project.Configuration, Options.ExplicitOptions> _optionMapping = null; // Unit Test Variables private string _unitTestFramework = "XCTest"; static XCodeProj() { FolderSeparator = Util.UnixSeparator; } public void Generate( Builder builder, Project project, List<Project.Configuration> configurations, string projectFile, List<string> generatedFiles, List<string> skipFiles ) { FileInfo fileInfo = new FileInfo(projectFile); string projectPath = fileInfo.Directory.FullName; string projectFileName = fileInfo.Name; var context = new XCodeGenerationContext(builder, projectPath, project); PrepareSections(context, configurations); bool updated; string projectFileResult = GenerateProject(context, configurations, projectFileName, out updated); if (updated) generatedFiles.Add(projectFileResult); else skipFiles.Add(projectFileResult); string projectFileSchemeResult = GenerateProjectScheme(context, configurations, projectFileName, out updated); if (updated) generatedFiles.Add(projectFileSchemeResult); else skipFiles.Add(projectFileSchemeResult); } private string GenerateProject( XCodeGenerationContext context, List<Project.Configuration> configurations, string projectFile, out bool updated ) { // Create the target folder (solutions and projects are folders in XCode). string projectFolder = Util.GetCapitalizedPath(Path.Combine(context.ProjectDirectoryCapitalized, projectFile + ProjectExtension)); Directory.CreateDirectory(projectFolder); string projectFilePath = Path.Combine(projectFolder, ProjectFileName); FileInfo projectFileInfo = new FileInfo(projectFilePath); var fileGenerator = InitProjectGenerator(configurations); // Write the project file updated = context.Builder.Context.WriteGeneratedFile(context.Project.GetType(), projectFileInfo, fileGenerator.ToMemoryStream()); string projectFileResult = projectFileInfo.FullName; return projectFileResult; } private string GenerateProjectScheme( XCodeGenerationContext context, List<Project.Configuration> configurations, string projectFile, out bool updated ) { // Create the target folder (solutions and projects are folders in XCode). string projectSchemeFolder = Util.GetCapitalizedPath(Path.Combine(context.ProjectDirectoryCapitalized, projectFile + ProjectExtension, "xcshareddata", "xcschemes")); Directory.CreateDirectory(projectSchemeFolder); string projectSchemeFilePath = Path.Combine(projectSchemeFolder, projectFile + ProjectSchemeExtension); FileInfo projectSchemeFileInfo = new FileInfo(projectSchemeFilePath); var fileGenerator = InitProjectSchemeGenerator(configurations, projectFile); // Write the scheme file updated = context.Builder.Context.WriteGeneratedFile(context.Project.GetType(), projectSchemeFileInfo, fileGenerator.ToMemoryStream()); string projectFileResult = projectSchemeFileInfo.FullName; return projectFileResult; } private FileGenerator InitProjectGenerator(IList<Project.Configuration> configurations) { // Header. var fileGenerator = new FileGenerator(); using (fileGenerator.Declare("archiveVersion", ProjectArchiveVersion)) using (fileGenerator.Declare("objectVersion", ProjectObjectVersion)) { fileGenerator.Write(Template.GlobalHeader); } WriteSection<ProjectBuildFile>(configurations[0], fileGenerator); WriteSection<ProjectContainerProxy>(configurations[0], fileGenerator); WriteSection<ProjectFile>(configurations[0], fileGenerator); WriteSection<ProjectFrameworksBuildPhase>(configurations[0], fileGenerator); WriteSection<ProjectFolder>(configurations[0], fileGenerator); WriteSection<ProjectNativeTarget>(configurations[0], fileGenerator); WriteSection<ProjectLegacyTarget>(configurations[0], fileGenerator); WriteSection<ProjectMain>(configurations[0], fileGenerator); WriteSection<ProjectReferenceProxy>(configurations[0], fileGenerator); WriteSection<ProjectResourcesBuildPhase>(configurations[0], fileGenerator); WriteSection<ProjectSourcesBuildPhase>(configurations[0], fileGenerator); WriteSection<ProjectVariantGroup>(configurations[0], fileGenerator); WriteSection<ProjectTargetDependency>(configurations[0], fileGenerator); WriteSection<ProjectBuildConfiguration>(configurations[0], fileGenerator); WriteSection<ProjectConfigurationList>(configurations[0], fileGenerator); WriteSection<ProjectShellScriptBuildPhase>(configurations[0], fileGenerator); // Footer. using (fileGenerator.Declare("RootObject", _projectMain)) { fileGenerator.Write(Template.GlobalFooter); } // Remove all line that contain RemoveLineTag fileGenerator.RemoveTaggedLines(); return fileGenerator; } private FileGenerator InitProjectSchemeGenerator( List<Project.Configuration> configurations, string projectFile ) { // Setup resolvers var fileGenerator = new FileGenerator(); // Build testable elements var testableTargets = _nativeOrLegacyTargets.Values.Where(target => target.OutputFile.OutputType == Project.Configuration.OutputType.IosTestBundle); var testableElements = new StringBuilder(); foreach (var target in testableTargets) { using (fileGenerator.Declare("projectFile", projectFile)) using (fileGenerator.Declare("item", target)) { testableElements.Append(fileGenerator.Resolver.Resolve(Template.SchemeTestableReference)); } } // Write the scheme file var defaultTarget = _nativeOrLegacyTargets.Values.Where(target => target.OutputFile.OutputType != Project.Configuration.OutputType.IosTestBundle).FirstOrDefault(); var options = new Options.ExplicitOptions(); Options.SelectOption(configurations[0], Options.Option(Options.XCode.Compiler.EnableGpuFrameCaptureMode.AutomaticallyEnable, () => options["EnableGpuFrameCaptureMode"] = RemoveLineTag), Options.Option(Options.XCode.Compiler.EnableGpuFrameCaptureMode.MetalOnly, () => options["EnableGpuFrameCaptureMode"] = "1"), Options.Option(Options.XCode.Compiler.EnableGpuFrameCaptureMode.OpenGLOnly, () => options["EnableGpuFrameCaptureMode"] = "2"), Options.Option(Options.XCode.Compiler.EnableGpuFrameCaptureMode.Disable, () => options["EnableGpuFrameCaptureMode"] = "3") ); using (fileGenerator.Declare("projectFile", projectFile)) using (fileGenerator.Declare("item", defaultTarget)) using (fileGenerator.Declare("options", options)) using (fileGenerator.Declare("testableElements", testableElements)) using (fileGenerator.Declare("optimization", configurations[0].Target.Name)) { fileGenerator.Write(Template.SchemeFileTemplate); } // Remove all line that contain RemoveLineTag fileGenerator.RemoveTaggedLines(); return fileGenerator; } private void PrepareSections(XCodeGenerationContext context, List<Project.Configuration> configurations) { Project project = context.Project; //TODO: add support for multiple targets with the same outputtype. Would need a mechanism to define a default configuration per target and associate it with non-default conf with different optimization. //At the moment it only supports target with different output type (e.g:lib, app, test bundle) //Note that we also separate FastBuild configurations Dictionary<string, List<Project.Configuration>> projectTargetsList = GetProjectConfigurationsPerTarget(configurations); //Directory structure SetRootGroup(project, configurations[0]); ProjectVariantGroup variantGroup = new ProjectVariantGroup(); _projectItems.Add(variantGroup); Strings resourceFiles = new Strings(project.ResourceFiles); Strings sourceFiles = new Strings(project.GetSourceFilesForConfigurations(configurations).Except(resourceFiles)); string workspacePath = Directory.GetParent(configurations[0].ProjectFullFileNameWithExtension).FullName; //Generate options for each configuration _optionMapping = new Dictionary<Project.Configuration, Options.ExplicitOptions>(); foreach (Project.Configuration configuration in configurations) { context.Configuration = configuration; _optionMapping[configuration] = GenerateOptions(context); } _projectReferencesGroups = new Dictionary<ProjectFolder, ProjectReference>(); _nativeOrLegacyTargets = new Dictionary<string, ProjectTarget>(); _targetDependencies = new Dictionary<string, List<ProjectTargetDependency>>(); _sourcesBuildPhases = new Dictionary<string, ProjectSourcesBuildPhase>(); _resourcesBuildPhases = new Dictionary<string, ProjectResourcesBuildPhase>(); _frameworksBuildPhases = new Dictionary<string, ProjectFrameworksBuildPhase>(); _shellScriptPreBuildPhases = new Dictionary<string, UniqueList<ProjectShellScriptBuildPhase>>(); _shellScriptPostBuildPhases = new Dictionary<string, UniqueList<ProjectShellScriptBuildPhase>>(); //Loop on each targets foreach (var projectTarget in projectTargetsList) { string xCodeTargetName = projectTarget.Key; var targetConfigurations = projectTarget.Value; var configurationsForTarget = new HashSet<ProjectBuildConfiguration>(); var configurationListForNativeTarget = new ProjectConfigurationList(configurationsForTarget, xCodeTargetName); _projectItems.Add(configurationListForNativeTarget); var firstConf = targetConfigurations.First(); if (!firstConf.IsFastBuild) // since we grouped all FastBuild conf together, we only need to test the first conf { var projectSourcesBuildPhase = new ProjectSourcesBuildPhase(xCodeTargetName, 2147483647); _projectItems.Add(projectSourcesBuildPhase); _sourcesBuildPhases.Add(xCodeTargetName, projectSourcesBuildPhase); } var resourceBuildPhase = new ProjectResourcesBuildPhase(xCodeTargetName, 2147483647); _projectItems.Add(resourceBuildPhase); _resourcesBuildPhases.Add(xCodeTargetName, resourceBuildPhase); var frameworkBuildPhase = new ProjectFrameworksBuildPhase(xCodeTargetName, 2147483647); _projectItems.Add(frameworkBuildPhase); _frameworksBuildPhases.Add(xCodeTargetName, frameworkBuildPhase); var targetDependencies = new List<ProjectTargetDependency>(); _targetDependencies.Add(xCodeTargetName, targetDependencies); string masterBffFilePath = null; foreach (var conf in targetConfigurations) { if (!conf.IsFastBuild) PrepareSourceFiles(xCodeTargetName, sourceFiles.SortedValues, project, conf, workspacePath); PrepareResourceFiles(xCodeTargetName, resourceFiles.SortedValues, project, conf); PrepareExternalResourceFiles(xCodeTargetName, project, conf); RegisterScriptBuildPhase(xCodeTargetName, _shellScriptPreBuildPhases, conf.EventPreBuild.GetEnumerator()); RegisterScriptBuildPhase(xCodeTargetName, _shellScriptPostBuildPhases, conf.EventPostBuild.GetEnumerator()); Strings systemFrameworks = Options.GetStrings<Options.XCode.Compiler.SystemFrameworks>(conf); foreach (string systemFramework in systemFrameworks) { var systemFrameworkItem = new ProjectSystemFrameworkFile(systemFramework); var buildFileItem = new ProjectBuildFile(systemFrameworkItem); if (!_frameworksFolder.Children.Exists(item => item.FullPath == systemFrameworkItem.FullPath)) { _frameworksFolder.Children.Add(systemFrameworkItem); _projectItems.Add(systemFrameworkItem); } _projectItems.Add(buildFileItem); _frameworksBuildPhases[xCodeTargetName].Files.Add(buildFileItem); } // master bff path if (conf.IsFastBuild) { // we only support projects in one or no master bff, but in that last case just output a warning var masterBffList = conf.FastBuildMasterBffList.Distinct().ToArray(); if (masterBffList.Length == 0) { Builder.Instance.LogWarningLine("Bff {0} doesn't appear in any master bff, it won't be buildable.", conf.BffFullFileName + FastBuildSettings.FastBuildConfigFileExtension); } else if (masterBffList.Length > 1) { throw new Error("Bff {0} appears in {1} master bff, sharpmake only supports 1.", conf.BffFullFileName + FastBuildSettings.FastBuildConfigFileExtension, masterBffList.Length); } else { if (masterBffFilePath != null && masterBffFilePath != masterBffList[0]) throw new Error("Project {0} has a fastbuild target that has distinct master bff, sharpmake only supports 1.", conf); masterBffFilePath = masterBffList[0]; } } Strings userFrameworks = Options.GetStrings<Options.XCode.Compiler.UserFrameworks>(conf); foreach (string userFramework in userFrameworks) { var userFrameworkItem = new ProjectUserFrameworkFile(XCodeUtil.ResolveProjectPaths(project, userFramework), workspacePath); var buildFileItem = new ProjectBuildFile(userFrameworkItem); _frameworksFolder.Children.Add(userFrameworkItem); _projectItems.Add(userFrameworkItem); _projectItems.Add(buildFileItem); _frameworksBuildPhases[xCodeTargetName].Files.Add(buildFileItem); } if (conf.Output == Project.Configuration.OutputType.IosTestBundle) { var testFrameworkItem = new ProjectDeveloperFrameworkFile(_unitTestFramework); var buildFileItem = new ProjectBuildFile(testFrameworkItem); if (_frameworksFolder != null) _frameworksFolder.Children.Add(testFrameworkItem); _projectItems.Add(testFrameworkItem); _projectItems.Add(buildFileItem); _frameworksBuildPhases[xCodeTargetName].Files.Add(buildFileItem); } } // use the first conf as file, but the target name var targetOutputFile = new ProjectOutputFile(firstConf, xCodeTargetName); _productsGroup.Children.Add(targetOutputFile); _projectItems.Add(targetOutputFile); var projectOutputBuildFile = new ProjectBuildFile(targetOutputFile); _projectItems.Add(projectOutputBuildFile); ProjectTarget target; if (!firstConf.IsFastBuild) { target = new ProjectNativeTarget(xCodeTargetName, targetOutputFile, configurationListForNativeTarget, _targetDependencies[xCodeTargetName]); } else { target = new ProjectLegacyTarget(xCodeTargetName, targetOutputFile, configurationListForNativeTarget, masterBffFilePath); } target.ResourcesBuildPhase = _resourcesBuildPhases[xCodeTargetName]; if (_sourcesBuildPhases.ContainsKey(xCodeTargetName)) target.SourcesBuildPhase = _sourcesBuildPhases[xCodeTargetName]; target.FrameworksBuildPhase = _frameworksBuildPhases[xCodeTargetName]; if (_shellScriptPreBuildPhases.ContainsKey(xCodeTargetName)) target.ShellScriptPreBuildPhases = _shellScriptPreBuildPhases[xCodeTargetName]; if (_shellScriptPostBuildPhases.ContainsKey(xCodeTargetName)) target.ShellScriptPostBuildPhases = _shellScriptPostBuildPhases[xCodeTargetName]; configurationListForNativeTarget.RelatedItem = target; _projectItems.Add(target); _nativeOrLegacyTargets.Add(xCodeTargetName, target); //Generate BuildConfigurations foreach (Project.Configuration targetConf in targetConfigurations) { var options = _optionMapping[targetConf]; ProjectBuildConfigurationForTarget configurationForTarget = null; if (targetConf.Output == Project.Configuration.OutputType.IosTestBundle) configurationForTarget = new ProjectBuildConfigurationForUnitTestTarget(targetConf, target, options); else if (!targetConf.IsFastBuild) configurationForTarget = new ProjectBuildConfigurationForNativeTarget(targetConf, (ProjectNativeTarget)target, options); else configurationForTarget = new ProjectBuildConfigurationForLegacyTarget(targetConf, (ProjectLegacyTarget)target, options); configurationsForTarget.Add(configurationForTarget); _projectItems.Add(configurationForTarget); } } // Generate dependencies for unit test targets. var unitTestConfigs = new List<Project.Configuration>(configurations).FindAll(element => element.Output == Project.Configuration.OutputType.IosTestBundle); if (unitTestConfigs != null && unitTestConfigs.Count != 0) { foreach (Project.Configuration unitTestConfig in unitTestConfigs) { Project.Configuration bundleLoadingAppConfiguration = FindBundleLoadingApp(configurations); if (bundleLoadingAppConfiguration == null) continue; string key = GetTargetKey(bundleLoadingAppConfiguration); if (!_nativeOrLegacyTargets.ContainsKey(key)) continue; ProjectTarget target = _nativeOrLegacyTargets[key]; if (!(target is ProjectNativeTarget)) continue; ProjectNativeTarget bundleLoadingAppTarget = (ProjectNativeTarget)_nativeOrLegacyTargets[key]; ProjectReference projectReference = new ProjectReference(ItemSection.PBXProject, bundleLoadingAppTarget.Identifier); ProjectContainerProxy projectProxy = new ProjectContainerProxy(projectReference, bundleLoadingAppTarget, ProjectContainerProxy.Type.Target); ProjectTargetDependency targetDependency = new ProjectTargetDependency(projectReference, projectProxy, bundleLoadingAppTarget); _projectItems.Add(targetDependency); ((ProjectNativeTarget)_nativeOrLegacyTargets[GetTargetKey(unitTestConfig)]).Dependencies.Add(targetDependency); } } HashSet<ProjectBuildConfiguration> configurationsForProject = new HashSet<ProjectBuildConfiguration>(); ProjectConfigurationList configurationListForProject = new ProjectConfigurationList(configurationsForProject, "configurationListForProject"); _projectItems.Add(configurationListForProject); //This loop will find the register to the sets _projectItems and configurationsForProject the first configuration for each optimization type that is contained in the configurations. //Project options can only be set according to optimization types e.g: Debug, Release, Retail. foreach (Project.Configuration configuration in configurations) { var options = _optionMapping[configuration]; ProjectBuildConfigurationForProject configurationForProject = new ProjectBuildConfigurationForProject(configuration, options); configurationsForProject.Add(configurationForProject); _projectItems.Add(configurationForProject); } bool iCloudSupport = (_optionMapping[configurations[0]]["iCloud"] == "1"); string developmentTeam = _optionMapping[configurations[0]]["DevelopmentTeam"]; string provisioningStyle = _optionMapping[configurations[0]]["ProvisioningStyle"]; var nativeOrLegacyTargets = new List<ProjectTarget>(_nativeOrLegacyTargets.Values); _projectMain = new ProjectMain(project.Name, _mainGroup, configurationListForProject, nativeOrLegacyTargets, iCloudSupport, developmentTeam, provisioningStyle); configurationListForProject.RelatedItem = _projectMain; foreach (KeyValuePair<ProjectFolder, ProjectReference> referenceGroup in _projectReferencesGroups) { _projectMain.AddProjectDependency(referenceGroup.Key, referenceGroup.Value); } _projectItems.Add(_projectMain); } //Find Project.Configuration of the bundle loading app that matches the unit test target, if it exists. //Should have OutputType IosApp assuming targets with different output type. private Project.Configuration FindBundleLoadingApp(List<Project.Configuration> configurations) { return configurations.Find(element => (element.Output == Project.Configuration.OutputType.IosApp)); } private static string GetTargetKey(Project.Configuration conf) { if (conf.IsFastBuild) return conf.Project.Name + " FastBuild"; return conf.Project.Name; } // Key is the name of a Target, Value is the list of configs per target private Dictionary<string, List<Project.Configuration>> GetProjectConfigurationsPerTarget(List<Project.Configuration> configurations) { var configsPerTarget = configurations.GroupBy(conf => GetTargetKey(conf)).ToDictionary(g => g.Key, g => g.ToList()); return configsPerTarget; } private void RegisterScriptBuildPhase(string xCodeTargetName, Dictionary<string, UniqueList<ProjectShellScriptBuildPhase>> shellScriptPhases, IEnumerator<string> eventsInConf) { while (eventsInConf.MoveNext()) { var buildEvent = eventsInConf.Current; var shellScriptBuildPhase = new ProjectShellScriptBuildPhase(buildEvent, 2147483647) { script = buildEvent }; _projectItems.Add(shellScriptBuildPhase); if (!shellScriptPhases.ContainsKey(xCodeTargetName)) { shellScriptPhases.Add(xCodeTargetName, new UniqueList<ProjectShellScriptBuildPhase>(new ProjectShellScriptBuildPhase.EqualityComparer()) { shellScriptBuildPhase }); } else { shellScriptPhases[xCodeTargetName].Add(shellScriptBuildPhase); } } } private static void FillIncludeDirectoriesOptions(IGenerationContext context, IPlatformVcxproj platformVcxproj) { var includePaths = new OrderableStrings(platformVcxproj.GetIncludePaths(context)); context.Options["IncludePaths"] = XCodeUtil.XCodeFormatList(includePaths, 4); } private static void FillCompilerOptions(IGenerationContext context, IPlatformVcxproj platformVcxproj) { platformVcxproj.SelectCompilerOptions(context); } private static void SelectAdditionalLibraryDirectoriesOption(IGenerationContext context, IPlatformVcxproj platformVcxproj) { var conf = context.Configuration; var options = context.Options; options["LibraryPaths"] = FileGeneratorUtilities.RemoveLineTag; var libraryPaths = new OrderableStrings(conf.LibraryPaths); libraryPaths.AddRange(conf.DependenciesOtherLibraryPaths); libraryPaths.AddRange(conf.DependenciesBuiltTargetsLibraryPaths); libraryPaths.AddRange(platformVcxproj.GetLibraryPaths(context)); // LCTODO: not sure about that one libraryPaths.Sort(); options["LibraryPaths"] = XCodeUtil.XCodeFormatList(libraryPaths, 4); } private bool IsBuildExcludedForAllConfigurations(List<Project.Configuration> configurations, string fullPath) { foreach (Project.Configuration conf in configurations) { if (!conf.ResolvedSourceFilesBuildExclude.Contains(fullPath)) { return false; } } return true; } private void PrepareSourceFiles(string xCodeTargetName, IEnumerable<string> sourceFiles, Project project, Project.Configuration configuration, string workspacePath = null) { foreach (string file in sourceFiles) { bool alreadyPresent; ProjectFileSystemItem item = AddInFileSystem(file, out alreadyPresent, workspacePath, true); if (alreadyPresent) continue; item.Build = !configuration.ResolvedSourceFilesBuildExclude.Contains(item.FullPath); item.Source = project.SourceFilesCompileExtensions.Contains(item.Extension) || (String.Compare(item.Extension, ".mm", StringComparison.OrdinalIgnoreCase) == 0) || (String.Compare(item.Extension, ".m", StringComparison.OrdinalIgnoreCase) == 0); if (item.Source) { if (item.Build) { ProjectFile fileItem = (ProjectFile)item; ProjectBuildFile buildFileItem = new ProjectBuildFile(fileItem); _projectItems.Add(buildFileItem); _sourcesBuildPhases[xCodeTargetName].Files.Add(buildFileItem); } } else { if (!item.Build) { // Headers not matching file restrictions : remove them from the solution. RemoveFromFileSystem(item); } } } } private void PrepareResourceFiles(string xCodeTargetName, IEnumerable<string> resourceFiles, Project project, Project.Configuration configuration, string workspacePath = null) { foreach (string file in resourceFiles) { bool alreadyPresent; ProjectFileSystemItem item = AddInFileSystem(file, out alreadyPresent, workspacePath); if (alreadyPresent) continue; item.Build = true; item.Source = true; ProjectFile fileItem = (ProjectFile)item; ProjectBuildFile buildFileItem = new ProjectBuildFile(fileItem); _projectItems.Add(buildFileItem); _resourcesBuildPhases[xCodeTargetName].Files.Add(buildFileItem); } } private void PrepareExternalResourceFiles(string xCodeTargetName, Project project, Project.Configuration configuration) { Strings externalResourceFiles = Options.GetStrings<Options.XCode.Compiler.ExternalResourceFiles>(configuration); XCodeUtil.ResolveProjectPaths(project, externalResourceFiles); Strings externalResourceFolders = Options.GetStrings<Options.XCode.Compiler.ExternalResourceFolders>(configuration); XCodeUtil.ResolveProjectPaths(project, externalResourceFolders); Strings externalResourcePackages = Options.GetStrings<Options.XCode.Compiler.ExternalResourcePackages>(configuration); XCodeUtil.ResolveProjectPaths(project, externalResourcePackages); foreach (string externalResourcePackage in externalResourcePackages) { Directory.CreateDirectory(externalResourcePackage); externalResourceFiles.Add(externalResourcePackage); } foreach (string externalResourceFolder in externalResourceFolders) { Directory.CreateDirectory(externalResourceFolder); AddAllFiles(externalResourceFolder, externalResourceFiles); } string workspacePath = Directory.GetParent(configuration.ProjectFullFileNameWithExtension).FullName; PrepareResourceFiles(xCodeTargetName, externalResourceFiles, project, configuration, workspacePath); } private void AddAllFiles(string fullPath, Strings outputFiles) { outputFiles.Add(Util.DirectoryGetFiles(fullPath)); foreach (string folderPath in Util.DirectoryGetDirectories(fullPath)) { if (FolderAsFile(folderPath)) outputFiles.Add(folderPath); else AddAllFiles(folderPath, outputFiles); } } private void SetRootGroup(Project project, Project.Configuration configuration) { _mainGroup = new ProjectFolder(project.GetType().Name, true); if (Options.GetObjects<Options.XCode.Compiler.SystemFrameworks>(configuration).Any() || Options.GetObjects<Options.XCode.Compiler.UserFrameworks>(configuration).Any()) { _frameworksFolder = new ProjectFolder("Frameworks", true); _projectItems.Add(_frameworksFolder); _mainGroup.Children.Add(_frameworksFolder); } _projectItems.Add(_mainGroup); string workspacePath = Directory.GetParent(configuration.ProjectFullFileNameWithExtension).FullName; string sourceRootPath = project.SourceRootPath; ProjectFolder rootGroup = new ProjectFolder(sourceRootPath, Util.PathGetRelative(workspacePath, sourceRootPath)); _projectItems.Add(rootGroup); _productsGroup = new ProjectFolder("Products", true); _mainGroup.Children.Add(rootGroup); _mainGroup.Children.Add(_productsGroup); _projectItems.Add(_productsGroup); } private void Write(string value, TextWriter writer, Resolver resolver) { string resolvedValue = resolver.Resolve(value); StringReader reader = new StringReader(resolvedValue); string str = reader.ReadToEnd(); writer.Write(str); writer.Flush(); } private void WriteSection<ProjectItemType>(Project.Configuration configuration, IFileGenerator fileGenerator) where ProjectItemType : ProjectItem { IEnumerable<ProjectItem> projectItems = _projectItems.Where(item => item is ProjectItemType); if (projectItems.Any()) { ProjectItem firstItem = projectItems.First(); using (fileGenerator.Declare("item", firstItem)) { fileGenerator.Write(Template.SectionBegin); } Dictionary<string, string> resolverParameters = new Dictionary<string, string>(); foreach (ProjectItemType item in projectItems) { resolverParameters.Clear(); item.GetAdditionalResolverParameters(item, fileGenerator.Resolver, ref resolverParameters); using (fileGenerator.Declare(resolverParameters.Select(p => new VariableAssignment(p.Key, p.Value)).ToArray())) { using (fileGenerator.Declare("item", item)) using (fileGenerator.Declare("options", configuration)) { fileGenerator.Write(Template.Section[item.Section]); } } } using (fileGenerator.Declare("item", firstItem)) { fileGenerator.Write(Template.SectionEnd); } } } private ProjectFileSystemItem AddInFileSystem(string fullPath, out bool alreadyPresent, string workspacePath = null, bool applyWorkspaceOnlyToRoot = false) { // Search in existing roots. var fileSystemItems = _projectItems.Where(item => item is ProjectFileSystemItem); foreach (ProjectFileSystemItem item in fileSystemItems) { if (fullPath.StartsWith(item.FullPath, StringComparison.OrdinalIgnoreCase)) { if (fullPath.Length > item.FullPath.Length) return AddInFileSystem(item, out alreadyPresent, fullPath.Substring(item.FullPath.Length + 1), applyWorkspaceOnlyToRoot ? null : workspacePath); } } // Not found in existing root, create a new root for this item. alreadyPresent = false; string parentDirectoryPath = Directory.GetParent(fullPath).FullName; //string fileName = fullPath.Substring(parentDirectoryPath.Length + 1); ProjectFolder folder = workspacePath != null ? new ProjectExternalFolder(parentDirectoryPath, workspacePath) : new ProjectFolder(parentDirectoryPath); _projectItems.Add(folder); _mainGroup.Children.Insert(0, folder); ProjectFile file = workspacePath != null ? new ProjectExternalFile(fullPath, workspacePath) : new ProjectFile(fullPath); _projectItems.Add(file); folder.Children.Add(file); return file; } private ProjectFileSystemItem AddInFileSystem(ProjectFileSystemItem parent, out bool alreadyPresent, string remainingPath, string workspacePath) { alreadyPresent = false; string[] remainingPathParts = remainingPath.Split(FolderSeparator); for (int i = 0; i < remainingPathParts.Length; i++) { bool found = false; string remainingPathPart = remainingPathParts[i]; foreach (ProjectFileSystemItem item in parent.Children) { if (remainingPathPart == item.Name) { parent = item; found = true; break; } } if (!found) { if (i == remainingPathParts.Length - 1) { string fullPath = parent.FullPath + FolderSeparator + remainingPathPart; ProjectFile file = workspacePath != null ? new ProjectExternalFile(fullPath, workspacePath) : new ProjectFile(fullPath); _projectItems.Add(file); parent.Children.Add(file); return file; } else { string fullPath = parent.FullPath + FolderSeparator + remainingPathPart; ProjectFolder folder = workspacePath != null ? new ProjectExternalFolder(fullPath, workspacePath) : new ProjectFolder(fullPath); _projectItems.Add(folder); parent.Children.Add(folder); parent = folder; } } else if (i == remainingPathParts.Length - 1) { alreadyPresent = true; } } parent.Children.Sort((f1, f2) => string.Compare(f1.Name, f2.Name, StringComparison.OrdinalIgnoreCase)); return parent; } private void RemoveFromFileSystem(ProjectFileSystemItem fileSystemItem) { ProjectFileSystemItem itemToSearch = fileSystemItem; while (itemToSearch != null) { ProjectFileSystemItem parentItemToSearch = _projectItems.Where(item => item is ProjectFileSystemItem).Cast<ProjectFileSystemItem>().FirstOrDefault(item => item.Children.Contains(itemToSearch)); if (parentItemToSearch == null) break; parentItemToSearch.Children.Remove(itemToSearch); if (parentItemToSearch.Children.Count != 0) break; itemToSearch = parentItemToSearch; _projectItems.Remove(itemToSearch); } _projectItems.Remove(fileSystemItem); } private bool FolderAsFile(string fullPath) { string extension = Path.GetExtension(fullPath); switch (extension) { case ".bundle": return true; } return false; } private Options.ExplicitOptions GenerateOptions(XCodeGenerationContext context) { var project = context.Project; var conf = context.Configuration; var options = new Options.ExplicitOptions(); context.Options = options; options["TargetName"] = XCodeUtil.XCodeFormatSingleItem(conf.Target.Name); // TODO: really not ideal, refactor and move the properties we need from it someplace else var platformVcxproj = PlatformRegistry.Query<VisualStudio.IPlatformVcxproj>(context.Configuration.Platform); FillIncludeDirectoriesOptions(context, platformVcxproj); FillCompilerOptions(context, platformVcxproj); SelectAdditionalLibraryDirectoriesOption(context, platformVcxproj); context.Options["GenerateMapFile"] = RemoveLineTag; platformVcxproj.SelectLinkerOptions(context); var libFiles = new OrderableStrings(conf.LibraryFiles); libFiles.AddRange(conf.DependenciesBuiltTargetsLibraryFiles); libFiles.AddRange(conf.DependenciesOtherLibraryFiles); libFiles.Sort(); var linkerOptions = new Strings(conf.AdditionalLinkerOptions); // TODO: make this an option linkerOptions.Add("-ObjC"); // TODO: fix this to use proper lib prefixing linkerOptions.AddRange(libFiles.Select(library => "-l" + library)); // TODO: when the above is fixed, we won't need this anymore if (conf.Output == Project.Configuration.OutputType.Dll) options["ExecutablePrefix"] = "lib"; else options["ExecutablePrefix"] = RemoveLineTag; if (conf.DefaultOption == Options.DefaultTarget.Debug) conf.Defines.Add("_DEBUG"); else // Release conf.Defines.Add("NDEBUG"); options["PreprocessorDefinitions"] = XCodeUtil.XCodeFormatList(conf.Defines, 4, forceQuotes: true); options["CompilerOptions"] = XCodeUtil.XCodeFormatList(conf.AdditionalCompilerOptions, 4, forceQuotes: true); if (conf.AdditionalLibrarianOptions.Any()) throw new NotImplementedException(nameof(conf.AdditionalLibrarianOptions) + " not supported with XCode generator"); options["LinkerOptions"] = XCodeUtil.XCodeFormatList(linkerOptions, 4, forceQuotes: true); return options; } private static class XCodeProjIdGenerator { private static System.Security.Cryptography.SHA1CryptoServiceProvider s_cryptoProvider; private static Dictionary<ProjectItem, string> s_hashRepository; private static object s_lockMyself = new object(); static XCodeProjIdGenerator() { s_cryptoProvider = new System.Security.Cryptography.SHA1CryptoServiceProvider(); s_hashRepository = new Dictionary<ProjectItem, string>(); } public static string GetXCodeId(ProjectItem item) { lock (s_hashRepository) { if (s_hashRepository.ContainsKey(item)) return s_hashRepository[item]; byte[] stringbytes = Encoding.UTF8.GetBytes(item.ToString()); byte[] hashedBytes = null; lock (s_lockMyself) { hashedBytes = s_cryptoProvider.ComputeHash(stringbytes); } Array.Resize(ref hashedBytes, 16); string guidString = new Guid(hashedBytes).ToString("N").ToUpper().Substring(7, 24); s_hashRepository[item] = guidString; return guidString; } } } public enum ItemSection { PBXBuildFile, PBXContainerItemProxy, PBXFileReference, PBXFrameworksBuildPhase, PBXGroup, PBXNativeTarget, PBXLegacyTarget, PBXProject, PBXReferenceProxy, PBXResourcesBuildPhase, PBXSourcesBuildPhase, PBXVariantGroup, PBXTargetDependency, XCBuildConfiguration_NativeTarget, XCBuildConfiguration_LegacyTarget, XCBuildConfiguration_UnitTestTarget, XCBuildConfiguration_Project, XCConfigurationList, PBXShellScriptBuildPhase } public abstract class ProjectItem : IEquatable<ProjectItem>, IComparable<ProjectItem> { private ItemSection _section; private string _identifier; private string _internalIdentifier; private int _hashCode; private string _uid; public ProjectItem(ItemSection section, string identifier) { _section = section; _identifier = identifier; _internalIdentifier = section.ToString() + "/" + Identifier; _hashCode = _internalIdentifier.GetHashCode(); _uid = XCodeProjIdGenerator.GetXCodeId(this); } public ItemSection Section { get { return _section; } } public string SectionString { get { return _section.ToString(); } } public string Identifier { get { return _identifier; } } public string Uid { get { return _uid; } } public virtual void GetAdditionalResolverParameters(ProjectItem item, Resolver resolver, ref Dictionary<string, string> resolverParameters) { } public override bool Equals(object obj) { if (!(obj is ProjectItem)) return false; return Equals((ProjectItem)obj); } public override int GetHashCode() { return _hashCode; } public override string ToString() { return _internalIdentifier; } public bool Equals(ProjectItem other) { return _hashCode == other._hashCode; } public int CompareTo(ProjectItem other) { int compare = Section.CompareTo(other.Section); if (compare != 0) return compare; return CompareToInternal(other); } protected virtual int CompareToInternal(ProjectItem other) { return string.Compare(Identifier, other.Identifier, StringComparison.Ordinal); } public static bool operator ==(ProjectItem left, ProjectItem right) { return Object.Equals(left, right); } public static bool operator !=(ProjectItem left, ProjectItem right) { return !(left == right); } } private static class EnumExtensions { private static ConcurrentDictionary<Enum, string> s_enumToStringMapping = new ConcurrentDictionary<Enum, string>(); public static string EnumToString(Enum enumValue) { string stringValue; if (s_enumToStringMapping.TryGetValue(enumValue, out stringValue)) return stringValue; stringValue = enumValue.ToString(); MemberInfo[] memberInfo = enumValue.GetType().GetMember(stringValue); if (memberInfo != null && memberInfo.Length > 0) { object[] attributes = memberInfo[0].GetCustomAttributes(typeof(System.ComponentModel.DescriptionAttribute), false); if (attributes != null && attributes.Length > 0) stringValue = ((System.ComponentModel.DescriptionAttribute)attributes[0]).Description; } s_enumToStringMapping.TryAdd(enumValue, stringValue); return stringValue; } } private abstract class ProjectFileSystemItem : ProjectItem { public enum SourceTreeSetting { [Description("\"<group>\"")] GROUP, SOURCE_ROOT, SDKROOT, BUILT_PRODUCTS_DIR, DEVELOPER_DIR } protected ProjectFileSystemItem(ItemSection section, string fullPath) : base(section, fullPath) { Children = new List<ProjectFileSystemItem>(); FullPath = fullPath; Name = fullPath.Substring(fullPath.LastIndexOf(FolderSeparator) + 1); } public List<ProjectFileSystemItem> Children { get; protected set; } public abstract bool Build { get; set; } public abstract bool Source { get; set; } public string FullPath { get; protected set; } public string FileName => System.IO.Path.GetFileName(FullPath); public virtual string Name { get; protected set; } public virtual string Path { get { return Name; } protected set { Name = value; } } public string Type => Source ? "Sources" : "Frameworks"; public abstract string Extension { get; } public string SourceTree => EnumExtensions.EnumToString(SourceTreeValue); public abstract SourceTreeSetting SourceTreeValue { get; } } private abstract class ProjectFileBase : ProjectFileSystemItem { private bool _build = false; private bool _source = false; private string _extension; private string _fileType; private string _explicitFileType; private string _includeInIndex; protected ProjectFileBase(ItemSection section, string fullPath) : base(section, fullPath) { _extension = System.IO.Path.GetExtension(FullPath); _fileType = GetFileType(); _explicitFileType = RemoveLineTag; _includeInIndex = RemoveLineTag; if (_fileType == "archive.ar") { _explicitFileType = _fileType; _fileType = RemoveLineTag; _includeInIndex = "0"; } } protected string GetFileType() { switch (_extension) { case "": return "\"compiled.mach-o.executable\""; case ".c": return "sourcecode.c.c"; case ".cpp": return "sourcecode.cpp.cpp"; case ".h": return "sourcecode.c.h"; case ".hpp": return "sourcecode.c.h"; case ".s": return "sourcecode.asm"; case ".m": return "sourcecode.c.objc"; case ".j": return "sourcecode.c.objc"; case ".mm": return "sourcecode.cpp.objcpp"; case ".xcodeproj": return "\"wrapper.pb-project\""; case ".framework": return "wrapper.framework"; case ".bundle": return "\"wrapper.plug-in\""; case ".nib": return "wrapper.nib"; case ".app": return "wrapper.application"; case ".xctest": return "wrapper.cfbundle"; case ".dylib": return "\"compiled.mach-o.dylib\""; case ".txt": return "text"; case ".plist": return "text.plist.xml"; case ".ico": return "text"; case ".rtf": return "text.rtf"; case ".strings": return "text.plist.strings"; case ".json": return "text.json"; case ".a": return "archive.ar"; case ".png": return "image.png"; case ".tiff": return "image.tiff"; case ".ipk": return "file.ipk"; case ".pem": return "file.pem"; case ".loc8": return "file.loc8"; case ".metapreload": return "file.metapreload"; case ".gf": return "file.gf"; case ".xib": return "file.xib"; } return "\"?\""; } public override string Extension { get { return _extension; } } public override bool Build { get { return _build; } set { _build = value; } } public override bool Source { get { return _source; } set { _source = value; } } public string FileType { get { return _fileType; } protected set { _fileType = value; } } public string ExplicitFileType { get { return _explicitFileType; } } public string IncludeInIndex { get { return _includeInIndex; } } } private class ProjectFile : ProjectFileBase { public ProjectFile(ItemSection section, string fullPath) : base(section, fullPath) { } public ProjectFile(string fullPath) : this(ItemSection.PBXFileReference, fullPath) { } public override string Path => FullPath; public override SourceTreeSetting SourceTreeValue { get { return SourceTreeSetting.GROUP; } } } private class ProjectExternalFile : ProjectFile { private string _relativePath; public ProjectExternalFile(ItemSection section, string fullPath, string workspacePath) : base(section, fullPath) { _relativePath = Util.PathGetRelative(workspacePath, fullPath); } public ProjectExternalFile(string fullPath, string workspacePath) : this(ItemSection.PBXFileReference, fullPath, workspacePath) { } public override ProjectFileSystemItem.SourceTreeSetting SourceTreeValue { get { return SourceTreeSetting.SOURCE_ROOT; } } public override string Path { get { return _relativePath; } } } private class ProjectReferenceProxy : ProjectFileBase { private ProjectContainerProxy _proxy; private ProjectFile _outputFile; public ProjectReferenceProxy(ProjectReference projectReference, ProjectContainerProxy proxy, ProjectFile outputFile) : base(ItemSection.PBXReferenceProxy, "PROXY" + FolderSeparator + projectReference.Name) { FileType = "archive.ar"; _outputFile = outputFile; _proxy = proxy; } public override string Extension { get { return ".a"; } } public ProjectContainerProxy Proxy { get { return _proxy; } } public ProjectFile OutputFile { get { return _outputFile; } } public override SourceTreeSetting SourceTreeValue { get { return SourceTreeSetting.BUILT_PRODUCTS_DIR; } } } private class ProjectReference : ProjectFile { public ProjectReference(string fullPath) : base(fullPath) { ProjectName = Name.Substring(0, Name.LastIndexOf('.')); } public ProjectReference(ItemSection itemSection, string identifier) : base(ItemSection.PBXProject, identifier) { ProjectName = identifier; } public override SourceTreeSetting SourceTreeValue { get { return SourceTreeSetting.SOURCE_ROOT; } } public string ProjectName { get; } } private class ProjectOutputFile : ProjectFile { private Project.Configuration _conf; public ProjectOutputFile(string fullPath) : base(fullPath) { } public ProjectOutputFile(Project.Configuration conf, string name = null) : this(((conf.Output == Project.Configuration.OutputType.Lib) ? conf.TargetLibraryPath : conf.TargetPath) + FolderSeparator + GetFilePrefix(conf.Output) + conf.TargetFileFullName + GetFileExtension(conf)) { Name = name ?? conf.Project.Name + " " + conf.Name; BuildableName = System.IO.Path.GetFileName(FullPath); _conf = conf; } private static string GetFilePrefix(Project.Configuration.OutputType outputType) { return (outputType == Project.Configuration.OutputType.Lib || outputType == Project.Configuration.OutputType.Dll) ? "lib" : ""; } public static string GetFileExtension(Project.Configuration conf) { switch (conf.Output) { case Project.Configuration.OutputType.Dll: return ".dylib"; case Project.Configuration.OutputType.Lib: return ".a"; case Project.Configuration.OutputType.Exe: return ""; // Mac executable case Project.Configuration.OutputType.IosApp: return ".app"; case Project.Configuration.OutputType.IosTestBundle: return ".xctest"; case Project.Configuration.OutputType.None: return ""; default: throw new NotSupportedException($"XCode generator doesn't handle {conf.Output}"); } } public override SourceTreeSetting SourceTreeValue { get { return SourceTreeSetting.BUILT_PRODUCTS_DIR; } } public Project.Configuration.OutputType OutputType { get { return _conf.Output; } } public string BuildableName { get; } } private abstract class ProjectFrameworkFile : ProjectFile { public ProjectFrameworkFile(string fullPath) : base(fullPath) { } } private class ProjectSystemFrameworkFile : ProjectFrameworkFile { private static readonly string s_frameworkPath = "System" + FolderSeparator + "Library" + FolderSeparator + "Frameworks" + FolderSeparator; private const string FrameworkExtension = ".framework"; public ProjectSystemFrameworkFile(string frameworkFileName) : base(s_frameworkPath + frameworkFileName + FrameworkExtension) { } public override SourceTreeSetting SourceTreeValue { get { return SourceTreeSetting.SDKROOT; } } public override string Path { get { return FullPath; } } } private class ProjectDeveloperFrameworkFile : ProjectFrameworkFile { private static readonly string s_frameworkPath = ".." + FolderSeparator + ".." + FolderSeparator + "Library" + FolderSeparator + "Frameworks" + FolderSeparator; private const string FrameworkExtension = ".framework"; public ProjectDeveloperFrameworkFile(string frameworkFileName) : base(s_frameworkPath + frameworkFileName + FrameworkExtension) { } public override SourceTreeSetting SourceTreeValue { get { return SourceTreeSetting.SDKROOT; } } public override string Path { get { return FullPath; } } } private class ProjectUserFrameworkFile : ProjectFrameworkFile { private string _relativePath; public ProjectUserFrameworkFile(string frameworkFullPath, string workspacePath) : base(frameworkFullPath) { _relativePath = Util.PathGetRelative(workspacePath, frameworkFullPath); } public override SourceTreeSetting SourceTreeValue { get { return SourceTreeSetting.SOURCE_ROOT; } } public override string Path { get { return _relativePath; } } } private class ProjectFolder : ProjectFileSystemItem { public ProjectFolder(string fullPath, bool removePathLine = false) : base(ItemSection.PBXGroup, fullPath) { Path = removePathLine ? RemoveLineTag : Name; } public ProjectFolder(string identifier, string fullPath) : base(ItemSection.PBXGroup, identifier) { Path = fullPath; } public override bool Build { get { return false; } set { throw new NotSupportedException(); } } public override bool Source { get { return false; } set { throw new NotSupportedException(); } } public override string Extension { get { throw new NotSupportedException(); } } public override SourceTreeSetting SourceTreeValue { get { return SourceTreeSetting.GROUP; } } public override string Path { get; protected set; } public override void GetAdditionalResolverParameters(ProjectItem item, Resolver resolver, ref Dictionary<string, string> resolverParameters) { ProjectFolder folderItem = (ProjectFolder)item; string childrenList = ""; foreach (ProjectFileSystemItem childItem in folderItem.Children) { using (resolver.NewScopedParameter("item", childItem)) { childrenList += resolver.Resolve(Template.SectionSubItem); } } resolverParameters.Add("itemChildren", childrenList); } } private class ProjectExternalFolder : ProjectFolder { public ProjectExternalFolder(string fullPath, string workspacePath) : base(fullPath) { Path = Util.PathGetRelative(workspacePath, fullPath); } public override SourceTreeSetting SourceTreeValue { get { return SourceTreeSetting.SOURCE_ROOT; } } } private class ProjectProductsFolder : ProjectFolder { public ProjectProductsFolder(string fullPath) : base("PRODUCTS" + FolderSeparator + fullPath) { } public override string Name { get { return "Products"; } } public override string Path { get { return RemoveLineTag; } } } private class ProjectBuildFile : ProjectItem { public ProjectBuildFile(ProjectFileBase file) : base(ItemSection.PBXBuildFile, file.Name) { File = file; } public ProjectFileBase File { get; } } private abstract class ProjectBuildPhase : ProjectItem { public ProjectBuildPhase(ItemSection section, string phaseName, uint buildActionMask) : base(section, phaseName) { Files = new UniqueList<ProjectBuildFile>(); BuildActionMask = buildActionMask; RunOnlyForDeploymentPostprocessing = 0; } public override void GetAdditionalResolverParameters(ProjectItem item, Resolver resolver, ref Dictionary<string, string> resolverParameters) { ProjectBuildPhase folderItem = (ProjectBuildPhase)item; string childrenList = ""; foreach (ProjectBuildFile childItem in folderItem.Files.SortedValues) { using (resolver.NewScopedParameter("item", childItem)) { childrenList += resolver.Resolve(Template.SectionSubItem); } } resolverParameters.Add("itemChildren", childrenList); } public UniqueList<ProjectBuildFile> Files { get; } public uint BuildActionMask { get; } = 0; public int RunOnlyForDeploymentPostprocessing { get; } } private class ProjectResourcesBuildPhase : ProjectBuildPhase { public ProjectResourcesBuildPhase(uint buildActionMask) : base(ItemSection.PBXResourcesBuildPhase, "Resources", buildActionMask) { } public ProjectResourcesBuildPhase(string name, uint buildActionMask) : base(ItemSection.PBXResourcesBuildPhase, name, buildActionMask) { } } private class ProjectSourcesBuildPhase : ProjectBuildPhase { public ProjectSourcesBuildPhase(uint buildActionMask) : base(ItemSection.PBXSourcesBuildPhase, "Sources", buildActionMask) { } public ProjectSourcesBuildPhase(string name, uint buildActionMask) : base(ItemSection.PBXSourcesBuildPhase, name, buildActionMask) { } } private class ProjectFrameworksBuildPhase : ProjectBuildPhase { public ProjectFrameworksBuildPhase(uint buildActionMask) : base(ItemSection.PBXFrameworksBuildPhase, "Frameworks", buildActionMask) { } public ProjectFrameworksBuildPhase(string name, uint buildActionMask) : base(ItemSection.PBXFrameworksBuildPhase, name, buildActionMask) { } } private class ProjectShellScriptBuildPhase : ProjectBuildPhase { public class EqualityComparer : IEqualityComparer<ProjectShellScriptBuildPhase> { public bool Equals(ProjectShellScriptBuildPhase x, ProjectShellScriptBuildPhase y) { return x.script == y.script; } public int GetHashCode(ProjectShellScriptBuildPhase obj) { return obj.script.GetHashCode(); } } public String script; public ProjectShellScriptBuildPhase(uint buildActionMask) : base(ItemSection.PBXShellScriptBuildPhase, "ShellScrips", buildActionMask) { } public ProjectShellScriptBuildPhase(string name, uint buildActionMask) : base(ItemSection.PBXShellScriptBuildPhase, name, buildActionMask) { } } private class ProjectVariantGroup : ProjectItem { public ProjectVariantGroup() : base(ItemSection.PBXVariantGroup, "") { } } private class ProjectContainerProxy : ProjectItem { public enum Type { Target = 1, Archive = 2, } private Type _proxyType; private ProjectItem _proxyItem; private ProjectReference _projectReference; public ProjectContainerProxy(ProjectReference projectReference, ProjectItem proxyItem, Type proxyType) : base(ItemSection.PBXContainerItemProxy, "PBXContainerItemProxy for " + projectReference.Name + " - " + proxyType.ToString()) { _proxyType = proxyType; _proxyItem = proxyItem; _projectReference = projectReference; } public ProjectItem ProxyItem { get { return _proxyItem; } } public int ProxyType { get { return (int)_proxyType; } } public ProjectReference ProjectReference { get { return _projectReference; } } } private class ProjectTargetDependency : ProjectItem { private ProjectContainerProxy _proxy; private ProjectReference _projectReference; private ProjectNativeTarget _target; public ProjectTargetDependency(ProjectReference projectReference, ProjectContainerProxy proxy) : base(ItemSection.PBXTargetDependency, projectReference.Name) { _proxy = proxy; _projectReference = projectReference; _target = null; } public ProjectTargetDependency(ProjectReference projectReference, ProjectContainerProxy proxy, ProjectNativeTarget target) : base(ItemSection.PBXTargetDependency, projectReference.Name) { _proxy = proxy; _projectReference = projectReference; _target = target; } public ProjectNativeTarget NativeTarget { get { return _target; } } public ProjectContainerProxy Proxy { get { return _proxy; } } public ProjectReference ProjectReference { get { return _projectReference; } } public String TargetIdentifier { get { if (_target != null) return _target.Uid; else return RemoveLineTag; } } } private abstract class ProjectTarget : ProjectItem { public ProjectTarget(ItemSection section, string identifier) : base(section, identifier) { // Only for Uid computation. OutputFile = null; } public ProjectTarget(ItemSection section, Project project) : base(section, project.Name) { // Only for Uid computation. OutputFile = null; } public ProjectTarget(ItemSection section, string identifier, ProjectOutputFile outputFile, ProjectConfigurationList configurationList) : base(section, identifier) { ConfigurationList = configurationList; OutputFile = outputFile; switch (OutputFile.OutputType) { case Project.Configuration.OutputType.Dll: ProductType = "com.apple.product-type.library.dynamic"; ProductInstallPath = RemoveLineTag; break; case Project.Configuration.OutputType.Lib: ProductType = "com.apple.product-type.library.static"; ProductInstallPath = RemoveLineTag; break; case Project.Configuration.OutputType.IosTestBundle: ProductType = "com.apple.product-type.bundle.unit-test"; ProductInstallPath = "$(HOME)/Applications"; break; case Project.Configuration.OutputType.IosApp: ProductType = "com.apple.product-type.application"; ProductInstallPath = "$(HOME)/Applications"; break; case Project.Configuration.OutputType.Exe: case Project.Configuration.OutputType.None: case Project.Configuration.OutputType.Utility: ProductType = "com.apple.product-type.tool"; ProductInstallPath = RemoveLineTag; break; default: throw new NotSupportedException($"XCode generator doesn't handle {OutputFile.OutputType}"); } } public ProjectResourcesBuildPhase ResourcesBuildPhase { get; set; } public ProjectSourcesBuildPhase SourcesBuildPhase { get; set; } public String SourceBuildPhaseUID { get { return SourcesBuildPhase?.Uid ?? RemoveLineTag; } } public ProjectFrameworksBuildPhase FrameworksBuildPhase { get; set; } public UniqueList<ProjectShellScriptBuildPhase> ShellScriptPreBuildPhases { get; set; } public UniqueList<ProjectShellScriptBuildPhase> ShellScriptPostBuildPhases { get; set; } public String ShellScriptPreBuildPhaseUIDs { get { if (ShellScriptPreBuildPhases != null && ShellScriptPreBuildPhases.Any()) return string.Join(",", ShellScriptPreBuildPhases.Select(buildEvent => buildEvent.Uid)); return RemoveLineTag; } } public String ShellScriptPostBuildPhaseUIDs { get { if (ShellScriptPostBuildPhases != null && ShellScriptPostBuildPhases.Any()) return string.Join(",", ShellScriptPostBuildPhases.Select(buildEvent => buildEvent.Uid)); return RemoveLineTag; } } public ProjectOutputFile OutputFile { get; } public string ProductType { get; } public ProjectConfigurationList ConfigurationList { get; } public string ProductInstallPath { get; } } private class ProjectNativeTarget : ProjectTarget { public ProjectNativeTarget(string identifier) : base(ItemSection.PBXNativeTarget, identifier) { } public ProjectNativeTarget(Project project) : base(ItemSection.PBXNativeTarget, project) { } public ProjectNativeTarget(string identifier, ProjectOutputFile outputFile, ProjectConfigurationList configurationList, List<ProjectTargetDependency> dependencies) : base(ItemSection.PBXNativeTarget, identifier, outputFile, configurationList) { Dependencies = dependencies; } public override void GetAdditionalResolverParameters(ProjectItem item, Resolver resolver, ref Dictionary<string, string> resolverParameters) { if (null == OutputFile) throw new Error("Trying to compute dependencies on incomplete native target. "); ProjectNativeTarget folderItem = (ProjectNativeTarget)item; string childrenList = ""; foreach (ProjectTargetDependency childItem in folderItem.Dependencies) { using (resolver.NewScopedParameter("item", childItem)) { childrenList += resolver.Resolve(Template.SectionSubItem); } } resolverParameters.Add("itemChildren", childrenList); } public List<ProjectTargetDependency> Dependencies { get; } } private class ProjectLegacyTarget : ProjectTarget { private string _masterBffFilePath; public ProjectLegacyTarget(string identifier, ProjectOutputFile outputFile, ProjectConfigurationList configurationList, string masterBffFilePath) : base(ItemSection.PBXLegacyTarget, identifier, outputFile, configurationList) { _masterBffFilePath = masterBffFilePath; } public string BuildArgumentsString { get { var fastBuildCommandLineOptions = new List<string>(); fastBuildCommandLineOptions.Add("$(FASTBUILD_TARGET)"); // special envvar hardcoded in the template if (FastBuildSettings.FastBuildUseIDE) fastBuildCommandLineOptions.Add("-ide"); if (FastBuildSettings.FastBuildReport) fastBuildCommandLineOptions.Add("-report"); if (FastBuildSettings.FastBuildNoSummaryOnError) fastBuildCommandLineOptions.Add("-nosummaryonerror"); if (FastBuildSettings.FastBuildSummary) fastBuildCommandLineOptions.Add("-summary"); if (FastBuildSettings.FastBuildVerbose) fastBuildCommandLineOptions.Add("-verbose"); if (FastBuildSettings.FastBuildMonitor) fastBuildCommandLineOptions.Add("-monitor"); if (FastBuildSettings.FastBuildWait) fastBuildCommandLineOptions.Add("-wait"); if (FastBuildSettings.FastBuildNoStopOnError) fastBuildCommandLineOptions.Add("-nostoponerror"); if (FastBuildSettings.FastBuildFastCancel) fastBuildCommandLineOptions.Add("-fastcancel"); if (FastBuildSettings.FastBuildNoUnity) fastBuildCommandLineOptions.Add("-nounity"); fastBuildCommandLineOptions.Add("-config " + Path.GetFileName(_masterBffFilePath)); return string.Join(" ", fastBuildCommandLineOptions); } } public string BuildToolPath { get { return XCodeUtil.XCodeFormatSingleItem(Util.SimplifyPath(FastBuildSettings.FastBuildMakeCommand)); } } public string BuildWorkingDirectory { get { return XCodeUtil.XCodeFormatSingleItem(Path.GetDirectoryName(_masterBffFilePath)); } } } private class ProjectBuildConfiguration : ProjectItem { public ProjectBuildConfiguration(ItemSection section, string configurationName, Project.Configuration configuration, Options.ExplicitOptions options) : base(section, configurationName) { Configuration = configuration; Options = options; } public Options.ExplicitOptions Options { get; } public Project.Configuration Configuration { get; } public string Optimization { get { return Configuration.Target.Name; } } } private class ProjectBuildConfigurationForTarget : ProjectBuildConfiguration { public ProjectBuildConfigurationForTarget(ItemSection section, Project.Configuration configuration, ProjectTarget target, Options.ExplicitOptions options) : base(section, configuration.Target.Name, configuration, options) { Target = target; } public ProjectTarget Target { get; } } private class ProjectBuildConfigurationForNativeTarget : ProjectBuildConfigurationForTarget { public ProjectBuildConfigurationForNativeTarget(Project.Configuration configuration, ProjectNativeTarget nativeTarget, Options.ExplicitOptions options) : base(ItemSection.XCBuildConfiguration_NativeTarget, configuration, nativeTarget, options) { } } private class ProjectBuildConfigurationForLegacyTarget : ProjectBuildConfigurationForTarget { public ProjectBuildConfigurationForLegacyTarget(Project.Configuration configuration, ProjectLegacyTarget legacyTarget, Options.ExplicitOptions options) : base(ItemSection.XCBuildConfiguration_LegacyTarget, configuration, legacyTarget, options) { } } private class ProjectBuildConfigurationForUnitTestTarget : ProjectBuildConfigurationForTarget { public ProjectBuildConfigurationForUnitTestTarget(Project.Configuration configuration, ProjectTarget target, Options.ExplicitOptions options) : base(ItemSection.XCBuildConfiguration_UnitTestTarget, configuration, target, options) { } public override void GetAdditionalResolverParameters(ProjectItem item, Resolver resolver, ref Dictionary<string, string> resolverParameters) { string testHostParam = RemoveLineTag; var nativeTarget = Target as ProjectNativeTarget; if (nativeTarget == null) return; // Lookup for the app in the unit test dependencies. ProjectTargetDependency testHostTargetDependency = nativeTarget.Dependencies.Find(dependency => dependency.NativeTarget != null && dependency.NativeTarget.OutputFile.OutputType == Project.Configuration.OutputType.IosApp); if (testHostTargetDependency != null) { ProjectNativeTarget testHostTarget = testHostTargetDependency.NativeTarget; // Each ProjectNativeTarget have a list of ProjectBuildConfiguration that wrap a Project.Configuration. // Here we look for the Project.Configuration in the ProjectBuildConfiguration list of the test host target (app) // that match the unit tests bundle ProjectBuildConfiguration. Project.Configuration testConfig = testHostTarget.ConfigurationList.Configurations.First(config => config.Configuration.Name == this.Configuration.Name).Configuration; testHostParam = String.Format("$(BUILT_PRODUCTS_DIR)/{0}{1}{2}/{0}{1}", testHostTarget.Identifier, testConfig.TargetFileSuffix, ProjectOutputFile.GetFileExtension(testConfig)); } resolverParameters.Add("testHost", testHostParam); } } private class ProjectBuildConfigurationForProject : ProjectBuildConfiguration { public ProjectBuildConfigurationForProject(Project.Configuration configuration, Options.ExplicitOptions options) : base(ItemSection.XCBuildConfiguration_Project, configuration.Target.Name, configuration, options) { } } private class ProjectConfigurationList : ProjectItem { private HashSet<ProjectBuildConfiguration> _configurations; private ProjectItem _relatedItem; public ProjectConfigurationList(HashSet<ProjectBuildConfiguration> configurations, string configurationListName) : base(ItemSection.XCConfigurationList, configurationListName) { _configurations = configurations; } public override void GetAdditionalResolverParameters(ProjectItem item, Resolver resolver, ref Dictionary<string, string> resolverParameters) { ProjectConfigurationList configurationList = (ProjectConfigurationList)item; string childrenList = ""; foreach (ProjectBuildConfiguration childItem in configurationList.Configurations) { using (resolver.NewScopedParameter("item", childItem)) { childrenList += resolver.Resolve(Template.SectionSubItem); } } resolverParameters.Add("itemChildren", childrenList); } public HashSet<ProjectBuildConfiguration> Configurations { get { return _configurations; } } public ProjectBuildConfiguration DefaultConfiguration { get { if (_configurations.Count != 0) { return _configurations.First(); } else { return null; } } } public string ConfigurationType { get { if (_configurations.Count != 0) { return _configurations.First().SectionString; } else { return ""; } } } public ProjectItem RelatedItem { get { return _relatedItem; } set { _relatedItem = value; } } } private class ProjectMain : ProjectItem { private ProjectFolder _mainGroup; private ProjectTarget _target; private string _developmentTeam; private string _provisioningStyle; private ProjectConfigurationList _configurationList; private string _compatibilityVersion; private List<ProjectTarget> _targets; private Dictionary<ProjectFolder, ProjectReference> _projectReferences; private bool _iCloudSupport; public ProjectMain(string projectName, ProjectFolder mainGroup, ProjectConfigurationList configurationList, List<ProjectTarget> targets, bool iCloudSupport, string developmentTeam, string provisioningStyle) : base(ItemSection.PBXProject, projectName) { _target = null; _mainGroup = mainGroup; _developmentTeam = developmentTeam; _provisioningStyle = provisioningStyle; _configurationList = configurationList; _compatibilityVersion = "Xcode 3.2"; _targets = targets; _projectReferences = new Dictionary<ProjectFolder, ProjectReference>(); _iCloudSupport = iCloudSupport; } public ProjectMain(ProjectTarget target, ProjectFolder mainGroup, ProjectConfigurationList configurationList, bool iCloudSupport, string developmentTeam, string provisioningStyle) : base(ItemSection.PBXProject, target.Identifier) { _target = target; _mainGroup = mainGroup; _developmentTeam = developmentTeam; _provisioningStyle = provisioningStyle; _configurationList = configurationList; _compatibilityVersion = "Xcode 3.2"; _targets = new List<ProjectTarget> { target }; _projectReferences = new Dictionary<ProjectFolder, ProjectReference>(); _iCloudSupport = iCloudSupport; } public void AddProjectDependency(ProjectFolder projectGroup, ProjectReference projectFile) { _projectReferences.Add(projectGroup, projectFile); } public void AddTarget(ProjectNativeTarget additionalTarget) { _targets.Add(additionalTarget); } public override void GetAdditionalResolverParameters(ProjectItem item, Resolver resolver, ref Dictionary<string, string> resolverParameters) { //ProjectMain mainItem = (ProjectMain)item; string targetList = ""; foreach (ProjectTarget target in _targets) { using (resolver.NewScopedParameter("item", target)) { targetList += resolver.Resolve(Template.SectionSubItem); } } resolverParameters.Add("itemTargets", targetList); string dependenciesList = ""; foreach (KeyValuePair<ProjectFolder, ProjectReference> projectReference in _projectReferences) { using (resolver.NewScopedParameter("group", projectReference.Key)) using (resolver.NewScopedParameter("project", projectReference.Value)) { dependenciesList += resolver.Resolve(Template.ProjectReferenceSubItem); } } resolverParameters.Add("itemProjectReferences", dependenciesList); string targetAttributes = ""; foreach (ProjectTarget target in _targets) { using (resolver.NewScopedParameter("item", target)) using (resolver.NewScopedParameter("project", this)) { targetAttributes += resolver.Resolve(Template.ProjectTargetAttribute); } } resolverParameters.Add("itemTargetAttributes", targetAttributes); } public ProjectTarget Target { get { return _target; } } public ProjectFolder MainGroup { get { return _mainGroup; } } public string DevelopmentTeam { get { return _developmentTeam; } } public string ProvisioningStyle { get { return _provisioningStyle; } } public ProjectConfigurationList ConfigurationList { get { return _configurationList; } } public string CompatibilityVersion { get { return _compatibilityVersion; } } public string ICloudSupport { get { return _iCloudSupport ? "1" : "0"; } } } } }
45.758689
259
0.604104
[ "Apache-2.0" ]
Friendly0Fire/Sharpmake
Sharpmake.Generators/Apple/XCodeProj.cs
92,160
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.Collections.Generic; using System.Collections.Immutable; using System.Linq; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.PooledObjects; namespace Microsoft.CodeAnalysis.CSharp { internal class FlowAnalysisPass { /// <summary> /// The flow analysis pass. This pass reports required diagnostics for unreachable /// statements and uninitialized variables (through the call to FlowAnalysisWalker.Analyze), /// and inserts a final return statement if the end of a void-returning method is reachable. /// </summary> /// <param name="method">the method to be analyzed</param> /// <param name="block">the method's body</param> /// <param name="diagnostics">the receiver of the reported diagnostics</param> /// <param name="hasTrailingExpression">indicates whether this Script had a trailing expression</param> /// <param name="originalBodyNested">the original method body is the last statement in the block</param> /// <returns>the rewritten block for the method (with a return statement possibly inserted)</returns> public static BoundBlock Rewrite( MethodSymbol method, BoundBlock block, DiagnosticBag diagnostics, bool hasTrailingExpression, bool originalBodyNested) { #if DEBUG // We should only see a trailingExpression if we're in a Script initializer. Debug.Assert(!hasTrailingExpression || method.IsScriptInitializer); var initialDiagnosticCount = diagnostics.ToReadOnly().Length; #endif var compilation = method.DeclaringCompilation; if (method.ReturnsVoid || method.IsIterator || method.IsAsyncReturningTask(compilation)) { // we don't analyze synthesized void methods. if ((method.IsImplicitlyDeclared && !method.IsScriptInitializer) || Analyze(compilation, method, block, diagnostics)) { block = AppendImplicitReturn(block, method, originalBodyNested); } } else if (Analyze(compilation, method, block, diagnostics)) { // If the method is a lambda expression being converted to a non-void delegate type // and the end point is reachable then suppress the error here; a special error // will be reported by the lambda binder. Debug.Assert(method.MethodKind != MethodKind.AnonymousFunction); // Add implicit "return default(T)" if this is a submission that does not have a trailing expression. var submissionResultType = (method as SynthesizedInteractiveInitializerMethod)?.ResultType; if (!hasTrailingExpression && ((object)submissionResultType != null)) { Debug.Assert(!submissionResultType.IsVoidType()); var trailingExpression = new BoundDefaultExpression(method.GetNonNullSyntaxNode(), submissionResultType); var newStatements = block.Statements.Add(new BoundReturnStatement(trailingExpression.Syntax, RefKind.None, trailingExpression)); block = new BoundBlock(block.Syntax, ImmutableArray<LocalSymbol>.Empty, newStatements) { WasCompilerGenerated = true }; #if DEBUG // It should not be necessary to repeat analysis after adding this node, because adding a trailing // return in cases where one was missing should never produce different Diagnostics. IEnumerable<Diagnostic> GetErrorsOnly(IEnumerable<Diagnostic> diags) => diags.Where(d => d.Severity == DiagnosticSeverity.Error); var flowAnalysisDiagnostics = DiagnosticBag.GetInstance(); Debug.Assert(!Analyze(compilation, method, block, flowAnalysisDiagnostics)); // Ignore warnings since flow analysis reports nullability mismatches. Debug.Assert(GetErrorsOnly(flowAnalysisDiagnostics.ToReadOnly()).SequenceEqual(GetErrorsOnly(diagnostics.ToReadOnly().Skip(initialDiagnosticCount)))); flowAnalysisDiagnostics.Free(); #endif } // If there's more than one location, then the method is partial and we // have already reported a non-void partial method error. else if (method.Locations.Length == 1) { diagnostics.Add(ErrorCode.ERR_ReturnExpected, method.Locations[0], method); } } return block; } private static BoundBlock AppendImplicitReturn(BoundBlock body, MethodSymbol method, bool originalBodyNested) { if (originalBodyNested) { var statements = body.Statements; int n = statements.Length; var builder = ArrayBuilder<BoundStatement>.GetInstance(n); builder.AddRange(statements, n - 1); builder.Add(AppendImplicitReturn((BoundBlock)statements[n - 1], method)); return body.Update(body.Locals, ImmutableArray<LocalFunctionSymbol>.Empty, builder.ToImmutableAndFree()); } else { return AppendImplicitReturn(body, method); } } // insert the implicit "return" statement at the end of the method body // Normally, we wouldn't bother attaching syntax trees to compiler-generated nodes, but these // ones are going to have sequence points. internal static BoundBlock AppendImplicitReturn(BoundBlock body, MethodSymbol method) { Debug.Assert(body != null); Debug.Assert(method != null); SyntaxNode syntax = body.Syntax; Debug.Assert(body.WasCompilerGenerated || syntax.IsKind(SyntaxKind.Block) || syntax.IsKind(SyntaxKind.ArrowExpressionClause) || syntax.IsKind(SyntaxKind.ConstructorDeclaration) || syntax.IsKind(SyntaxKind.CompilationUnit)); BoundStatement ret = (method.IsIterator && !method.IsAsync) ? (BoundStatement)BoundYieldBreakStatement.Synthesized(syntax) : BoundReturnStatement.Synthesized(syntax, RefKind.None, null); return body.Update(body.Locals, body.LocalFunctions, body.Statements.Add(ret)); } private static bool Analyze( CSharpCompilation compilation, MethodSymbol method, BoundBlock block, DiagnosticBag diagnostics) { var result = ControlFlowPass.Analyze(compilation, method, block, diagnostics); DefiniteAssignmentPass.Analyze(compilation, method, block, diagnostics); return result; } } }
50.894366
170
0.635395
[ "MIT" ]
06needhamt/roslyn
src/Compilers/CSharp/Portable/FlowAnalysis/FlowAnalysisPass.cs
7,229
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the chime-2018-05-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.Chime.Model { /// <summary> /// This is the response object from the PutVoiceConnectorTermination operation. /// </summary> public partial class PutVoiceConnectorTerminationResponse : AmazonWebServiceResponse { private Termination _termination; /// <summary> /// Gets and sets the property Termination. /// <para> /// The updated termination setting details. /// </para> /// </summary> public Termination Termination { get { return this._termination; } set { this._termination = value; } } // Check to see if Termination property is set internal bool IsSetTermination() { return this._termination != null; } } }
29.526316
103
0.668449
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/Chime/Generated/Model/PutVoiceConnectorTerminationResponse.cs
1,683
C#
using System; using System.Collections.Generic; using System.Linq; using DependencySort; using NHibernate.Mapping; using urn.nhibernate.mapping.Item2.Item2; namespace NhCodeFirst.Conventions { public class AddVersion : IClassConvention, IRunAfter<CreateNonCompositeIdentity> { public void Apply(Type type, @class @class, IEnumerable<Type> entityTypes, hibernatemapping hbm) { if (type.GetMember("Version").Any()) @class.version = new version {name = "Version", column1 = "Version"}; } public IEnumerable<IAuxiliaryDatabaseObject> AuxDbObjects() { yield break; } } }
27.833333
104
0.669162
[ "MIT" ]
mcintyre321/NhCodeFirst
NhCodeFirst/Conventions/AddVersion.cs
668
C#
using System; using System.IO; using System.Text; using Calamari.Commands.Support; using Calamari.Deployment; using Calamari.Deployment.Conventions; using Calamari.Integration.FileSystem; using Calamari.Integration.Processes; using Calamari.Integration.Scripting; using FluentAssertions; using NSubstitute; using NSubstitute.Core.Arguments; using NUnit.Framework; namespace Calamari.Tests.Fixtures.Conventions { [TestFixture] public class ConfiguredScriptConventionFixture { ICalamariFileSystem fileSystem; IScriptEngine scriptEngine; ICommandLineRunner commandLineRunner; RunningDeployment deployment; CalamariVariableDictionary variables; const string stagingDirectory = "c:\\applications\\acme\\1.0.0"; [SetUp] public void SetUp() { fileSystem = Substitute.For<ICalamariFileSystem>(); scriptEngine = Substitute.For<IScriptEngine>(); commandLineRunner = Substitute.For<ICommandLineRunner>(); scriptEngine.GetSupportedTypes().Returns(new[] { ScriptSyntax.PowerShell }); variables = new CalamariVariableDictionary(); variables.Set(SpecialVariables.Package.EnabledFeatures, SpecialVariables.Features.CustomScripts); deployment = new RunningDeployment("C:\\packages", variables) { StagingDirectory = stagingDirectory }; } [Test] public void ShouldRunScriptAtAppropriateStage() { const string stage = DeploymentStages.PostDeploy; const string scriptBody = "lorem ipsum blah blah blah"; var scriptName = ConfiguredScriptConvention.GetScriptName(stage, ScriptSyntax.PowerShell); var scriptPath = Path.Combine(stagingDirectory, scriptName); var script = new Script(scriptPath); variables.Set(scriptName, scriptBody); var convention = CreateConvention(stage); scriptEngine.Execute(Arg.Any<Script>(), variables, commandLineRunner).Returns(new CommandResult("", 0)); convention.Install(deployment); fileSystem.Received().WriteAllBytes(scriptPath, Arg.Any<byte[]>()); scriptEngine.Received().Execute(Arg.Is<Script>(s => s.File == scriptPath), variables, commandLineRunner); } [Test] public void ShouldRemoveScriptFileAfterRunning() { const string stage = DeploymentStages.PostDeploy; var scriptName = ConfiguredScriptConvention.GetScriptName(stage, ScriptSyntax.PowerShell); var scriptPath = Path.Combine(stagingDirectory, scriptName); var script = new Script(scriptPath); variables.Set(scriptName, "blah blah"); var convention = CreateConvention(stage); scriptEngine.Execute(Arg.Any<Script>(), variables, commandLineRunner).Returns(new CommandResult("", 0)); convention.Install(deployment); fileSystem.Received().DeleteFile(scriptPath, Arg.Any<FailureOptions>()); } [Test] public void ShouldNotRemoveCustomPostDeployScriptFileAfterRunningIfSpecialVariableIsSet() { deployment.Variables.Set(SpecialVariables.DeleteScriptsOnCleanup, false.ToString()); const string stage = DeploymentStages.PostDeploy; var scriptName = ConfiguredScriptConvention.GetScriptName(stage, ScriptSyntax.PowerShell); var scriptPath = Path.Combine(stagingDirectory, scriptName); variables.Set(scriptName, "blah blah"); var convention = CreateConvention(stage); scriptEngine.Execute(Arg.Any<Script>(), variables, commandLineRunner).Returns(new CommandResult("", 0)); convention.Install(deployment); fileSystem.DidNotReceive().DeleteFile(scriptPath, Arg.Any<FailureOptions>()); } [Test] public void ShouldThrowAnErrorIfAScriptExistsWithTheWrongType() { const string stage = DeploymentStages.PostDeploy; var scriptName = ConfiguredScriptConvention.GetScriptName(stage, ScriptSyntax.CSharp); variables.Set(scriptName, "blah blah"); var convention = CreateConvention(stage); Action exec = () => convention.Install(deployment); exec.ShouldThrow<CommandException>().WithMessage("CSharp scripts are not supported on this platform (PostDeploy)"); } private ConfiguredScriptConvention CreateConvention(string deployStage) { return new ConfiguredScriptConvention(deployStage, fileSystem, scriptEngine, commandLineRunner); } } }
43.157407
127
0.682686
[ "Apache-2.0" ]
espenwa/Calamari
source/Calamari.Tests/Fixtures/Conventions/ConfiguredScriptConventionFixture.cs
4,663
C#
namespace De.Osthus.Ambeth.Security { public enum SecurityContextType { AUTHORIZED, AUTHENTICATED, NOT_REQUIRED } }
18.857143
44
0.719697
[ "Apache-2.0" ]
Dennis-Koch/ambeth
ambeth/Ambeth.Security/ambeth/security/SecurityContextType.cs
132
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace SuppressionCleanupTool.Tests.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("SuppressionCleanupTool.Tests.Properties.Resources", typeof(Resources).Assembly); resourceMan = temp; } return resourceMan; } } /// <summary> /// Overrides the current thread's CurrentUICulture property for all /// resource lookups using this strongly typed resource class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Globalization.CultureInfo Culture { get { return resourceCulture; } set { resourceCulture = value; } } /// <summary> /// Looks up a localized string similar to // 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.Concurrent; ///using System.Collections.Generic; ///using System.Collections.Immutable; ///using System.Linq; ///using System.Threading; ///using System.Threading.Tasks; ///using Microsoft.CodeAnalysis.CodeActions; ///using Microsoft.CodeAnalysis.Editing; ///using Microsoft.CodeA [rest of string was truncated]&quot;;. /// </summary> internal static string AbstractAddImportFeatureService { get { return ResourceManager.GetString("AbstractAddImportFeatureService", resourceCulture); } } } }
44.395349
194
0.616291
[ "MIT" ]
jnm2/SuppressionCleanupTool
src/SuppressionCleanupTool.Tests/Properties/Resources.Designer.cs
3,820
C#
using CadEditor; using System; using PluginMapEditor; //css_include shared_settings/BlockUtils.cs; //css_include shared_settings/SharedUtils.cs; //css_include little_red_hood/LittleRedHoodUtils.cs; public class Data { public string[] getPluginNames() { return new string[] { "PluginMapEditor.dll", }; } public OffsetRec getScreensOffset() { return new OffsetRec(0x6583, 9 , 16*15, 16, 15); } public bool isBigBlockEditorEnabled() { return false; } public bool isBlockEditorEnabled() { return true; } public bool isEnemyEditorEnabled() { return false; } public GetVideoPageAddrFunc getVideoPageAddrFunc() { return SharedUtils.fakeVideoAddr(); } public GetVideoChunkFunc getVideoChunkFunc() { return SharedUtils.getVideoChunk(new[] {"chr1.bin"}); } public SetVideoChunkFunc setVideoChunkFunc() { return null; } public bool isBuildScreenFromSmallBlocks() { return true; } public OffsetRec getBlocksOffset() { return new OffsetRec(0x7d93, 1 , 0x1000); } public int getBlocksCount() { return 256; } public int getBigBlocksCount() { return 256; } public int getPalBytesAddr() { return 0x6df3; } public GetBlocksFunc getBlocksFunc() { return BlockUtils.getBlocksLinear2x2Masked;} public SetBlocksFunc setBlocksFunc() { return BlockUtils.setBlocksLinear2x2Masked;} public GetPalFunc getPalFunc() { return SharedUtils.readPalFromBin(new[] {"pal-basement.bin"}); } public SetPalFunc setPalFunc() { return null;} //---------------------------------------------------------------------------- public MapInfo[] getMapsInfo() { return LittleRedHoodUtils.makeMapsInfo(); } public LoadMapFunc getLoadMapFunc() { return MapUtils.loadMapBatman; } public SaveMapFunc getSaveMapFunc() { return MapUtils.saveAttribs; } public bool isMapReadOnly() { return true; } public bool mapEditorSharePallete() { return true; } //---------------------------------------------------------------------------- }
45.391304
119
0.647031
[ "MIT" ]
spiiin/CadEditor
CadEditor/settings_nes/little_red_hood/Settings_LittleRedHood-basement.cs
2,088
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Security; using System.Threading.Tasks; using NewLife.Collections; using NewLife.Log; using NewLife.Model; using NewLife.Serialization; #if __WIN__ using System.Management; using Microsoft.VisualBasic.Devices; using Microsoft.Win32; #endif namespace NewLife { /// <summary>机器信息</summary> /// <remarks> /// 刷新信息成本较高,建议采用单例模式 /// </remarks> public class MachineInfo { #region 属性 /// <summary>系统名称</summary> public String OSName { get; set; } /// <summary>系统版本</summary> public String OSVersion { get; set; } /// <summary>产品名称。制造商</summary> public String Product { get; set; } /// <summary>处理器型号</summary> public String Processor { get; set; } /// <summary>处理器序列号</summary> public String CpuID { get; set; } /// <summary>硬件唯一标识</summary> public String UUID { get; set; } /// <summary>系统标识</summary> public String Guid { get; set; } /// <summary>磁盘序列号</summary> public String DiskID { get; set; } /// <summary>内存总量</summary> public UInt64 Memory { get; set; } /// <summary>可用内存</summary> public UInt64 AvailableMemory { get; private set; } /// <summary>CPU占用率</summary> public Single CpuRate { get; private set; } /// <summary>温度</summary> public Double Temperature { get; set; } #endregion #region 构造 /// <summary>当前机器信息。默认null,在RegisterAsync后才能使用</summary> public static MachineInfo Current { get; set; } private static Task<MachineInfo> _task; /// <summary>异步注册一个初始化后的机器信息实例</summary> /// <returns></returns> public static Task<MachineInfo> RegisterAsync() { if (_task != null) return _task; return _task = Task.Factory.StartNew(() => { var set = Setting.Current; var dataPath = set.DataPath; if (dataPath.IsNullOrEmpty()) dataPath = "Data"; // 文件缓存,加快机器信息获取 var file = Path.GetTempPath().CombinePath("machine_info.json"); var file2 = dataPath.CombinePath("machine_info.json").GetBasePath(); if (Current == null) { var f = file; if (!File.Exists(f)) f = file2; if (File.Exists(f)) { try { //XTrace.WriteLine("Load MachineInfo {0}", f); Current = File.ReadAllText(f).ToJsonEntity<MachineInfo>(); } catch { } } } var mi = Current ?? new MachineInfo(); mi.Init(); Current = mi; //// 定时刷新 //if (msRefresh > 0) mi._timer = new TimerX(s => mi.Refresh(), null, msRefresh, msRefresh) { Async = true }; // 注册到对象容器 ObjectContainer.Current.AddSingleton(mi); try { var json = mi.ToJson(true); File.WriteAllText(file.EnsureDirectory(true), json); File.WriteAllText(file2.EnsureDirectory(true), json); } catch { } return mi; }); } /// <summary>获取当前信息,如果未设置则等待异步注册结果</summary> /// <returns></returns> public static MachineInfo GetCurrent() => Current ?? RegisterAsync().Result; /// <summary>从对象容器中获取一个已注册机器信息实例</summary> /// <returns></returns> public static MachineInfo Resolve() => ObjectContainer.Current.Resolve<MachineInfo>(); #endregion #region 方法 /// <summary>刷新</summary> public void Init() { var osv = Environment.OSVersion; if (OSVersion.IsNullOrEmpty()) OSVersion = osv.Version + ""; if (OSName.IsNullOrEmpty()) OSName = (osv + "").TrimStart("Microsoft").TrimEnd(OSVersion).Trim(); if (Guid.IsNullOrEmpty()) Guid = ""; try { #if __CORE__ if (Runtime.Windows) LoadWindowsInfo(); else if (Runtime.Linux) LoadLinuxInfo(); #else if (Runtime.Windows) LoadWindowsInfoFx(); else if (Runtime.Linux) LoadLinuxInfo(); #endif } catch (Exception ex) { XTrace.WriteException(ex); } // window+netcore 不方便读取注册表,随机生成一个guid,借助文件缓存确保其不变 if (Guid.IsNullOrEmpty()) Guid = "0-" + System.Guid.NewGuid().ToString(); if (UUID.IsNullOrEmpty()) UUID = "0-" + System.Guid.NewGuid().ToString(); try { Refresh(); } catch { } } private void LoadWindowsInfoFx() { #if !__CORE__ var machine_guid = ""; var reg = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Cryptography"); if (reg != null) machine_guid = reg.GetValue("MachineGuid") + ""; if (machine_guid.IsNullOrEmpty()) { reg = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64); if (reg != null) machine_guid = reg.GetValue("MachineGuid") + ""; } var ci = new ComputerInfo(); try { Memory = ci.TotalPhysicalMemory; // 系统名取WMI可能出错 OSName = ci.OSFullName.TrimStart("Microsoft").Trim(); OSVersion = ci.OSVersion; } catch { var reg2 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); if (reg2 != null) { OSName = reg2.GetValue("ProductName") + ""; OSVersion = reg2.GetValue("ReleaseId") + ""; } } Processor = GetInfo("Win32_Processor", "Name"); CpuID = GetInfo("Win32_Processor", "ProcessorId"); var uuid = GetInfo("Win32_ComputerSystemProduct", "UUID"); Product = GetInfo("Win32_ComputerSystemProduct", "Name"); DiskID = GetInfo("Win32_DiskDrive", "SerialNumber"); // UUID取不到时返回 FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF if (!uuid.IsNullOrEmpty() && !uuid.EqualIgnoreCase("FFFFFFFF-FFFF-FFFF-FFFF-FFFFFFFFFFFF")) UUID = uuid; //// 可能因WMI导致读取UUID失败 //if (UUID.IsNullOrEmpty()) //{ // var reg3 = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion"); // if (reg3 != null) UUID = reg3.GetValue("ProductId") + ""; //} // 读取主板温度,不太准。标准方案是ring0通过IOPort读取CPU温度,太难在基础类库实现 var str = GetInfo("Win32_TemperatureProbe", "CurrentReading"); if (!str.IsNullOrEmpty()) { Temperature = str.ToDouble(); } else { str = GetInfo("MSAcpi_ThermalZoneTemperature", "CurrentTemperature"); if (!str.IsNullOrEmpty()) Temperature = (str.ToDouble() - 2732) / 10.0; } if (!machine_guid.IsNullOrEmpty()) Guid = machine_guid; #endif } private void LoadWindowsInfo() { var str = ""; var os = ReadWmic("os", "Caption", "Version"); if (os != null) { if (os.TryGetValue("Caption", out str)) OSName = str.TrimStart("Microsoft").Trim(); if (os.TryGetValue("Version", out str)) OSVersion = str; } var csproduct = ReadWmic("csproduct", "Name", "UUID"); if (csproduct != null) { if (csproduct.TryGetValue("Name", out str)) Product = str; if (csproduct.TryGetValue("UUID", out str)) UUID = str; } var disk = ReadWmic("diskdrive", "serialnumber"); if (disk != null) { if (disk.TryGetValue("serialnumber", out str)) DiskID = str?.Trim(); } // 不要在刷新里面取CPU负载,因为运行wmic会导致CPU负载很不准确,影响测量 var cpu = ReadWmic("cpu", "Name", "ProcessorId", "LoadPercentage"); if (cpu != null) { if (cpu.TryGetValue("Name", out str)) Processor = str; if (cpu.TryGetValue("ProcessorId", out str)) CpuID = str; if (cpu.TryGetValue("LoadPercentage", out str)) CpuRate = (Single)(str.ToDouble() / 100); } // 从注册表读取 MachineGuid str = Execute("reg", @"query HKLM\SOFTWARE\Microsoft\Cryptography /v MachineGuid"); if (!str.IsNullOrEmpty() && str.Contains("REG_SZ")) Guid = str.Substring("REG_SZ", null).Trim(); } private void LoadLinuxInfo() { var str = GetLinuxName(); if (!str.IsNullOrEmpty()) OSName = str; // 树莓派的Hardware无法区分P0/P4 var dic = ReadInfo("/proc/cpuinfo"); if (dic != null) { if (dic.TryGetValue("Hardware", out str) || dic.TryGetValue("cpu model", out str) || dic.TryGetValue("model name", out str)) Processor = str; if (dic.TryGetValue("Model", out str)) Product = str; if (dic.TryGetValue("Serial", out str)) CpuID = str; } var mid = "/etc/machine-id"; if (!File.Exists(mid)) mid = "/var/lib/dbus/machine-id"; if (TryRead(mid, out var value)) Guid = value; var file = "/sys/class/dmi/id/product_uuid"; if (TryRead(file, out value)) UUID = value; file = "/sys/class/dmi/id/product_name"; if (TryRead(file, out value)) Product = value; var disks = GetFiles("/dev/disk/by-id", true); if (disks.Count == 0) disks = GetFiles("/dev/disk/by-uuid", false); if (disks.Count > 0) DiskID = disks.Join(","); var dmi = Execute("dmidecode")?.SplitAsDictionary(":", "\n"); if (dmi != null) { if (dmi.TryGetValue("ID", out str)) CpuID = str.Replace(" ", null); if (dmi.TryGetValue("UUID", out str)) UUID = str; if (dmi.TryGetValue("Product Name", out str)) Product = str; //if (TryFind(dmi, new[] { "Serial Number" }, out str)) Guid = str; } // 从release文件读取产品 var prd = GetProductByRelease(); if (!prd.IsNullOrEmpty()) Product = prd; } /// <summary>获取实时数据,如CPU、内存、温度</summary> public void Refresh() { if (Runtime.Windows) { MEMORYSTATUSEX ms = default; ms.Init(); if (GlobalMemoryStatusEx(ref ms)) { Memory = ms.ullTotalPhys; AvailableMemory = ms.ullAvailPhys; } } // 特别识别Linux发行版 else if (Runtime.Linux) { var dic = ReadInfo("/proc/meminfo"); if (dic != null) { if (dic.TryGetValue("MemTotal", out var str)) Memory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024; if (dic.TryGetValue("MemAvailable", out str) || dic.TryGetValue("MemFree", out str)) AvailableMemory = (UInt64)str.TrimEnd(" kB").ToInt() * 1024; } var file = "/sys/class/thermal/thermal_zone0/temp"; if (TryRead(file, out var value)) Temperature = value.ToDouble() / 1000; else { // A2温度获取,Ubuntu 16.04 LTS, Linux 3.4.39 file = "/sys/class/hwmon/hwmon0/device/temp_value"; if (TryRead(file, out value)) Temperature = value.Substring(null, ":").ToDouble(); } //var upt = Execute("uptime"); //if (!upt.IsNullOrEmpty()) //{ // str = upt.Substring("load average:"); // if (!str.IsNullOrEmpty()) CpuRate = (Single)str.Split(",")[0].ToDouble(); //} //file = "/proc/loadavg"; //if (File.Exists(file)) CpuRate = (Single)File.ReadAllText(file).Substring(null, " ").ToDouble() / Environment.ProcessorCount; file = "/proc/stat"; if (File.Exists(file)) { // CPU指标:user,nice, system, idle, iowait, irq, softirq // cpu 57057 0 14420 1554816 0 443 0 0 0 0 using var reader = new StreamReader(file); var line = reader.ReadLine(); if (!line.IsNullOrEmpty() && line.StartsWith("cpu")) { var vs = line.TrimStart("cpu").Trim().Split(" "); var current = new SystemTime { IdleTime = vs[3].ToLong(), TotalTime = vs.Take(7).Select(e => e.ToLong()).Sum().ToLong(), }; var idle = current.IdleTime - (_systemTime?.IdleTime ?? 0); var total = current.TotalTime - (_systemTime?.TotalTime ?? 0); _systemTime = current; CpuRate = total == 0 ? 0 : ((Single)(total - idle) / total); } } } if (Runtime.Windows) { GetSystemTimes(out var idleTime, out var kernelTime, out var userTime); var current = new SystemTime { IdleTime = idleTime.ToLong(), TotalTime = kernelTime.ToLong() + userTime.ToLong(), }; var idle = current.IdleTime - (_systemTime?.IdleTime ?? 0); var total = current.TotalTime - (_systemTime?.TotalTime ?? 0); _systemTime = current; CpuRate = total == 0 ? 0 : ((Single)(total - idle) / total); } } #endregion #region 辅助 /// <summary>获取Linux发行版名称</summary> /// <returns></returns> public static String GetLinuxName() { var fr = "/etc/redhat-release"; if (TryRead(fr, out var value)) return value; var dr = "/etc/debian-release"; if (TryRead(dr, out value)) return value; var sr = "/etc/os-release"; if (TryRead(sr, out value)) return value?.SplitAsDictionary("=", "\n", true)["PRETTY_NAME"].Trim(); var uname = Execute("uname", "-sr")?.Trim(); if (!uname.IsNullOrEmpty()) return uname; return null; } private static String GetProductByRelease() { var di = "/etc/".AsDirectory(); if (!di.Exists) return null; foreach (var fi in di.GetFiles("*-release")) { if (!fi.Name.EqualIgnoreCase("redhat-release", "debian-release", "os-release", "system-release")) { var dic = File.ReadAllText(fi.FullName).SplitAsDictionary("=", "\n", true); if (dic.TryGetValue("BOARD", out var str)) return str; if (dic.TryGetValue("BOARD_NAME", out str)) return str; } } return null; } private static Boolean TryRead(String fileName, out String value) { value = null; if (!File.Exists(fileName)) return false; try { value = File.ReadAllText(fileName)?.Trim(); if (value.IsNullOrEmpty()) return false; } catch { return false; } return true; } private static IDictionary<String, String> ReadInfo(String file, Char separate = ':') { if (file.IsNullOrEmpty() || !File.Exists(file)) return null; var dic = new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase); using var reader = new StreamReader(file); while (!reader.EndOfStream) { // 按行读取 var line = reader.ReadLine(); if (line != null) { // 分割 var p = line.IndexOf(separate); if (p > 0) { var key = line.Substring(0, p).Trim(); var value = line.Substring(p + 1).Trim(); dic[key] = value; } } } return dic; } private static String Execute(String cmd, String arguments = null) { try { var psi = new ProcessStartInfo(cmd, arguments) { RedirectStandardOutput = true }; var process = Process.Start(psi); if (!process.WaitForExit(3_000)) { process.Kill(); return null; } return process.StandardOutput.ReadToEnd(); } catch { return null; } } /// <summary>通过WMIC命令读取信息</summary> /// <param name="type"></param> /// <param name="keys"></param> /// <returns></returns> public static IDictionary<String, String> ReadWmic(String type, params String[] keys) { var dic = new Dictionary<String, String>(StringComparer.OrdinalIgnoreCase); var args = $"{type} get {keys.Join(",")} /format:list"; var str = Execute("wmic", args)?.Trim(); if (str.IsNullOrEmpty()) return dic; //return str.SplitAsDictionary("=", Environment.NewLine); var ss = str.Split(Environment.NewLine); foreach (var item in ss) { var ks = item.Split("="); if (ks != null && ks.Length >= 2) { var k = ks[0].Trim(); var v = ks[1].Trim(); if (dic.TryGetValue(k, out var val)) dic[k] = val + "," + v; else dic[k] = v; } } return dic; } #endregion #region 内存 [DllImport("Kernel32.dll", CharSet = CharSet.Auto, SetLastError = true)] [SecurityCritical] [return: MarshalAs(UnmanagedType.Bool)] internal static extern Boolean GlobalMemoryStatusEx(ref MEMORYSTATUSEX lpBuffer); internal struct MEMORYSTATUSEX { internal UInt32 dwLength; internal UInt32 dwMemoryLoad; internal UInt64 ullTotalPhys; internal UInt64 ullAvailPhys; internal UInt64 ullTotalPageFile; internal UInt64 ullAvailPageFile; internal UInt64 ullTotalVirtual; internal UInt64 ullAvailVirtual; internal UInt64 ullAvailExtendedVirtual; internal void Init() => dwLength = checked((UInt32)Marshal.SizeOf(typeof(MEMORYSTATUSEX))); } #endregion #region 磁盘 /// <summary>获取指定目录所在盘可用空间,默认当前目录</summary> /// <param name="path"></param> /// <returns>返回可用空间,字节,获取失败返回-1</returns> public static Int64 GetFreeSpace(String path = null) { if (path.IsNullOrEmpty()) path = "."; var driveInfo = new DriveInfo(Path.GetPathRoot(path.GetFullPath())); if (driveInfo == null || !driveInfo.IsReady) return -1; try { return driveInfo.AvailableFreeSpace; } catch { return -1; } } /// <summary>获取指定目录下文件名,支持去掉后缀的去重,主要用于Linux</summary> /// <param name="path"></param> /// <param name="trimSuffix"></param> /// <returns></returns> public static ICollection<String> GetFiles(String path, Boolean trimSuffix = false) { var list = new List<String>(); if (path.IsNullOrEmpty()) return list; var di = path.AsDirectory(); if (!di.Exists) return list; var list2 = di.GetFiles().Select(e => e.Name).ToList(); foreach (var item in list2) { var line = item?.Trim(); if (!line.IsNullOrEmpty()) { if (trimSuffix) { if (!list2.Any(e => e != line && line.StartsWith(e))) list.Add(line); } else { list.Add(line); } } } return list; } #endregion #region Windows辅助 [DllImport("kernel32.dll", SetLastError = true)] private static extern Boolean GetSystemTimes(out FILETIME idleTime, out FILETIME kernelTime, out FILETIME userTime); private struct FILETIME { public UInt32 Low; public UInt32 High; public FILETIME(Int64 time) { Low = (UInt32)time; High = (UInt32)(time >> 32); } public Int64 ToLong() => (Int64)(((UInt64)High << 32) | Low); } private class SystemTime { public Int64 IdleTime; public Int64 TotalTime; } private SystemTime _systemTime; #if __WIN__ /// <summary>获取WMI信息</summary> /// <param name="path"></param> /// <param name="property"></param> /// <returns></returns> public static String GetInfo(String path, String property) { // Linux Mono不支持WMI if (Runtime.Mono) return ""; var bbs = new List<String>(); try { var wql = $"Select {property} From {path}"; var cimobject = new ManagementObjectSearcher(wql); var moc = cimobject.Get(); foreach (var mo in moc) { var val = mo?.Properties?[property]?.Value; if (val != null) bbs.Add(val.ToString().Trim()); } } catch (Exception ex) { //XTrace.WriteException(ex); if (XTrace.Log.Level <= LogLevel.Debug) XTrace.WriteLine("WMI.GetInfo({0})失败!{1}", path, ex.Message); return ""; } bbs.Sort(); return bbs.Distinct().Join(); } #endif #endregion } }
34.127007
143
0.483424
[ "MIT" ]
justinlxf/X
NewLife.Core/Common/MachineInfo.cs
24,267
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; [CreateAssetMenu(menuName = "Variable/Vector 4")] public class Vector4Variable : ScriptableObject { public Vector4 Value { get { return value; } set { this.value = value; } } [SerializeField] private Vector4 value; }
18.428571
49
0.591731
[ "MIT" ]
killermode15/scriptable_object_variable_library
ScriptableVariableUnity/ScriptableVariableUnity/Variables/Vector4Variable.cs
389
C#
// <copyright file="IccDataReader.Curves.cs" company="James Jackson-South"> // Copyright (c) James Jackson-South and contributors. // Licensed under the Apache License, Version 2.0. // </copyright> namespace ImageSharp.Tests { internal static class IccTestDataMultiProcessElement { #region CurveSet /// <summary> /// <para>Input Channel Count: 3</para> /// <para>Output Channel Count: 3</para> /// </summary> public static readonly IccCurveSetProcessElement CurvePE_ValGrad = new IccCurveSetProcessElement(new IccOneDimensionalCurve[] { IccTestDataCurves.OneDimensional_ValFormula1, IccTestDataCurves.OneDimensional_ValFormula2, IccTestDataCurves.OneDimensional_ValFormula1 }); /// <summary> /// <para>Input Channel Count: 3</para> /// <para>Output Channel Count: 3</para> /// </summary> public static readonly byte[] CurvePE_Grad = ArrayHelper.Concat ( IccTestDataCurves.OneDimensional_Formula1, IccTestDataCurves.OneDimensional_Formula2, IccTestDataCurves.OneDimensional_Formula1 ); public static readonly object[][] CurveSetTestData = { new object[] { CurvePE_Grad, CurvePE_ValGrad, 3, 3 }, }; #endregion #region Matrix /// <summary> /// <para>Input Channel Count: 3</para> /// <para>Output Channel Count: 3</para> /// </summary> public static readonly IccMatrixProcessElement MatrixPE_ValGrad = new IccMatrixProcessElement ( IccTestDataMatrix.Single_2DArray_ValGrad, IccTestDataMatrix.Single_1DArray_ValGrad ); /// <summary> /// <para>Input Channel Count: 3</para> /// <para>Output Channel Count: 3</para> /// </summary> public static readonly byte[] MatrixPE_Grad = ArrayHelper.Concat ( IccTestDataMatrix.Single_2D_Grad, IccTestDataMatrix.Single_1D_Grad ); public static readonly object[][] MatrixTestData = { new object[] { MatrixPE_Grad, MatrixPE_ValGrad, 3, 3 }, }; #endregion #region CLUT /// <summary> /// <para>Input Channel Count: 2</para> /// <para>Output Channel Count: 3</para> /// </summary> public static readonly IccClutProcessElement CLUTPE_ValGrad = new IccClutProcessElement(IccTestDataLut.CLUT_Valf32); /// <summary> /// <para>Input Channel Count: 2</para> /// <para>Output Channel Count: 3</para> /// </summary> public static readonly byte[] CLUTPE_Grad = IccTestDataLut.CLUT_f32; public static readonly object[][] ClutTestData = { new object[] { CLUTPE_Grad, CLUTPE_ValGrad, 2, 3 }, }; #endregion #region MultiProcessElement public static readonly IccMultiProcessElement MPE_ValMatrix = MatrixPE_ValGrad; public static readonly IccMultiProcessElement MPE_ValCLUT = CLUTPE_ValGrad; public static readonly IccMultiProcessElement MPE_ValCurve = CurvePE_ValGrad; public static readonly IccMultiProcessElement MPE_ValbACS = new IccBAcsProcessElement(3, 3); public static readonly IccMultiProcessElement MPE_ValeACS = new IccEAcsProcessElement(3, 3); public static readonly byte[] MPE_Matrix = ArrayHelper.Concat ( new byte[] { 0x6D, 0x61, 0x74, 0x66, 0x00, 0x03, 0x00, 0x03, }, MatrixPE_Grad ); public static readonly byte[] MPE_CLUT = ArrayHelper.Concat ( new byte[] { 0x63, 0x6C, 0x75, 0x74, 0x00, 0x02, 0x00, 0x03, }, CLUTPE_Grad ); public static readonly byte[] MPE_Curve = ArrayHelper.Concat ( new byte[] { 0x6D, 0x66, 0x6C, 0x74, 0x00, 0x03, 0x00, 0x03, }, CurvePE_Grad ); public static readonly byte[] MPE_bACS = { 0x62, 0x41, 0x43, 0x53, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; public static readonly byte[] MPE_eACS = { 0x65, 0x41, 0x43, 0x53, 0x00, 0x03, 0x00, 0x03, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, }; public static readonly object[][] MultiProcessElementTestData = { new object[] { MPE_Matrix, MPE_ValMatrix }, new object[] { MPE_CLUT, MPE_ValCLUT }, new object[] { MPE_Curve, MPE_ValCurve }, new object[] { MPE_bACS, MPE_ValbACS }, new object[] { MPE_eACS, MPE_ValeACS }, }; #endregion } }
31.841772
133
0.569867
[ "Apache-2.0" ]
OrchardCMS/ImageSharp
tests/ImageSharp.Tests/TestDataIcc/IccTestDataMultiProcessElements.cs
5,033
C#
// ------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. // ------------------------------------------------------------ namespace Microsoft.Azure.Cosmos.ChangeFeed.Pagination { using System; using System.Threading; using System.Threading.Tasks; using Microsoft.Azure.Cosmos.Pagination; using Microsoft.Azure.Cosmos.Query.Core.Monads; using Microsoft.Azure.Cosmos.Tracing; using Microsoft.Azure.Documents; internal sealed class ChangeFeedPartitionRangePageAsyncEnumerator : PartitionRangePageAsyncEnumerator<ChangeFeedPage, ChangeFeedState> { private readonly IChangeFeedDataSource changeFeedDataSource; private readonly int pageSize; public ChangeFeedPartitionRangePageAsyncEnumerator( IChangeFeedDataSource changeFeedDataSource, FeedRangeInternal range, int pageSize, ChangeFeedState state, CancellationToken cancellationToken) : base(range, cancellationToken, state) { this.changeFeedDataSource = changeFeedDataSource ?? throw new ArgumentNullException(nameof(changeFeedDataSource)); this.pageSize = pageSize; } public override ValueTask DisposeAsync() => default; protected override Task<TryCatch<ChangeFeedPage>> GetNextPageAsync(ITrace trace, CancellationToken cancellationToken) => this.changeFeedDataSource.MonadicChangeFeedAsync( this.State, this.Range, this.pageSize, trace, cancellationToken); } }
38.952381
178
0.650367
[ "MIT" ]
isabella232/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/src/ChangeFeed/Pagination/ChangeFeedPartitionRangePageAsyncEnumerator.cs
1,638
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: Templates\CSharp\Model\ComplexType.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Runtime.Serialization; using Newtonsoft.Json; /// <summary> /// The type CustomTimeZone. /// </summary> [JsonObject(MemberSerialization = MemberSerialization.OptIn)] public partial class CustomTimeZone : TimeZoneBase { /// <summary> /// Gets or sets bias. /// The time offset of the time zone from Coordinated Universal Time (UTC). This value is in minutes. Time zones that are ahead of UTC have a positive offset; time zones that are behind UTC have a negative offset. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "bias", Required = Newtonsoft.Json.Required.Default)] public Int32? Bias { get; set; } /// <summary> /// Gets or sets standardOffset. /// Specifies when the time zone switches from daylight saving time to standard time. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "standardOffset", Required = Newtonsoft.Json.Required.Default)] public StandardTimeZoneOffset StandardOffset { get; set; } /// <summary> /// Gets or sets daylightOffset. /// Specifies when the time zone switches from standard time to daylight saving time. /// </summary> [JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "daylightOffset", Required = Newtonsoft.Json.Required.Default)] public DaylightTimeZoneOffset DaylightOffset { get; set; } } }
44.666667
221
0.633862
[ "MIT" ]
gurry/msgraph-beta-sdk-dotnet
src/Microsoft.Graph/Models/Generated/CustomTimeZone.cs
2,145
C#
namespace AngleSharp.Dom.Css { using System; using System.IO; sealed class GroupCondition : CssNode, IConditionFunction { IConditionFunction _content; public IConditionFunction Content { get { return _content ?? new EmptyCondition(); } set { if (_content != null) { RemoveChild(_content); } _content = value; if (value != null) { AppendChild(_content); } } } public Boolean Check() { return Content.Check(); } public override void ToCss(TextWriter writer, IStyleFormatter formatter) { writer.Write("("); Content.ToCss(writer, formatter); writer.Write(")"); } } }
21.857143
80
0.454248
[ "MIT" ]
ArmyMedalMei/AngleSharp
src/AngleSharp/Dom/Css/ConditionFunctions/GroupCondition.cs
920
C#
// Copyright (c) Stickymaddness 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; namespace Sextant.Tests.Builders { public class EventBuilder { private string _event; private Dictionary<string, object> _payload = new Dictionary<string, object>(); public static implicit operator TestEvent(EventBuilder b) => new TestEvent(b._event, b._payload); public EventBuilder WithEvent(string @event) { _event = @event; return this; } public EventBuilder WithPayload(string key, object value) { _payload[key] = value; return this; } } }
27.928571
111
0.643223
[ "Apache-2.0" ]
RikCSherman/R2R-VoiceAttack
Sextant.Tests/Builders/EventBuilder.cs
784
C#
using Microsoft.Extensions.DependencyInjection; using Newtonsoft.Json; using Newtonsoft.Json.Serialization; namespace Microservice.Core3.Basic { public partial class Startup { private static void ConfigureJsonSettings(IMvcBuilder builder) { DefaultContractResolver snakeCase = new DefaultContractResolver { NamingStrategy = new SnakeCaseNamingStrategy() }; DefaultContractResolver camelCase = new DefaultContractResolver { NamingStrategy = new CamelCaseNamingStrategy() }; // Json Settings for all responses builder.AddNewtonsoftJson(options => { options.SerializerSettings.ContractResolver = snakeCase; options.SerializerSettings.Formatting = Formatting.Indented; options.SerializerSettings.NullValueHandling = NullValueHandling.Ignore; }); // Json Settings for all static Serialize and Deserialize JsonConvert.DefaultSettings = () => new JsonSerializerSettings { ContractResolver = camelCase, Formatting = Formatting.Indented, NullValueHandling = NullValueHandling.Ignore }; } } }
40.870968
128
0.646409
[ "MIT" ]
RASK18/Microservice.Core3.Basic
Microservice.Core3.Basic/Startup.Json.cs
1,267
C#
namespace Kisaragi.Views { partial class VersionWindow { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(VersionWindow)); this.MainTitle = new System.Windows.Forms.Label(); this.label1 = new System.Windows.Forms.Label(); this.label2 = new System.Windows.Forms.Label(); this.label3 = new System.Windows.Forms.Label(); this.CloseButton = new System.Windows.Forms.Button(); this.gitIcon = new System.Windows.Forms.PictureBox(); this.Twitter = new System.Windows.Forms.PictureBox(); this.kisaragi = new System.Windows.Forms.PictureBox(); ((System.ComponentModel.ISupportInitialize)(this.gitIcon)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.Twitter)).BeginInit(); ((System.ComponentModel.ISupportInitialize)(this.kisaragi)).BeginInit(); this.SuspendLayout(); // // MainTitle // this.MainTitle.AutoSize = true; this.MainTitle.Font = new System.Drawing.Font("メイリオ", 21.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.MainTitle.Location = new System.Drawing.Point(168, 12); this.MainTitle.Name = "MainTitle"; this.MainTitle.Size = new System.Drawing.Size(131, 44); this.MainTitle.TabIndex = 0; this.MainTitle.Text = "Kisaragi"; // // label1 // this.label1.AutoSize = true; this.label1.Font = new System.Drawing.Font("メイリオ", 9.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.label1.Location = new System.Drawing.Point(222, 56); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(262, 20); this.label1.TabIndex = 1; this.label1.Text = " - 快適なPC Lifeを送るための時報アプリ - "; // // label2 // this.label2.AutoSize = true; this.label2.Font = new System.Drawing.Font("メイリオ", 12.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.label2.Location = new System.Drawing.Point(180, 80); this.label2.Name = "label2"; this.label2.Size = new System.Drawing.Size(158, 25); this.label2.TabIndex = 2; this.label2.Text = "Author : Asterisk."; // // label3 // this.label3.AutoSize = true; this.label3.Font = new System.Drawing.Font("メイリオ", 12.75F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(128))); this.label3.Location = new System.Drawing.Point(282, 106); this.label3.Name = "label3"; this.label3.Size = new System.Drawing.Size(222, 25); this.label3.TabIndex = 3; this.label3.Text = "まったり開発中(*\'ω\'*)~~"; // // CloseButton // this.CloseButton.Location = new System.Drawing.Point(424, 139); this.CloseButton.Name = "CloseButton"; this.CloseButton.Size = new System.Drawing.Size(75, 23); this.CloseButton.TabIndex = 4; this.CloseButton.Text = "閉じる"; this.CloseButton.UseVisualStyleBackColor = true; // // gitIcon // this.gitIcon.Location = new System.Drawing.Point(176, 112); this.gitIcon.Name = "gitIcon"; this.gitIcon.Size = new System.Drawing.Size(50, 50); this.gitIcon.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.gitIcon.TabIndex = 5; this.gitIcon.TabStop = false; // // Twitter // this.Twitter.Location = new System.Drawing.Point(226, 112); this.Twitter.Name = "Twitter"; this.Twitter.Size = new System.Drawing.Size(50, 50); this.Twitter.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.Twitter.TabIndex = 6; this.Twitter.TabStop = false; // // kisaragi // this.kisaragi.Location = new System.Drawing.Point(12, 12); this.kisaragi.Name = "kisaragi"; this.kisaragi.Size = new System.Drawing.Size(150, 150); this.kisaragi.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom; this.kisaragi.TabIndex = 7; this.kisaragi.TabStop = false; // // VersionWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 12F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.AutoSize = true; this.BackColor = System.Drawing.Color.White; this.ClientSize = new System.Drawing.Size(511, 172); this.Controls.Add(this.kisaragi); this.Controls.Add(this.Twitter); this.Controls.Add(this.gitIcon); this.Controls.Add(this.CloseButton); this.Controls.Add(this.label3); this.Controls.Add(this.label2); this.Controls.Add(this.label1); this.Controls.Add(this.MainTitle); this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle; this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.Name = "VersionWindow"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen; this.Text = "Kisaragi について"; ((System.ComponentModel.ISupportInitialize)(this.gitIcon)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.Twitter)).EndInit(); ((System.ComponentModel.ISupportInitialize)(this.kisaragi)).EndInit(); this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label MainTitle; private System.Windows.Forms.Label label1; private System.Windows.Forms.Label label2; private System.Windows.Forms.Label label3; private System.Windows.Forms.Button CloseButton; private System.Windows.Forms.PictureBox gitIcon; private System.Windows.Forms.PictureBox Twitter; private System.Windows.Forms.PictureBox kisaragi; } }
38.58125
149
0.70695
[ "MIT" ]
Asteriskx/Kisaragi
Kisaragi/Views/VersionWindow.Designer.cs
6,268
C#
using System; using System.Xml.Serialization; using System.ComponentModel.DataAnnotations; using BroadWorksConnector.Ocip.Validation; using System.Collections.Generic; namespace BroadWorksConnector.Ocip.Models { /// <summary> /// Request the user level data associated with Device Policy. /// The response is either a UserDevicePoliciesGetResponse20 or an /// ErrorResponse. /// <see cref="UserDevicePoliciesGetResponse20"/> /// <see cref="ErrorResponse"/> /// </summary> [Serializable] [XmlRoot(Namespace = "")] [Groups(@"[{""__type"":""Sequence:#BroadWorksConnector.Ocip.Validation"",""id"":""ab0042aa512abc10edb3c55e4b416b0b:35696""}]")] public class UserDevicePoliciesGetRequest20 : BroadWorksConnector.Ocip.Models.C.OCIRequest { private string _userId; [XmlElement(ElementName = "userId", IsNullable = false, Namespace = "")] [Group(@"ab0042aa512abc10edb3c55e4b416b0b:35696")] [MinLength(1)] [MaxLength(161)] public string UserId { get => _userId; set { UserIdSpecified = true; _userId = value; } } [XmlIgnore] protected bool UserIdSpecified { get; set; } } }
29.159091
131
0.633671
[ "MIT" ]
JTOne123/broadworks-connector-net
BroadworksConnector/Ocip/Models/UserDevicePoliciesGetRequest20.cs
1,283
C#
namespace CovidDataLake.ContentIndexer.Indexing { public interface IRootIndexFileAccess : IRootIndexAccess { } }
18
60
0.753968
[ "Apache-2.0" ]
eran-gil/covid19-data-lake
CovidDataLake.ContentIndexer/Indexing/IRootIndexFileAccess.cs
128
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. #nullable disable using System.Collections.Specialized; using System.ComponentModel; using System.Diagnostics; using System.Drawing; using System.Net; using System.Runtime.InteropServices; using System.Windows.Forms.Layout; using static Interop; namespace System.Windows.Forms { /// <summary> /// Displays an image that can be a graphic from a bitmap, icon, or metafile, as well as from /// an enhanced metafile, JPEG, or GIF files. /// </summary> [DefaultProperty(nameof(Image))] [DefaultBindingProperty(nameof(Image))] [Docking(DockingBehavior.Ask)] [Designer("System.Windows.Forms.Design.PictureBoxDesigner, " + AssemblyRef.SystemDesign)] [SRDescription(nameof(SR.DescriptionPictureBox))] public partial class PictureBox : Control, ISupportInitialize { /// <summary> /// The type of border this control will have. /// </summary> private BorderStyle _borderStyle = BorderStyle.None; /// <summary> /// The image being displayed. /// </summary> private Image _image; /// <summary> /// Controls how the image is placed within our bounds, or how we are sized to fit said image. /// </summary> private PictureBoxSizeMode _sizeMode = PictureBoxSizeMode.Normal; private Size _savedSize; private bool _currentlyAnimating; // Instance members for asynchronous behavior private AsyncOperation _currentAsyncLoadOperation; private string _imageLocation; private Image _initialImage; private Image errorImage; private int _contentLength; private int _totalBytesRead; private MemoryStream _tempDownloadStream; private const int ReadBlockSize = 4096; private byte[] _readBuffer; private ImageInstallationType _imageInstallationType; private SendOrPostCallback _loadCompletedDelegate; private SendOrPostCallback _loadProgressDelegate; private bool _handleValid; private readonly object _internalSyncObject = new object(); // These default images will be demand loaded. private Image _defaultInitialImage; private Image _defaultErrorImage; [ThreadStatic] private static Image t_defaultInitialImageForThread; [ThreadStatic] private static Image t_defaultErrorImageForThread; private static readonly object s_loadCompletedKey = new object(); private static readonly object s_loadProgressChangedKey = new object(); private const int AsyncOperationInProgressState = 0x00000001; private const int CancellationPendingState = 0x00000002; private const int UseDefaultInitialImageState = 0x00000004; private const int UseDefaultErrorImageState = 0x00000008; private const int WaitOnLoadState = 0x00000010; private const int NeedToLoadImageLocationState = 0x00000020; private const int InInitializationState = 0x00000040; // PERF: take all the bools and put them into a state variable private BitVector32 _pictureBoxState; // see PICTUREBOXSTATE_ consts above /// <summary> /// https://docs.microsoft.com/dotnet/api/system.drawing.image.fromstream#System_Drawing_Image_FromStream_System_IO_Stream_ /// if we load an image from a stream, we must keep the stream open for the lifetime of the Image /// </summary> private StreamReader _localImageStreamReader; private Stream _uriImageStream; /// <summary> /// Creates a new picture with all default properties and no Image. The default PictureBox.SizeMode /// will be PictureBoxSizeMode.NORMAL. /// </summary> public PictureBox() { // this class overrides GetPreferredSizeCore, let Control automatically cache the result SetExtendedState(ExtendedStates.UserPreferredSizeCache, true); _pictureBoxState = new BitVector32(UseDefaultErrorImageState | UseDefaultInitialImageState); SetStyle(ControlStyles.Opaque | ControlStyles.Selectable, false); SetStyle(ControlStyles.OptimizedDoubleBuffer | ControlStyles.SupportsTransparentBackColor, true); TabStop = false; _savedSize = Size; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public override bool AllowDrop { get => base.AllowDrop; set => base.AllowDrop = value; } /// <summary> /// Indicates the border style for the control. /// </summary> [DefaultValue(BorderStyle.None)] [SRCategory(nameof(SR.CatAppearance))] [DispId((int)Ole32.DispatchID.BORDERSTYLE)] [SRDescription(nameof(SR.PictureBoxBorderStyleDescr))] public BorderStyle BorderStyle { get => _borderStyle; set { SourceGenerated.EnumValidator.Validate(value); if (_borderStyle != value) { _borderStyle = value; RecreateHandle(); AdjustSize(); } } } /// <summary> /// Try to build a URI, but if that fails, that means it's a relative path, and we treat it as /// relative to the working directory (which is what GetFullPath uses). /// </summary> private Uri CalculateUri(string path) { try { return new Uri(path); } catch (UriFormatException) { // It's a relative pathname, get its full path as a file. path = Path.GetFullPath(path); return new Uri(path); } } [SRCategory(nameof(SR.CatAsynchronous))] [SRDescription(nameof(SR.PictureBoxCancelAsyncDescr))] public void CancelAsync() { _pictureBoxState[CancellationPendingState] = true; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new bool CausesValidation { get => base.CausesValidation; set => base.CausesValidation = value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler CausesValidationChanged { add => base.CausesValidationChanged += value; remove => base.CausesValidationChanged -= value; } /// <summary> /// Returns the parameters needed to create the handle. /// </summary> protected override CreateParams CreateParams { get { CreateParams cp = base.CreateParams; switch (_borderStyle) { case BorderStyle.Fixed3D: cp.ExStyle |= (int)User32.WS_EX.CLIENTEDGE; break; case BorderStyle.FixedSingle: cp.Style |= (int)User32.WS.BORDER; break; } return cp; } } protected override ImeMode DefaultImeMode => ImeMode.Disable; /// <summary> /// Deriving classes can override this to configure a default size for their control. /// This is more efficient than setting the size in the control's constructor. /// </summary> protected override Size DefaultSize => new Size(100, 50); [SRCategory(nameof(SR.CatAsynchronous))] [Localizable(true)] [RefreshProperties(RefreshProperties.All)] [SRDescription(nameof(SR.PictureBoxErrorImageDescr))] public Image ErrorImage { get { // Strange pictureBoxState[PICTUREBOXSTATE_useDefaultErrorImage] approach used // here to avoid statically loading the default bitmaps from resources at // runtime when they're never used. if (errorImage is null && _pictureBoxState[UseDefaultErrorImageState]) { if (_defaultErrorImage is null) { // Can't share images across threads. if (t_defaultErrorImageForThread is null) { t_defaultErrorImageForThread = DpiHelper.GetBitmapFromIcon(typeof(PictureBox), "ImageInError"); } _defaultErrorImage = t_defaultErrorImageForThread; } errorImage = _defaultErrorImage; } return errorImage; } set { if (ErrorImage != value) { _pictureBoxState[UseDefaultErrorImageState] = false; } errorImage = value; } } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public override Color ForeColor { get => base.ForeColor; set => base.ForeColor = value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler ForeColorChanged { add => base.ForeColorChanged += value; remove => base.ForeColorChanged -= value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public override Font Font { get => base.Font; set => base.Font = value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler FontChanged { add => base.FontChanged += value; remove => base.FontChanged -= value; } /// <summary> /// Retrieves the Image that the <see cref='PictureBox'/> is currently displaying. /// </summary> [SRCategory(nameof(SR.CatAppearance))] [Localizable(true)] [Bindable(true)] [SRDescription(nameof(SR.PictureBoxImageDescr))] public Image Image { get => _image; set => InstallNewImage(value, ImageInstallationType.DirectlySpecified); } // The area occupied by the image [SRCategory(nameof(SR.CatAsynchronous))] [Localizable(true)] [DefaultValue(null)] [RefreshProperties(RefreshProperties.All)] [SRDescription(nameof(SR.PictureBoxImageLocationDescr))] public string ImageLocation { get => _imageLocation; set { // Reload even if value hasn't changed, since Image itself may have changed. _imageLocation = value; _pictureBoxState[NeedToLoadImageLocationState] = !string.IsNullOrEmpty(_imageLocation); // Reset main image if it hasn't been directly specified. if (string.IsNullOrEmpty(_imageLocation) && _imageInstallationType != ImageInstallationType.DirectlySpecified) { InstallNewImage(null, ImageInstallationType.DirectlySpecified); } if (WaitOnLoad && !_pictureBoxState[InInitializationState] && !string.IsNullOrEmpty(_imageLocation)) { // Load immediately, so any error will occur synchronously Load(); } Invalidate(); } } private Rectangle ImageRectangle => ImageRectangleFromSizeMode(_sizeMode); private Rectangle ImageRectangleFromSizeMode(PictureBoxSizeMode mode) { Rectangle result = LayoutUtils.DeflateRect(ClientRectangle, Padding); if (_image is not null) { switch (mode) { case PictureBoxSizeMode.Normal: case PictureBoxSizeMode.AutoSize: // Use image's size rather than client size. result.Size = _image.Size; break; case PictureBoxSizeMode.StretchImage: // Do nothing, was initialized to the available dimensions. break; case PictureBoxSizeMode.CenterImage: // Center within the available space. result.X += (result.Width - _image.Width) / 2; result.Y += (result.Height - _image.Height) / 2; result.Size = _image.Size; break; case PictureBoxSizeMode.Zoom: Size imageSize = _image.Size; float ratio = Math.Min((float)ClientRectangle.Width / (float)imageSize.Width, (float)ClientRectangle.Height / (float)imageSize.Height); result.Width = (int)(imageSize.Width * ratio); result.Height = (int)(imageSize.Height * ratio); result.X = (ClientRectangle.Width - result.Width) / 2; result.Y = (ClientRectangle.Height - result.Height) / 2; break; default: Debug.Fail("Unsupported PictureBoxSizeMode value: " + mode); break; } } return result; } [SRCategory(nameof(SR.CatAsynchronous))] [Localizable(true)] [RefreshProperties(RefreshProperties.All)] [SRDescription(nameof(SR.PictureBoxInitialImageDescr))] public Image InitialImage { get { // Strange pictureBoxState[PICTUREBOXSTATE_useDefaultInitialImage] approach // used here to avoid statically loading the default bitmaps from resources at // runtime when they're never used. if (_initialImage is null && _pictureBoxState[UseDefaultInitialImageState]) { if (_defaultInitialImage is null) { // Can't share images across threads. if (t_defaultInitialImageForThread is null) { t_defaultInitialImageForThread = DpiHelper.GetBitmapFromIcon(typeof(PictureBox), "PictureBox.Loading"); } _defaultInitialImage = t_defaultInitialImageForThread; } _initialImage = _defaultInitialImage; } return _initialImage; } set { if (InitialImage != value) { _pictureBoxState[UseDefaultInitialImageState] = false; } _initialImage = value; } } private void InstallNewImage(Image value, ImageInstallationType installationType) { StopAnimate(); _image = value; LayoutTransaction.DoLayoutIf(AutoSize, this, this, PropertyNames.Image); Animate(); if (installationType != ImageInstallationType.ErrorOrInitial) { AdjustSize(); } _imageInstallationType = installationType; Invalidate(); CommonProperties.xClearPreferredSizeCache(this); } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new ImeMode ImeMode { get => base.ImeMode; set => base.ImeMode = value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler ImeModeChanged { add => base.ImeModeChanged += value; remove => base.ImeModeChanged -= value; } /// <summary> /// Synchronous load /// </summary> [SRCategory(nameof(SR.CatAsynchronous))] [SRDescription(nameof(SR.PictureBoxLoad0Descr))] public void Load() { if (string.IsNullOrEmpty(_imageLocation)) { throw new InvalidOperationException(SR.PictureBoxNoImageLocation); } // If the load and install fails, pictureBoxState[PICTUREBOXSTATE_needToLoadImageLocation] will be // false to prevent subsequent attempts. _pictureBoxState[NeedToLoadImageLocationState] = false; Image img; ImageInstallationType installType = ImageInstallationType.FromUrl; try { DisposeImageStream(); Uri uri = CalculateUri(_imageLocation); if (uri.IsFile) { _localImageStreamReader = new StreamReader(uri.LocalPath); img = Image.FromStream(_localImageStreamReader.BaseStream); } else { #pragma warning disable SYSLIB0014 // Type or member is obsolete using (WebClient wc = new WebClient()) #pragma warning restore SYSLIB0014 // Type or member is obsolete { _uriImageStream = wc.OpenRead(uri.ToString()); img = Image.FromStream(_uriImageStream); } } } catch { if (!DesignMode) { throw; } else { // In design mode, just replace with Error bitmap. img = ErrorImage; installType = ImageInstallationType.ErrorOrInitial; } } InstallNewImage(img, installType); } [SRCategory(nameof(SR.CatAsynchronous))] [SRDescription(nameof(SR.PictureBoxLoad1Descr))] public void Load(string url) { ImageLocation = url; Load(); } [SRCategory(nameof(SR.CatAsynchronous))] [SRDescription(nameof(SR.PictureBoxLoadAsync0Descr))] public void LoadAsync() { if (string.IsNullOrEmpty(_imageLocation)) { throw new InvalidOperationException(SR.PictureBoxNoImageLocation); } if (_pictureBoxState[AsyncOperationInProgressState]) { // We shouldn't throw here: just return. return; } _pictureBoxState[AsyncOperationInProgressState] = true; if ((Image is null || (_imageInstallationType == ImageInstallationType.ErrorOrInitial)) && InitialImage is not null) { InstallNewImage(InitialImage, ImageInstallationType.ErrorOrInitial); } _currentAsyncLoadOperation = AsyncOperationManager.CreateOperation(null); if (_loadCompletedDelegate is null) { _loadCompletedDelegate = new SendOrPostCallback(LoadCompletedDelegate); _loadProgressDelegate = new SendOrPostCallback(LoadProgressDelegate); _readBuffer = new byte[ReadBlockSize]; } _pictureBoxState[NeedToLoadImageLocationState] = false; _pictureBoxState[CancellationPendingState] = false; _contentLength = -1; _tempDownloadStream = new MemoryStream(); #pragma warning disable SYSLIB0014 // Type or member is obsolete WebRequest req = WebRequest.Create(CalculateUri(_imageLocation)); #pragma warning restore SYSLIB0014 // Type or member is obsolete Task.Run(() => { // Invoke BeginGetResponse on a threadpool thread, as it has unpredictable latency req.BeginGetResponse(new AsyncCallback(GetResponseCallback), req); }); } private void PostCompleted(Exception error, bool cancelled) { AsyncOperation temp = _currentAsyncLoadOperation; _currentAsyncLoadOperation = null; if (temp is not null) { temp.PostOperationCompleted(_loadCompletedDelegate, new AsyncCompletedEventArgs(error, cancelled, null)); } } private void LoadCompletedDelegate(object arg) { AsyncCompletedEventArgs e = (AsyncCompletedEventArgs)arg; Image img = ErrorImage; ImageInstallationType installType = ImageInstallationType.ErrorOrInitial; if (!e.Cancelled && e.Error is null) { // successful completion try { img = Image.FromStream(_tempDownloadStream); installType = ImageInstallationType.FromUrl; } catch (Exception error) { e = new AsyncCompletedEventArgs(error, false, null); } } // If cancelled, don't change the image if (!e.Cancelled) { InstallNewImage(img, installType); } _tempDownloadStream = null; _pictureBoxState[CancellationPendingState] = false; _pictureBoxState[AsyncOperationInProgressState] = false; OnLoadCompleted(e); } private void LoadProgressDelegate(object arg) => OnLoadProgressChanged((ProgressChangedEventArgs)arg); private void GetResponseCallback(IAsyncResult result) { if (_pictureBoxState[CancellationPendingState]) { PostCompleted(null, true); return; } try { WebRequest req = (WebRequest)result.AsyncState; WebResponse webResponse = req.EndGetResponse(result); _contentLength = (int)webResponse.ContentLength; _totalBytesRead = 0; Stream responseStream = webResponse.GetResponseStream(); // Continue on with asynchronous reading. responseStream.BeginRead( _readBuffer, 0, ReadBlockSize, new AsyncCallback(ReadCallBack), responseStream); } catch (Exception error) { // Since this is on a non-UI thread, we catch any exceptions and // pass them back as data to the UI-thread. PostCompleted(error, false); } } private void ReadCallBack(IAsyncResult result) { if (_pictureBoxState[CancellationPendingState]) { PostCompleted(null, true); return; } Stream responseStream = (Stream)result.AsyncState; try { int bytesRead = responseStream.EndRead(result); if (bytesRead > 0) { _totalBytesRead += bytesRead; _tempDownloadStream.Write(_readBuffer, 0, bytesRead); responseStream.BeginRead( _readBuffer, 0, ReadBlockSize, new AsyncCallback(ReadCallBack), responseStream); // Report progress thus far, but only if we know total length. if (_contentLength != -1) { int progress = (int)(100 * (((float)_totalBytesRead) / ((float)_contentLength))); if (_currentAsyncLoadOperation is not null) { _currentAsyncLoadOperation.Post(_loadProgressDelegate, new ProgressChangedEventArgs(progress, null)); } } } else { _tempDownloadStream.Seek(0, SeekOrigin.Begin); if (_currentAsyncLoadOperation is not null) { _currentAsyncLoadOperation.Post(_loadProgressDelegate, new ProgressChangedEventArgs(100, null)); } PostCompleted(null, false); // Do this so any exception that Close() throws will be // dealt with ok. Stream rs = responseStream; responseStream = null; rs.Close(); } } catch (Exception error) { // Since this is on a non-UI thread, we catch any exceptions and // pass them back as data to the UI-thread. PostCompleted(error, false); responseStream?.Close(); } } [SRCategory(nameof(SR.CatAsynchronous))] [SRDescription(nameof(SR.PictureBoxLoadAsync1Descr))] public void LoadAsync(string url) { ImageLocation = url; LoadAsync(); } [SRCategory(nameof(SR.CatAsynchronous))] [SRDescription(nameof(SR.PictureBoxLoadCompletedDescr))] public event AsyncCompletedEventHandler LoadCompleted { add => Events.AddHandler(s_loadCompletedKey, value); remove => Events.RemoveHandler(s_loadCompletedKey, value); } [SRCategory(nameof(SR.CatAsynchronous))] [SRDescription(nameof(SR.PictureBoxLoadProgressChangedDescr))] public event ProgressChangedEventHandler LoadProgressChanged { add => Events.AddHandler(s_loadProgressChangedKey, value); remove => Events.RemoveHandler(s_loadProgressChangedKey, value); } private void ResetInitialImage() { _pictureBoxState[UseDefaultInitialImageState] = true; _initialImage = _defaultInitialImage; } private void ResetErrorImage() { _pictureBoxState[UseDefaultErrorImageState] = true; errorImage = _defaultErrorImage; } private void ResetImage() { InstallNewImage(null, ImageInstallationType.DirectlySpecified); } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public override RightToLeft RightToLeft { get => base.RightToLeft; set => base.RightToLeft = value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler RightToLeftChanged { add => base.RightToLeftChanged += value; remove => base.RightToLeftChanged -= value; } /// <summary> /// Be sure not to re-serialized initial image if it's the default. /// </summary> private bool ShouldSerializeInitialImage() { return !_pictureBoxState[UseDefaultInitialImageState]; } /// <summary> /// Be sure not to re-serialized error image if it's the default. /// </summary> private bool ShouldSerializeErrorImage() { return !_pictureBoxState[UseDefaultErrorImageState]; } /// <summary> /// Be sure not to serialize image if it wasn't directly specified /// through the Image property (e.g., if it's a download, or an initial /// or error image) /// </summary> private bool ShouldSerializeImage() { return (_imageInstallationType == ImageInstallationType.DirectlySpecified) && (Image is not null); } /// <summary> /// Indicates how the image is displayed. /// </summary> [DefaultValue(PictureBoxSizeMode.Normal)] [SRCategory(nameof(SR.CatBehavior))] [Localizable(true)] [SRDescription(nameof(SR.PictureBoxSizeModeDescr))] [RefreshProperties(RefreshProperties.Repaint)] public PictureBoxSizeMode SizeMode { get => _sizeMode; set { SourceGenerated.EnumValidator.Validate(value); if (_sizeMode != value) { if (value == PictureBoxSizeMode.AutoSize) { AutoSize = true; SetStyle(ControlStyles.FixedHeight | ControlStyles.FixedWidth, true); } if (value != PictureBoxSizeMode.AutoSize) { AutoSize = false; SetStyle(ControlStyles.FixedHeight | ControlStyles.FixedWidth, false); _savedSize = Size; } _sizeMode = value; AdjustSize(); Invalidate(); OnSizeModeChanged(EventArgs.Empty); } } } private static readonly object EVENT_SIZEMODECHANGED = new object(); [SRCategory(nameof(SR.CatPropertyChanged))] [SRDescription(nameof(SR.PictureBoxOnSizeModeChangedDescr))] public event EventHandler SizeModeChanged { add => Events.AddHandler(EVENT_SIZEMODECHANGED, value); remove => Events.RemoveHandler(EVENT_SIZEMODECHANGED, value); } internal override bool SupportsUiaProviders => true; [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new bool TabStop { get => base.TabStop; set => base.TabStop = value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler TabStopChanged { add => base.TabStopChanged += value; remove => base.TabStopChanged -= value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new int TabIndex { get => base.TabIndex; set => base.TabIndex = value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler TabIndexChanged { add => base.TabIndexChanged += value; remove => base.TabIndexChanged -= value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] [Bindable(false)] public override string Text { get => base.Text; set => base.Text = value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler TextChanged { add => base.TextChanged += value; remove => base.TextChanged -= value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler Enter { add => base.Enter += value; remove => base.Enter -= value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event KeyEventHandler KeyUp { add => base.KeyUp += value; remove => base.KeyUp -= value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event KeyEventHandler KeyDown { add => base.KeyDown += value; remove => base.KeyDown -= value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event KeyPressEventHandler KeyPress { add => base.KeyPress += value; remove => base.KeyPress -= value; } [Browsable(false)] [EditorBrowsable(EditorBrowsableState.Never)] public new event EventHandler Leave { add => base.Leave += value; remove => base.Leave -= value; } /// <summary> /// If the PictureBox has the SizeMode property set to AutoSize, this makes sure that the /// picturebox is large enough to hold the image. /// </summary> private void AdjustSize() { if (_sizeMode == PictureBoxSizeMode.AutoSize) { Size = PreferredSize; } else { Size = _savedSize; } } private void Animate() => Animate(animate: !DesignMode && Visible && Enabled && ParentInternal is not null); private void StopAnimate() => Animate(animate: false); private void Animate(bool animate) { if (animate != _currentlyAnimating) { if (animate) { if (_image is not null) { ImageAnimator.Animate(_image, new EventHandler(OnFrameChanged)); _currentlyAnimating = animate; } } else { if (_image is not null) { ImageAnimator.StopAnimate(_image, new EventHandler(OnFrameChanged)); _currentlyAnimating = animate; } } } } protected override AccessibleObject CreateAccessibilityInstance() => new PictureBoxAccessibleObject(this); protected override void Dispose(bool disposing) { if (disposing) { StopAnimate(); } DisposeImageStream(); base.Dispose(disposing); } private void DisposeImageStream() { if (_localImageStreamReader is not null) { _localImageStreamReader.Dispose(); _localImageStreamReader = null; } if (_uriImageStream is not null) { _uriImageStream.Dispose(); _localImageStreamReader = null; } } /// <summary> /// Overriding this method allows us to get the caching and clamping the proposedSize/output to /// MinimumSize / MaximumSize from GetPreferredSize for free. /// </summary> internal override Size GetPreferredSizeCore(Size proposedSize) { if (_image is null) { return CommonProperties.GetSpecifiedBounds(this).Size; } else { Size bordersAndPadding = SizeFromClientSize(Size.Empty) + Padding.Size; return _image.Size + bordersAndPadding; } } protected override void OnEnabledChanged(EventArgs e) { base.OnEnabledChanged(e); Animate(); } private void OnFrameChanged(object o, EventArgs e) { if (Disposing || IsDisposed) { return; } // Handle should be created, before calling the BeginInvoke. if (InvokeRequired && IsHandleCreated) { lock (_internalSyncObject) { if (_handleValid) { BeginInvoke(new EventHandler(OnFrameChanged), o, e); } return; } } Invalidate(); } [EditorBrowsable(EditorBrowsableState.Advanced)] protected override void OnHandleDestroyed(EventArgs e) { lock (_internalSyncObject) { _handleValid = false; } base.OnHandleDestroyed(e); } [EditorBrowsable(EditorBrowsableState.Advanced)] protected override void OnHandleCreated(EventArgs e) { lock (_internalSyncObject) { _handleValid = true; } base.OnHandleCreated(e); } protected virtual void OnLoadCompleted(AsyncCompletedEventArgs e) { ((AsyncCompletedEventHandler)(Events[s_loadCompletedKey]))?.Invoke(this, e); } protected virtual void OnLoadProgressChanged(ProgressChangedEventArgs e) { ((ProgressChangedEventHandler)(Events[s_loadProgressChangedKey]))?.Invoke(this, e); } /// <summary> /// Overridden onPaint to make sure that the image is painted correctly. /// </summary> protected override void OnPaint(PaintEventArgs pe) { if (_pictureBoxState[NeedToLoadImageLocationState]) { try { if (WaitOnLoad) { Load(); } else { LoadAsync(); } } catch (Exception ex) when (!ClientUtils.IsCriticalException(ex)) { _image = ErrorImage; } } if (_image is not null && pe is not null) { Animate(); ImageAnimator.UpdateFrames(Image); // Error and initial image are drawn centered, non-stretched. Rectangle drawingRect = (_imageInstallationType == ImageInstallationType.ErrorOrInitial) ? ImageRectangleFromSizeMode(PictureBoxSizeMode.CenterImage) : ImageRectangle; pe.Graphics.DrawImage(_image, drawingRect); } // Windows draws the border for us (see CreateParams) base.OnPaint(pe); } protected override void OnVisibleChanged(EventArgs e) { base.OnVisibleChanged(e); Animate(); } protected override void OnParentChanged(EventArgs e) { base.OnParentChanged(e); Animate(); } /// <summary> /// OnResize override to invalidate entire control in Stetch mode /// </summary> protected override void OnResize(EventArgs e) { base.OnResize(e); if (_sizeMode == PictureBoxSizeMode.Zoom || _sizeMode == PictureBoxSizeMode.StretchImage || _sizeMode == PictureBoxSizeMode.CenterImage || BackgroundImage is not null) { Invalidate(); } _savedSize = Size; } protected virtual void OnSizeModeChanged(EventArgs e) { if (Events[EVENT_SIZEMODECHANGED] is EventHandler eh) { eh(this, e); } } /// <summary> /// Returns a string representation for this control. /// </summary> public override string ToString() { string s = base.ToString(); return s + ", SizeMode: " + _sizeMode.ToString("G"); } [SRCategory(nameof(SR.CatAsynchronous))] [Localizable(true)] [DefaultValue(false)] [SRDescription(nameof(SR.PictureBoxWaitOnLoadDescr))] public bool WaitOnLoad { get => _pictureBoxState[WaitOnLoadState]; set => _pictureBoxState[WaitOnLoadState] = value; } void ISupportInitialize.BeginInit() { _pictureBoxState[InInitializationState] = true; } void ISupportInitialize.EndInit() { if (!_pictureBoxState[InInitializationState]) { return; } // Need to do this in EndInit since there's no guarantee of the // order in which ImageLocation and WaitOnLoad will be set. if (ImageLocation is not null && ImageLocation.Length != 0 && WaitOnLoad) { // Load when initialization completes, so any error will occur synchronously Load(); } _pictureBoxState[InInitializationState] = false; } } }
34.154424
179
0.543759
[ "MIT" ]
AraHaan/winforms
src/System.Windows.Forms/src/System/Windows/Forms/PictureBox.cs
40,919
C#
namespace MobileBgWebScraper.App { using System; using System.Globalization; using MobileBgWebScraper.Services; public static class TechnicalCharacteristicsParsers { public static void ParseManufacturingDate(string input, AdvertisementInputModel advertisement) { if (input == null) { return; } string rawDateInput = input.Replace("г.", string.Empty); string[] rawDateInputArgs = rawDateInput.Split(" "); int month = DateTime.ParseExact(rawDateInputArgs[0], "MMMM", new CultureInfo("bg-BG")).Month; int year = int.Parse(rawDateInputArgs[1]); advertisement.ManufacturingDate = new DateTime(year, month, 1); } public static void ParseKilometrage(string input, AdvertisementInputModel advertisement) { if (input == null) { return; } int kilometrage = int.Parse(input .Replace(" ", string.Empty) .ToLower() .Replace("км", string.Empty)); advertisement.Kilometrage = kilometrage; } public static void ParseHorsePowers(string input, AdvertisementInputModel advertisement) { if (input == null) { return; } int horsePowers = int.Parse(input .Replace(" ", string.Empty) .ToLower() .Replace("к.с.", string.Empty)); advertisement.HorsePowers = horsePowers; } public static void ParseEngineType(string input, AdvertisementInputModel advertisement) { advertisement.EngineType = input?.Trim(); } public static void ParseTransmissionType(string input, AdvertisementInputModel advertisement) { advertisement.TransmissionType = input?.Trim(); } public static void ParseBodyStyle(string input, AdvertisementInputModel advertisement) { advertisement.BodyStyle = input?.Trim(); } public static void ParseColorName(string input, AdvertisementInputModel advertisement) { advertisement.ColorName = input?.Trim(); } public static void ParseEuroStandard(string input, AdvertisementInputModel advertisement) { advertisement.EuroStandard = input?.Trim(); } } }
32.109756
105
0.549943
[ "MIT" ]
georgy-kirilov/MobileBgWebScraper
MobileBgWebScraper/MobileBgWebScraper.App/TechnicalCharacteristicsParsers.cs
2,640
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("DeclareVar")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DeclareVar")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("e9267b54-a5fc-4b2e-bc05-66ee930ae81c")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.648649
84
0.744436
[ "MIT" ]
kaizer04/Telerik-Academy-2013-2014
C#1/Data-Types-Variables-Homework/DeclareVar/Properties/AssemblyInfo.cs
1,396
C#
/* * Copyright(c) 2019 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System.ComponentModel; using System.Runtime.InteropServices; using Tizen.NUI.BaseComponents; namespace Tizen.NUI { /// <summary> /// Touch events are a collection of points at a specific moment in time.<br /> /// When a multi-touch event occurs, each point represents the points that are currently being /// touched or the points where a touch has stopped.<br /> /// </summary> /// <since_tizen> 3 </since_tizen> public class Touch : BaseHandle { /// <summary> /// An uninitialized touch instance.<br /> /// Calling member functions with an uninitialized touch handle is not allowed.<br /> /// </summary> /// <since_tizen> 3 </since_tizen> public Touch() : this(Interop.Touch.NewTouch(), true) { if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal Touch(Touch other) : this(Interop.Touch.NewTouch(Touch.getCPtr(other)), true) { if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } internal Touch(global::System.IntPtr cPtr, bool cMemoryOwn) : base(Interop.Touch.Upcast(cPtr), cMemoryOwn) { } /// <summary> /// Returns the time (in ms) that the touch event occurred. /// </summary> /// <returns>The time (in ms) that the touch event occurred.</returns> /// <since_tizen> 3 </since_tizen> public uint GetTime() { uint ret = Interop.Touch.GetTime(SwigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Returns the total number of points in this TouchData. /// </summary> /// <returns>The total number of points.</returns> /// <since_tizen> 3 </since_tizen> public uint GetPointCount() { uint ret = Interop.Touch.GetPointCount(SwigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Returns the ID of the device used for the point specified.<br /> /// Each point has a unique device ID, which specifies the device used for that /// point. This is returned by this method.<br /> /// If a point is greater than GetPointCount(), then this method will return -1.<br /> /// </summary> /// <param name="point">The point required.</param> /// <returns>The device ID of this point.</returns> /// <since_tizen> 3 </since_tizen> public int GetDeviceId(uint point) { int ret = Interop.Touch.GetDeviceId(SwigCPtr, point); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Retrieves the state of the point specified.<br /> /// If a point is greater than GetPointCount(), then this method will return PointState.Finished.<br /> /// </summary> /// <param name="point">The point required.</param> /// <returns>The state of the point specified.</returns> /// <since_tizen> 3 </since_tizen> public PointStateType GetState(uint point) { PointStateType ret = (PointStateType)Interop.Touch.GetState(SwigCPtr, point); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Retrieves the actor that was underneath the point specified.<br /> /// If a point is greater than GetPointCount(), then this method will return an empty handle.<br /> /// </summary> /// <param name="point">The point required.</param> /// <returns>The actor that was underneath the point specified.</returns> /// <since_tizen> 3 </since_tizen> public View GetHitView(uint point) { //to fix memory leak issue, match the handle count with native side. global::System.IntPtr cPtr = Interop.Touch.GetHitActor(SwigCPtr, point); View ret = this.GetInstanceSafely<View>(cPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Retrieves the coordinates relative to the top-left of the hit actor at the point specified.<br /> /// The top-left of an actor is (0.0, 0.0, 0.5).<br /> /// If you require the local coordinates of another actor (for example, the parent of the hit actor), /// then you should use Actor::ScreenToLocal().<br /> /// If a point is greater than GetPointCount(), then this method will return Vector2.Zero.<br /> /// </summary> /// <param name="point">The point required.</param> /// <returns>The coordinates relative to the top-left of the hit actor of the point specified.</returns> /// <since_tizen> 3 </since_tizen> public Vector2 GetLocalPosition(uint point) { Vector2 ret = new Vector2(Interop.Touch.GetLocalPosition(SwigCPtr, point), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Retrieves the coordinates relative to the top-left of the screen of the point specified.<br /> /// If a point is greater than GetPointCount(), then this method will return Vector2.Zero.<br /> /// </summary> /// <param name="point">The point required.</param> /// <returns>The coordinates relative to the top-left of the screen of the point specified.</returns> /// <since_tizen> 3 </since_tizen> public Vector2 GetScreenPosition(uint point) { Vector2 ret = new Vector2(Interop.Touch.GetScreenPosition(SwigCPtr, point), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Retrieves the radius of the press point.<br /> /// This is the average of both the horizontal and vertical radii of the press point.<br /> /// If point is greater than GetPointCount(), then this method will return 0.0f.<br /> /// </summary> /// <param name="point">The point required.</param> /// <returns>The radius of the press point.</returns> /// <since_tizen> 3 </since_tizen> public float GetRadius(uint point) { float ret = Interop.Touch.GetRadius(SwigCPtr, point); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Retrieves both the horizontal and the vertical radii of the press point.<br /> /// If a point is greater than GetPointCount(), then this method will return Vector2.Zero.<br /> /// </summary> /// <param name="point">The point required.</param> /// <returns>The horizontal and vertical radii of the press point.</returns> /// <since_tizen> 3 </since_tizen> public Vector2 GetEllipseRadius(uint point) { Vector2 ret = new Vector2(Interop.Touch.GetEllipseRadius(SwigCPtr, point), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Retrieves the touch pressure.<br /> /// The pressure range starts at 0.0f.<br /> /// Normal pressure is defined as 1.0f.<br /> /// A value between 0.0f and 1.0f means light pressure has been applied.<br /> /// A value greater than 1.0f means more pressure than normal has been applied.<br /> /// If point is greater than GetPointCount(), then this method will return 1.0f.<br /> /// </summary> /// <param name="point">The point required.</param> /// <returns>The touch pressure.</returns> /// <since_tizen> 3 </since_tizen> public float GetPressure(uint point) { float ret = Interop.Touch.GetPressure(SwigCPtr, point); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Get mouse device's button value (for example, right or left button) /// </summary> /// <param name="point">The point required.</param> /// <returns></returns> /// <since_tizen> 5 </since_tizen> /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public MouseButton GetMouseButton(uint point) { int ret = Interop.Touch.GetMouseButton(SwigCPtr, point); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return (MouseButton)ret; } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(Touch obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.SwigCPtr; } internal static Touch GetTouchFromPtr(global::System.IntPtr cPtr) { Touch ret = Registry.GetManagedBaseHandleFromNativePtr(cPtr) as Touch; if (ret == null) { ret = new Touch(cPtr, false); } if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// This will be public opened in tizen_next after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Degree GetAngle(uint point) { Degree ret = new Degree(Interop.Touch.GetAngle(SwigCPtr, point), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// This will not be public opened. [EditorBrowsable(EditorBrowsableState.Never)] protected override void ReleaseSwigCPtr(System.Runtime.InteropServices.HandleRef swigCPtr) { Interop.Touch.DeleteTouch(swigCPtr); } } /// <summary> /// Mouse device button type. /// </summary> /// <since_tizen> 5 </since_tizen> /// This will be public opened in tizen_5.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public enum MouseButton { /// <summary> /// No mouse button event or invalid data. /// </summary> /// <since_tizen> 5 </since_tizen> Invalid = -1, /// <summary> /// Primary(Left) mouse button. /// </summary> /// <since_tizen> 5 </since_tizen> Primary = 1, /// <summary> /// Secondary(Right) mouse button. /// </summary> /// <since_tizen> 5 </since_tizen> Secondary = 3, /// <summary> /// Center(Wheel) mouse button. /// </summary> /// <since_tizen> 5 </since_tizen> Tertiary = 2, } }
44.340502
137
0.621858
[ "Apache-2.0", "MIT" ]
bshsqa/TizenFX
src/Tizen.NUI/src/public/Touch.cs
12,371
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("DrawFortSecondLeg")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("DrawFortSecondLeg")] [assembly: AssemblyCopyright("Copyright © 2016")] [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("aa877618-77e3-4441-89ec-8b16a7a1b8e1")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.027027
84
0.746979
[ "MIT" ]
pkindalov/beginner_exercises
OldBasicsExams/OldExams/DrawFortSecondLeg/Properties/AssemblyInfo.cs
1,410
C#
using System.Reflection; namespace FubuMVC.Core.Diagnostics.Querying { public class AssemblyToken { public AssemblyToken() { } public AssemblyToken(Assembly assembly) { var assemblyName = assembly.GetName(); Name = assemblyName.Name; Version = assemblyName.Version.ToString(); FullName = assemblyName.FullName; } public string Name { get; set;} public string Version { get; set;} public string FullName { get; set;} public bool Equals(AssemblyToken other) { if (ReferenceEquals(null, other)) return false; if (ReferenceEquals(this, other)) return true; return Equals(other.Name, Name) && Equals(other.Version, Version) && Equals(other.FullName, FullName); } public override bool Equals(object obj) { if (ReferenceEquals(null, obj)) return false; if (ReferenceEquals(this, obj)) return true; if (obj.GetType() != typeof (AssemblyToken)) return false; return Equals((AssemblyToken) obj); } public override int GetHashCode() { unchecked { int result = (Name != null ? Name.GetHashCode() : 0); result = (result*397) ^ (Version != null ? Version.GetHashCode() : 0); result = (result*397) ^ (FullName != null ? FullName.GetHashCode() : 0); return result; } } } }
32.632653
115
0.533458
[ "Apache-2.0" ]
uluhonolulu/fubumvc
src/FubuMVC.Core/Diagnostics/Querying/AssemblyToken.cs
1,601
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: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Szkolniak.Core")] [assembly: AssemblyTrademark("")] // 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("0fa75a5b-ab83-4fd0-b545-279774c01e87")]
41.315789
84
0.77707
[ "MIT" ]
dominikdysput/SzkolniakApp
aspnet-core/src/Szkolniak.Core/Properties/AssemblyInfo.cs
787
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using System.Collections.Generic; using System.Reflection; using Microsoft.VisualStudio.TestPlatform.Common.ExtensionFramework.Utilities; using Microsoft.VisualStudio.TestPlatform.Common.Telemetry; using Microsoft.VisualStudio.TestTools.UnitTesting; using FluentAssertions; #nullable disable namespace TestPlatform.Common.UnitTests.ExtensionFramework.Utilities; [TestClass] public class TestExtensionsTests { private TestExtensions _testExtensions; [TestInitialize] public void TestInit() { _testExtensions = new TestExtensions(); } [TestMethod] public void AddExtensionsShouldNotThrowIfExtensionsIsNull() { _testExtensions.AddExtension<TestPluginInformation>(null); // Validate that the default state does not change. Assert.IsNull(_testExtensions.TestDiscoverers); } [TestMethod] public void AddExtensionsShouldNotThrowIfExistingExtensionCollectionIsNull() { var testDiscoverers = new Dictionary<string, TestDiscovererPluginInformation> { { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } }; _testExtensions.AddExtension(testDiscoverers); Assert.IsNotNull(_testExtensions.TestDiscoverers); CollectionAssert.AreEqual(_testExtensions.TestDiscoverers, testDiscoverers); // Validate that the others remain same. Assert.IsNull(_testExtensions.TestExecutors); Assert.IsNull(_testExtensions.TestSettingsProviders); Assert.IsNull(_testExtensions.TestLoggers); } [TestMethod] public void AddExtensionsShouldAddToExistingExtensionCollection() { var testDiscoverers = new Dictionary<string, TestDiscovererPluginInformation> { { "td1", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) }, { "td2", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } }; _testExtensions.TestDiscoverers = new Dictionary<string, TestDiscovererPluginInformation> { { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } }; // Act. _testExtensions.AddExtension(testDiscoverers); // Validate. var expectedTestExtensions = new Dictionary<string, TestDiscovererPluginInformation> { { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) }, { "td1", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) }, { "td2", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } }; CollectionAssert.AreEqual(_testExtensions.TestDiscoverers.Keys, expectedTestExtensions.Keys); // Validate that the others remain same. Assert.IsNull(_testExtensions.TestExecutors); Assert.IsNull(_testExtensions.TestSettingsProviders); Assert.IsNull(_testExtensions.TestLoggers); } [TestMethod] public void AddExtensionsShouldNotAddAnAlreadyExistingExtensionToTheCollection() { var testDiscoverers = new Dictionary<string, TestDiscovererPluginInformation> { { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } }; _testExtensions.TestDiscoverers = new Dictionary<string, TestDiscovererPluginInformation> { { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } }; // Act. _testExtensions.AddExtension(testDiscoverers); // Validate. CollectionAssert.AreEqual(_testExtensions.TestDiscoverers.Keys, testDiscoverers.Keys); // Validate that the others remain same. Assert.IsNull(_testExtensions.TestExecutors); Assert.IsNull(_testExtensions.TestSettingsProviders); Assert.IsNull(_testExtensions.TestLoggers); } [TestMethod] public void GetExtensionsDiscoveredFromAssemblyShouldReturnNullIfNoExtensionsPresent() { var assemblyLocation = typeof(TestExtensionsTests).GetTypeInfo().Assembly.Location; Assert.IsNull(_testExtensions.GetExtensionsDiscoveredFromAssembly(assemblyLocation)); } [TestMethod] public void GetExtensionsDiscoveredFromAssemblyShouldNotThrowIfExtensionAssemblyIsNull() { _testExtensions.TestDiscoverers = new Dictionary<string, TestDiscovererPluginInformation> { { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } }; Assert.IsNull(_testExtensions.GetExtensionsDiscoveredFromAssembly(null)); } [TestMethod] public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestDiscoverers() { var assemblyLocation = typeof(TestExtensionsTests).GetTypeInfo().Assembly.Location; _testExtensions.TestDiscoverers = new Dictionary<string, TestDiscovererPluginInformation> { { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) }, { "td1", new TestDiscovererPluginInformation(typeof(TestExtensions)) } }; var extensions = _testExtensions.GetExtensionsDiscoveredFromAssembly(assemblyLocation); var expectedExtensions = new Dictionary<string, TestDiscovererPluginInformation> { { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } }; CollectionAssert.AreEqual(expectedExtensions.Keys, extensions.TestDiscoverers.Keys); } [TestMethod] public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestExecutors() { var assemblyLocation = typeof(TestExtensionsTests).GetTypeInfo().Assembly.Location; _testExtensions.TestExecutors = new Dictionary<string, TestExecutorPluginInformation> { { "te", new TestExecutorPluginInformation(typeof(TestExtensionsTests)) }, { "te1", new TestExecutorPluginInformation(typeof(TestExtensions)) } }; var extensions = _testExtensions.GetExtensionsDiscoveredFromAssembly(assemblyLocation); var expectedExtensions = new Dictionary<string, TestExecutorPluginInformation> { { "te", new TestExecutorPluginInformation(typeof(TestExtensionsTests)) } }; CollectionAssert.AreEqual(expectedExtensions.Keys, extensions.TestExecutors.Keys); } [TestMethod] public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestSettingsProviders() { var assemblyLocation = typeof(TestExtensionsTests).GetTypeInfo().Assembly.Location; _testExtensions.TestSettingsProviders = new Dictionary<string, TestSettingsProviderPluginInformation> { { "tsp", new TestSettingsProviderPluginInformation(typeof(TestExtensionsTests)) }, { "tsp1", new TestSettingsProviderPluginInformation(typeof(TestExtensions)) } }; var extensions = _testExtensions.GetExtensionsDiscoveredFromAssembly(assemblyLocation); var expectedExtensions = new Dictionary<string, TestSettingsProviderPluginInformation> { { "tsp", new TestSettingsProviderPluginInformation(typeof(TestExtensionsTests)) } }; CollectionAssert.AreEqual(expectedExtensions.Keys, extensions.TestSettingsProviders.Keys); } [TestMethod] public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestLoggers() { var assemblyLocation = typeof(TestExtensionsTests).GetTypeInfo().Assembly.Location; _testExtensions.TestLoggers = new Dictionary<string, TestLoggerPluginInformation> { { "tl", new TestLoggerPluginInformation(typeof(TestExtensionsTests)) }, { "tl1", new TestLoggerPluginInformation(typeof(TestExtensions)) } }; var extensions = _testExtensions.GetExtensionsDiscoveredFromAssembly(assemblyLocation); var expectedExtensions = new Dictionary<string, TestLoggerPluginInformation> { { "tl", new TestLoggerPluginInformation(typeof(TestExtensionsTests)) } }; CollectionAssert.AreEqual(expectedExtensions.Keys, extensions.TestLoggers.Keys); } [TestMethod] public void GetExtensionsDiscoveredFromAssemblyShouldReturnTestDiscoveresAndLoggers() { var assemblyLocation = typeof(TestExtensionsTests).GetTypeInfo().Assembly.Location; _testExtensions.TestDiscoverers = new Dictionary<string, TestDiscovererPluginInformation> { { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } }; _testExtensions.TestLoggers = new Dictionary<string, TestLoggerPluginInformation> { { "tl", new TestLoggerPluginInformation(typeof(TestExtensionsTests)) } }; var extensions = _testExtensions.GetExtensionsDiscoveredFromAssembly(assemblyLocation); var expectedDiscoverers = new Dictionary<string, TestDiscovererPluginInformation> { { "td", new TestDiscovererPluginInformation(typeof(TestExtensionsTests)) } }; CollectionAssert.AreEqual(expectedDiscoverers.Keys, extensions.TestDiscoverers.Keys); var expectedLoggers = new Dictionary<string, TestLoggerPluginInformation> { { "tl", new TestLoggerPluginInformation(typeof(TestExtensionsTests)) } }; CollectionAssert.AreEqual(expectedLoggers.Keys, extensions.TestLoggers.Keys); } [TestMethod] public void MergedDictionaryOfEmptyDictionariesShouldBeAnEmptyDictionary() { var first = new Dictionary<string, HashSet<string>>(); var second = new Dictionary<string, HashSet<string>>(); var merged = TestExtensions.CreateMergedDictionary(first, second); // Merging two empty dictionaries should result in an empty dictionary. merged.Should().HaveCount(0); // Make sure the method is "pure" and returns a new reference. merged.Should().NotBeSameAs(first); merged.Should().NotBeSameAs(second); } [TestMethod] public void MergedDictionaryOfOneEmptyAndOneNonEmptyDictionaryShouldContainAllTheItemsOfTheNonEmptyDictionary() { var first = new Dictionary<string, HashSet<string>>(); var second = new Dictionary<string, HashSet<string>> { { "aaa", new HashSet<string>() } }; var merged1 = TestExtensions.CreateMergedDictionary(first, second); var merged2 = TestExtensions.CreateMergedDictionary(second, first); // Merging one empty dictionary with a not empty one should result in a not empty // dictionary. merged1.Should().HaveCount(1); merged2.Should().HaveCount(1); merged1.Should().ContainKey("aaa"); merged2.Should().ContainKey("aaa"); // Make sure the method stays "pure" and returns a new reference regardless of the input. merged1.Should().NotBeSameAs(first); merged1.Should().NotBeSameAs(second); merged2.Should().NotBeSameAs(first); merged2.Should().NotBeSameAs(second); merged1.Should().NotBeSameAs(merged2); } [TestMethod] public void MergedDictionaryShouldBeEquivalentToTheExpectedDictionary() { var first = new Dictionary<string, HashSet<string>> { // Merged with "key1" from the next set. { "key1", new HashSet<string>(new List<string>() { "ext1", "ext2", "ext3" }) }, // Empty hashset, will be removed from the result. { "key2", new HashSet<string>() }, // Added as is. { "key5", new HashSet<string>(new List<string>() { "ext1", "ext2" }) } }; var second = new Dictionary<string, HashSet<string>> { // Merged with "key1" from the previous set. { "key1", new HashSet<string>(new List<string>() { "ext2", "ext3", "ext3", "ext4", "ext5" }) }, // Empty hashset, will be removed from the result. { "key2", new HashSet<string>() }, // Empty hashset, will be removed from the result. { "key3", new HashSet<string>() }, // Added as is. { "key4", new HashSet<string>(new List<string>() { "ext1" }) } }; var expected = new Dictionary<string, HashSet<string>> { { "key1", new HashSet<string>(new List<string>() { "ext1", "ext2", "ext3", "ext4", "ext5" }) }, { "key4", new HashSet<string>(new List<string>() { "ext1" }) }, { "key5", new HashSet<string>(new List<string>() { "ext1", "ext2" }) } }; // Merge the two dictionaries. var merged = TestExtensions.CreateMergedDictionary(first, second); // Make sure the merged dictionary has the exact same keys as the expected dictionary. merged.Should().HaveCount(expected.Count); merged.Should().ContainKeys(expected.Keys); expected.Should().ContainKeys(merged.Keys); // Make sure the hashsets for each key are equal. merged.Values.Should().BeEquivalentTo(expected.Values); } [TestMethod] public void AddExtensionTelemetryShouldAddJsonFormattedDiscoveredExtensionsTelemetry() { var telemetryData = new Dictionary<string, object>(); var extensions = new Dictionary<string, HashSet<string>> { { "key1", new HashSet<string>(new List<string>() { "ext1", "ext2", "ext3", "ext4", "ext5" }) }, { "key4", new HashSet<string>(new List<string>() { "ext1" }) }, { "key5", new HashSet<string>(new List<string>() { "ext1", "ext2" }) } }; var expectedTelemetry = @"{""key1"":[""ext1"",""ext2"",""ext3"",""ext4"",""ext5""]," + @"""key4"":[""ext1""]," + @"""key5"":[""ext1"",""ext2""]}"; TestExtensions.AddExtensionTelemetry(telemetryData, extensions); telemetryData.Should().ContainKey(TelemetryDataConstants.DiscoveredExtensions); telemetryData[TelemetryDataConstants.DiscoveredExtensions].Should().BeEquivalentTo(expectedTelemetry); } }
40.534091
115
0.681385
[ "MIT" ]
Microsoft/vstest
test/Microsoft.TestPlatform.Common.UnitTests/ExtensionFramework/Utilities/TestExtensionsTests.cs
14,268
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Threading.Tasks; public class ConsoleWriterEventArgs : EventArgs { public string Value { get; private set; } public ConsoleWriterEventArgs(string value) { Value = value; } } public class ConsoleWriter : TextWriter { public override Encoding Encoding { get { return Encoding.UTF8; } } public override void Write(string value) { if (WriteEvent != null) WriteEvent(this, new ConsoleWriterEventArgs(value)); base.Write(value); } public override void WriteLine(string value) { if (WriteLineEvent != null) WriteLineEvent(this, new ConsoleWriterEventArgs(value)); base.WriteLine(value); } public event EventHandler<ConsoleWriterEventArgs> WriteEvent; public event EventHandler<ConsoleWriterEventArgs> WriteLineEvent; }
26.428571
92
0.713514
[ "MIT" ]
Crushedice/UpdateServer
Classes/ConsoleWriter.cs
927
C#
using System.Threading.Tasks; namespace PrivateWiki.Services.DefaultPagesService { public interface IDefaultPagesService { Task<bool> InsertStartPage(); Task<bool> InsertSyntaxPage(); Task<bool> InsertMarkdownTestPage(); Task<bool> InsertHtmlTestPage(); Task<bool> InsertTextTestPage(); Task<bool> InsertDefaultPages(); } }
18.105263
50
0.761628
[ "MIT" ]
lampenlampen/PrivateWiki
PrivateWiki/Services/DefaultPagesService/IDefaultPagesService.cs
344
C#
/* * QUANTCONNECT.COM - Democratizing Finance, Empowering Individuals. * Lean Algorithmic Trading Engine v2.0. Copyright 2014 QuantConnect Corporation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System; using System.Collections.Generic; using System.Linq; using QuantConnect.Data; using QuantConnect.Interfaces; namespace QuantConnect.Algorithm.CSharp { /// <summary> /// Regression algorithm with a custom universe and benchmark, both using the same security. /// </summary> public class CustomUniverseWithBenchmarkRegressionAlgorithm : QCAlgorithm, IRegressionAlgorithmDefinition { private const int ExpectedLeverage = 2; private Symbol _spy; private decimal _previousBenchmarkValue; private DateTime _previousTime; private decimal _previousSecurityValue; private bool _universeSelected; private bool _onDataWasCalled; private int _benchmarkPriceDidNotChange; /// <summary> /// Initialise the data and resolution required, as well as the cash and start-end dates for your algorithm. All algorithms must initialized. /// </summary> public override void Initialize() { SetStartDate(2013, 10, 4); SetEndDate(2013, 10, 11); // Hour resolution _spy = AddEquity("SPY", Resolution.Hour).Symbol; // Minute resolution AddUniverse("my-universe", x => { if(x.Day % 2 == 0) { _universeSelected = true; return new List<string> {"SPY"}; } _universeSelected = false; return Enumerable.Empty<string>(); } ); // internal daily resolution SetBenchmark("SPY"); Symbol symbol; if (!SymbolCache.TryGetSymbol("SPY", out symbol) || !ReferenceEquals(_spy, symbol)) { throw new Exception("We expected 'SPY' to be added to the Symbol cache," + " since the algorithm is also using it"); } } /// <summary> /// OnData event is the primary entry point for your algorithm. Each new data point will be pumped in here. /// </summary> /// <param name="data">Slice object keyed by symbol containing the stock data</param> public override void OnData(Slice data) { var security = Securities[_spy]; _onDataWasCalled = true; var bar = data.Bars.Values.Single(); if (_universeSelected) { if (bar.IsFillForward || bar.Period != TimeSpan.FromMinutes(1)) { // bar should always be the Minute resolution one here throw new Exception("Unexpected Bar error"); } if (_previousTime.Date == data.Time.Date && (data.Time - _previousTime) != TimeSpan.FromMinutes(1)) { throw new Exception("For the same date expected data updates every 1 minute"); } } else { if (data.Time.Minute == 0 && _previousSecurityValue == security.Price) { throw new Exception($"Security Price error. Price should change every new hour"); } if (data.Time.Minute != 0 && _previousSecurityValue != security.Price) { throw new Exception($"Security Price error. Price should not change every minute"); } } _previousSecurityValue = security.Price; // assert benchmark updates only on date change var currentValue = Benchmark.Evaluate(data.Time); if (_previousTime.Hour == data.Time.Hour) { if (currentValue != _previousBenchmarkValue) { throw new Exception($"Benchmark value error - expected: {_previousBenchmarkValue} {_previousTime}, actual: {currentValue} {data.Time}. " + "Benchmark value should only change when there is a change in hours"); } } else { if (data.Time.Minute == 0) { if (currentValue == _previousBenchmarkValue) { _benchmarkPriceDidNotChange++; // there are two consecutive equal data points so we give it some room if (_benchmarkPriceDidNotChange > 1) { throw new Exception($"Benchmark value error - expected a new value, current {currentValue} {data.Time}" + "Benchmark value should change when there is a change in hours"); } } else { _benchmarkPriceDidNotChange = 0; } } } _previousBenchmarkValue = currentValue; _previousTime = data.Time; // assert algorithm security is the correct one - not the internal one if (security.Leverage != ExpectedLeverage) { throw new Exception($"Leverage error - expected: {ExpectedLeverage}, actual: {security.Leverage}"); } } public override void OnEndOfAlgorithm() { if (!_onDataWasCalled) { throw new Exception("OnData was not called"); } } /// <summary> /// This is used by the regression test system to indicate if the open source Lean repository has the required data to run this algorithm. /// </summary> public bool CanRunLocally { get; } = true; /// <summary> /// This is used by the regression test system to indicate which languages this algorithm is written in. /// </summary> public Language[] Languages { get; } = { Language.CSharp }; /// <summary> /// This is used by the regression test system to indicate what the expected statistics are from running the algorithm /// </summary> public Dictionary<string, string> ExpectedStatistics => new Dictionary<string, string> { {"Total Trades", "0"}, {"Average Win", "0%"}, {"Average Loss", "0%"}, {"Compounding Annual Return", "0%"}, {"Drawdown", "0%"}, {"Expectancy", "0"}, {"Net Profit", "0%"}, {"Sharpe Ratio", "0"}, {"Probabilistic Sharpe Ratio", "0%"}, {"Loss Rate", "0%"}, {"Win Rate", "0%"}, {"Profit-Loss Ratio", "0"}, {"Alpha", "0"}, {"Beta", "0"}, {"Annual Standard Deviation", "0"}, {"Annual Variance", "0"}, {"Information Ratio", "-2.53"}, {"Tracking Error", "0.211"}, {"Treynor Ratio", "0"}, {"Total Fees", "$0.00"}, {"Fitness Score", "0"}, {"Kelly Criterion Estimate", "0"}, {"Kelly Criterion Probability Value", "0"}, {"Sortino Ratio", "79228162514264337593543950335"}, {"Return Over Maximum Drawdown", "79228162514264337593543950335"}, {"Portfolio Turnover", "0"}, {"Total Insights Generated", "0"}, {"Total Insights Closed", "0"}, {"Total Insights Analysis Completed", "0"}, {"Long Insight Count", "0"}, {"Short Insight Count", "0"}, {"Long/Short Ratio", "100%"}, {"Estimated Monthly Alpha Value", "$0"}, {"Total Accumulated Estimated Alpha Value", "$0"}, {"Mean Population Estimated Insight Value", "$0"}, {"Mean Population Direction", "0%"}, {"Mean Population Magnitude", "0%"}, {"Rolling Averaged Population Direction", "0%"}, {"Rolling Averaged Population Magnitude", "0%"}, {"OrderListHash", "371857150"} }; } }
40.817352
158
0.529589
[ "Apache-2.0" ]
9812334/Lean
Algorithm.CSharp/CustomUniverseWithBenchmarkRegressionAlgorithm.cs
8,939
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/wincontypes.h in the Windows SDK for Windows 10.0.20348.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="COORD" /> struct.</summary> public static unsafe class COORDTests { /// <summary>Validates that the <see cref="COORD" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<COORD>(), Is.EqualTo(sizeof(COORD))); } /// <summary>Validates that the <see cref="COORD" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(COORD).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="COORD" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(COORD), Is.EqualTo(4)); } } }
35.666667
145
0.644081
[ "MIT" ]
phizch/terrafx.interop.windows
tests/Interop/Windows/um/wincontypes/COORDTests.cs
1,286
C#
using System.Threading.Tasks; using Microsoft.Extensions.Logging; using Moq; using NUnit.Framework; using Umbraco.Cms.Core.Configuration.Models; using Umbraco.Cms.Core.Models; using Umbraco.Cms.Core.Routing; using Umbraco.Extensions; namespace Umbraco.Cms.Tests.UnitTests.Umbraco.Core.Routing { [TestFixture] public class ContentFinderByUrlWithDomainsTests : UrlRoutingTestBase { private void SetDomains3() { var domainService = Mock.Get(DomainService); domainService.Setup(service => service.GetAll(It.IsAny<bool>())) .Returns((bool incWildcards) => new[] { new UmbracoDomain("domain1.com/") {Id = 1, LanguageId = LangDeId, RootContentId = 1001, LanguageIsoCode = "de-DE"} }); } private void SetDomains4() { var domainService = Mock.Get(DomainService); domainService.Setup(service => service.GetAll(It.IsAny<bool>())) .Returns((bool incWildcards) => new[] { new UmbracoDomain("domain1.com/") {Id = 1, LanguageId = LangEngId, RootContentId = 1001, LanguageIsoCode = "en-US"}, new UmbracoDomain("domain1.com/en") {Id = 2, LanguageId = LangEngId, RootContentId = 10011, LanguageIsoCode = "en-US"}, new UmbracoDomain("domain1.com/fr") {Id = 3, LanguageId = LangFrId, RootContentId = 10012, LanguageIsoCode = "fr-FR"}, new UmbracoDomain("http://domain3.com/") {Id = 4, LanguageId = LangEngId, RootContentId = 1003, LanguageIsoCode = "en-US"}, new UmbracoDomain("http://domain3.com/en") {Id = 5, LanguageId = LangEngId, RootContentId = 10031, LanguageIsoCode = "en-US"}, new UmbracoDomain("http://domain3.com/fr") {Id = 6, LanguageId = LangFrId, RootContentId = 10032, LanguageIsoCode = "fr-FR"} }); } protected override string GetXmlContent(int templateId) => @"<?xml version=""1.0"" encoding=""utf-8""?> <!DOCTYPE root[ <!ELEMENT Doc ANY> <!ATTLIST Doc id ID #REQUIRED> ]> <root id=""-1""> <Doc id=""1001"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""0"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Home"" urlName=""1001"" writerName=""admin"" creatorName=""admin"" path=""-1,1001"" isDoc=""""> <content><![CDATA[]]></content> <Doc id=""10011"" parentID=""1001"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""0"" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" nodeName=""Sub1"" urlName=""1001-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1001,10011"" isDoc=""""> <content><![CDATA[<div>This is some content</div>]]></content> <Doc id=""100111"" parentID=""10011"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""0"" createDate=""2012-07-20T18:07:54"" updateDate=""2012-07-20T19:10:27"" nodeName=""Sub2"" urlName=""1001-1-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1001,10011,100111"" isDoc=""""> <content><![CDATA[]]></content> </Doc> <Doc id=""100112"" parentID=""10011"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""1001-1-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1001,10011,100112"" isDoc=""""> <content><![CDATA[]]></content> <Doc id=""1001121"" parentID=""100112"" level=""4"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""1001-1-2-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1001,10011,100112,1001121"" isDoc=""""> <content><![CDATA[]]></content> </Doc> <Doc id=""1001122"" parentID=""100112"" level=""4"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""1001-1-2-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1001,10011,100112,1001122"" isDoc=""""> <content><![CDATA[]]></content> </Doc> </Doc> </Doc> <Doc id=""10012"" parentID=""1001"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub 2"" urlName=""1001-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1001,10012"" isDoc=""""> <content><![CDATA[<div>This is some content</div>]]></content> <Doc id=""100121"" parentID=""10012"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""0"" createDate=""2012-07-20T18:07:54"" updateDate=""2012-07-20T19:10:27"" nodeName=""Sub2"" urlName=""1001-2-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1001,10012,100121"" isDoc=""""> <content><![CDATA[]]></content> </Doc> <Doc id=""100122"" parentID=""10012"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""1001-2-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1001,10012,100122"" isDoc=""""> <content><![CDATA[]]></content> <Doc id=""1001221"" parentID=""100122"" level=""4"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""1001-2-2-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1001,10012,100122,1001221"" isDoc=""""> <content><![CDATA[]]></content> </Doc> <Doc id=""1001222"" parentID=""100122"" level=""4"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""1001-2-2-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1001,10012,100122,1001222"" isDoc=""""> <content><![CDATA[]]></content> </Doc> </Doc> </Doc> <Doc id=""10013"" parentID=""1001"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub 2"" urlName=""1001-3"" writerName=""admin"" creatorName=""admin"" path=""-1,1001,10013"" isDoc=""""> </Doc> </Doc> <Doc id=""1002"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1234"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-16T15:26:59"" updateDate=""2012-07-18T14:23:35"" nodeName=""Test"" urlName=""1002"" writerName=""admin"" creatorName=""admin"" path=""-1,1002"" isDoc=""""> </Doc> <Doc id=""1003"" parentID=""-1"" level=""1"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""0"" createDate=""2012-06-12T14:13:17"" updateDate=""2012-07-20T18:50:43"" nodeName=""Home"" urlName=""1003"" writerName=""admin"" creatorName=""admin"" path=""-1,1003"" isDoc=""""> <content><![CDATA[]]></content> <Doc id=""10031"" parentID=""1003"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""0"" createDate=""2012-07-20T18:06:45"" updateDate=""2012-07-20T19:07:31"" nodeName=""Sub1"" urlName=""1003-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1003,10031"" isDoc=""""> <content><![CDATA[<div>This is some content</div>]]></content> <Doc id=""100311"" parentID=""10031"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""0"" createDate=""2012-07-20T18:07:54"" updateDate=""2012-07-20T19:10:27"" nodeName=""Sub2"" urlName=""1003-1-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1003,10031,100311"" isDoc=""""> <content><![CDATA[]]></content> </Doc> <Doc id=""100312"" parentID=""10031"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""1003-1-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1003,10031,100312"" isDoc=""""> <content><![CDATA[]]></content> <Doc id=""1003121"" parentID=""100312"" level=""4"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""1003-1-2-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1003,10031,100312,1003121"" isDoc=""""> <content><![CDATA[]]></content> </Doc> <Doc id=""1003122"" parentID=""100312"" level=""4"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""1003-1-2-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1003,10031,100312,1003122"" isDoc=""""> <content><![CDATA[]]></content> </Doc> </Doc> </Doc> <Doc id=""10032"" parentID=""1003"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub 2"" urlName=""1003-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1003,10032"" isDoc=""""> <content><![CDATA[<div>This is some content</div>]]></content> <Doc id=""100321"" parentID=""10032"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""0"" createDate=""2012-07-20T18:07:54"" updateDate=""2012-07-20T19:10:27"" nodeName=""Sub2"" urlName=""1003-2-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1003,10032,100321"" isDoc=""""> <content><![CDATA[]]></content> </Doc> <Doc id=""100322"" parentID=""10032"" level=""3"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""1003-2-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1003,10032,100322"" isDoc=""""> <content><![CDATA[]]></content> <Doc id=""1003221"" parentID=""100322"" level=""4"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""0"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""1003-2-2-1"" writerName=""admin"" creatorName=""admin"" path=""-1,1003,10032,100322,1003221"" isDoc=""""> <content><![CDATA[]]></content> </Doc> <Doc id=""1003222"" parentID=""100322"" level=""4"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""1"" createDate=""2012-07-20T18:08:08"" updateDate=""2012-07-20T19:10:52"" nodeName=""Sub 3"" urlName=""1003-2-2-2"" writerName=""admin"" creatorName=""admin"" path=""-1,1003,10032,100322,1003222"" isDoc=""""> <content><![CDATA[]]></content> </Doc> </Doc> </Doc> <Doc id=""10033"" parentID=""1003"" level=""2"" writerID=""0"" creatorID=""0"" nodeType=""1044"" template=""" + templateId + @""" sortOrder=""2"" createDate=""2012-07-20T18:08:01"" updateDate=""2012-07-20T18:49:32"" nodeName=""Sub 2"" urlName=""1003-3"" writerName=""admin"" creatorName=""admin"" path=""-1,1003,10033"" isDoc=""""> </Doc> </Doc> </root>"; [TestCase("http://domain1.com/", 1001)] [TestCase("http://domain1.com/1001-1", 10011)] [TestCase("http://domain1.com/1001-2/1001-2-1", 100121)] public async Task Lookup_SingleDomain(string url, int expectedId) { SetDomains3(); GlobalSettings.HideTopLevelNodeFromPath = true; var umbracoContextAccessor = GetUmbracoContextAccessor(url); var publishedRouter = CreatePublishedRouter(umbracoContextAccessor); var umbracoContext = umbracoContextAccessor.GetRequiredUmbracoContext(); var frequest = await publishedRouter.CreateRequestAsync(umbracoContext.CleanedUmbracoUrl); // must lookup domain else lookup by URL fails publishedRouter.FindDomain(frequest); var lookup = new ContentFinderByUrl(Mock.Of<ILogger<ContentFinderByUrl>>(), umbracoContextAccessor); var result = await lookup.TryFindContent(frequest); Assert.IsTrue(result); Assert.AreEqual(expectedId, frequest.PublishedContent.Id); } [TestCase("http://domain1.com/", 1001, "en-US")] [TestCase("http://domain1.com/en", 10011, "en-US")] [TestCase("http://domain1.com/en/1001-1-1", 100111, "en-US")] [TestCase("http://domain1.com/fr", 10012, "fr-FR")] [TestCase("http://domain1.com/fr/1001-2-1", 100121, "fr-FR")] [TestCase("http://domain1.com/1001-3", 10013, "en-US")] [TestCase("http://domain2.com/1002", 1002, "")] [TestCase("http://domain3.com/", 1003, "en-US")] [TestCase("http://domain3.com/en", 10031, "en-US")] [TestCase("http://domain3.com/en/1003-1-1", 100311, "en-US")] [TestCase("http://domain3.com/fr", 10032, "fr-FR")] [TestCase("http://domain3.com/fr/1003-2-1", 100321, "fr-FR")] [TestCase("http://domain3.com/1003-3", 10033, "en-US")] [TestCase("https://domain1.com/", 1001, "en-US")] [TestCase("https://domain3.com/", 1001, "")] // because domain3 is explicitely set on http public async Task Lookup_NestedDomains(string url, int expectedId, string expectedCulture) { SetDomains4(); // defaults depend on test environment expectedCulture ??= System.Threading.Thread.CurrentThread.CurrentUICulture.Name; GlobalSettings.HideTopLevelNodeFromPath = true; var umbracoContextAccessor = GetUmbracoContextAccessor(url); var publishedRouter = CreatePublishedRouter(umbracoContextAccessor); var umbracoContext = umbracoContextAccessor.GetRequiredUmbracoContext(); var frequest = await publishedRouter.CreateRequestAsync(umbracoContext.CleanedUmbracoUrl); // must lookup domain else lookup by URL fails publishedRouter.FindDomain(frequest); Assert.AreEqual(expectedCulture, frequest.Culture); var lookup = new ContentFinderByUrl(Mock.Of<ILogger<ContentFinderByUrl>>(), umbracoContextAccessor); var result = await lookup.TryFindContent(frequest); Assert.IsTrue(result); Assert.AreEqual(expectedId, frequest.PublishedContent.Id); } } }
82.557292
370
0.595988
[ "MIT" ]
Lantzify/Umbraco-CMS
tests/Umbraco.Tests.UnitTests/Umbraco.Core/Routing/ContentFinderByUrlWithDomainsTests.cs
15,851
C#