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.IO;
using SharpCompress.Common;
namespace SharpCompress.IO
{
internal class ListeningStream : Stream
{
private long currentEntryTotalReadBytes;
private IExtractionListener listener;
public ListeningStream(IExtractionListener listener, Stream stream)
{
Stream = stream;
this.listener = listener;
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
Stream.Dispose();
}
}
public Stream Stream { get; private set; }
public override bool CanRead
{
get { return Stream.CanRead; }
}
public override bool CanSeek
{
get { return Stream.CanSeek; }
}
public override bool CanWrite
{
get { return Stream.CanWrite; }
}
public override void Flush()
{
Stream.Flush();
}
public override long Length
{
get { return Stream.Length; }
}
public override long Position
{
get { return Stream.Position; }
set { Stream.Position = value; }
}
public override int Read(byte[] buffer, int offset, int count)
{
int read = Stream.Read(buffer, offset, count);
currentEntryTotalReadBytes += read;
listener.FireCompressedBytesRead(currentEntryTotalReadBytes, currentEntryTotalReadBytes);
return read;
}
public override long Seek(long offset, SeekOrigin origin)
{
return Stream.Seek(offset, origin);
}
public override void SetLength(long value)
{
Stream.SetLength(value);
}
public override void Write(byte[] buffer, int offset, int count)
{
Stream.Write(buffer, offset, count);
}
}
} | 24.209877 | 101 | 0.54156 | [
"Apache-2.0"
] | 3-1415926/mono | mcs/class/System.IO.Compression/SharpCompress/IO/ListeningStream.cs | 1,963 | C# |
//-----------------------------------------------------------------------------
// FILE: InternalDescribeDomainResponse.cs
// CONTRIBUTOR: Jeff Lill
// COPYRIGHT: Copyright (c) 2005-2021 by neonFORGE LLC. 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.
// 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.ComponentModel;
using Neon.Cadence;
using Neon.Common;
using Newtonsoft.Json;
namespace Neon.Cadence.Internal
{
/// <summary>
/// <b>INTERNAL USE ONLY:</b> Describes a Cadence domain.
/// </summary>
internal class InternalDescribeDomainResponse
{
/// <summary>
/// The domain information.
/// </summary>
[JsonProperty(PropertyName = "domainInfo", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
[DefaultValue(null)]
public InternalDomainInfo DomainInfo { get; set; }
/// <summary>
/// The domain configuration.
/// </summary>
[JsonProperty(PropertyName = "configuration", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
[DefaultValue(null)]
public InternalDomainConfiguration DomainConfiguration { get; set; }
/// <summary>
/// Indicates whether the domain is global.
/// </summary>
[JsonProperty(PropertyName = "isGlobalDomain", DefaultValueHandling = DefaultValueHandling.IgnoreAndPopulate)]
[DefaultValue(false)]
public bool IsGlobalDomain;
// $todo(jefflill): Ignorning:
//
// DomainReplicationConfiguration
// FailoverVersion
/// <summary>
/// Converts the internal instance into a public <see cref="DomainDescription"/>.
/// </summary>
/// <returns>The converted <see cref="DomainDescription"/>.</returns>
public DomainDescription ToPublic()
{
return new DomainDescription()
{
DomainInfo = this.DomainInfo.ToPublic(),
Configuration = this.DomainConfiguration.ToPublic(),
IsGlobalDomain = this.IsGlobalDomain
};
}
}
}
| 35.493333 | 118 | 0.636364 | [
"Apache-2.0"
] | nforgeio/neonKUBE | Lib/Neon.Cadence/Internal/InternalDescribeDomainResponse.cs | 2,664 | C# |
// [System.Serializable]
// public class ByteConstantSO : ConstantSO<byte> { }
// [System.Serializable]
// public class ByteConstantReference : ConstantReference<ByteConstantSO, byte>
// {
// public ByteConstantReference( byte startValue = 0 ) : base( startValue ) { }
// public static implicit operator byte( ByteConstantReference c ) => c.Value;
// } | 33.363636 | 81 | 0.702997 | [
"MIT"
] | k10czar/K10-SOVars | ConstantSO/ByteConstantSO.cs | 367 | 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\EntityType.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
using System.Runtime.Serialization;
using Newtonsoft.Json;
/// <summary>
/// The type Mailbox Usage Quota Status Mailbox Counts.
/// </summary>
[JsonObject(MemberSerialization = MemberSerialization.OptIn)]
public partial class MailboxUsageQuotaStatusMailboxCounts : Entity
{
///<summary>
/// The MailboxUsageQuotaStatusMailboxCounts constructor
///</summary>
public MailboxUsageQuotaStatusMailboxCounts()
{
this.ODataType = "microsoft.graph.mailboxUsageQuotaStatusMailboxCounts";
}
/// <summary>
/// Gets or sets report refresh date.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "reportRefreshDate", Required = Newtonsoft.Json.Required.Default)]
public Date ReportRefreshDate { get; set; }
/// <summary>
/// Gets or sets under limit.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "underLimit", Required = Newtonsoft.Json.Required.Default)]
public Int64? UnderLimit { get; set; }
/// <summary>
/// Gets or sets warning issued.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "warningIssued", Required = Newtonsoft.Json.Required.Default)]
public Int64? WarningIssued { get; set; }
/// <summary>
/// Gets or sets send prohibited.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "sendProhibited", Required = Newtonsoft.Json.Required.Default)]
public Int64? SendProhibited { get; set; }
/// <summary>
/// Gets or sets send receive prohibited.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "sendReceiveProhibited", Required = Newtonsoft.Json.Required.Default)]
public Int64? SendReceiveProhibited { get; set; }
/// <summary>
/// Gets or sets indeterminate.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "indeterminate", Required = Newtonsoft.Json.Required.Default)]
public Int64? Indeterminate { get; set; }
/// <summary>
/// Gets or sets report date.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "reportDate", Required = Newtonsoft.Json.Required.Default)]
public Date ReportDate { get; set; }
/// <summary>
/// Gets or sets report period.
/// </summary>
[JsonProperty(NullValueHandling = NullValueHandling.Ignore, PropertyName = "reportPeriod", Required = Newtonsoft.Json.Required.Default)]
public string ReportPeriod { get; set; }
}
}
| 41.357143 | 153 | 0.625216 | [
"MIT"
] | OfficeGlobal/msgraph-beta-sdk-dotnet | src/Microsoft.Graph/Models/Generated/MailboxUsageQuotaStatusMailboxCounts.cs | 3,474 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Sander.DirLister.Core.Application.Writers;
namespace Sander.DirLister.Core.Application
{
internal sealed class OutputFileWriter
{
private readonly Configuration _configuration;
private List<string> _outputFiles;
internal OutputFileWriter(Configuration configuration)
{
_configuration = configuration;
_outputFiles = new List<string>(_configuration.OutputFormats.Count);
}
internal void Write(List<FileEntry> entries)
{
_configuration.Log(TraceLevel.Info, "Creating output files...");
var endDate = DateTimeOffset.Now;
var tasks = new List<Task<string>>();
//todo: more elegant than repeated if
if (_configuration.OutputFormats.Contains(OutputFormat.Csv))
{
tasks.Add(Task.Run(() => new CsvWriter(_configuration, endDate, entries).Write()));
}
if (_configuration.OutputFormats.Contains(OutputFormat.Html))
{
tasks.Add(Task.Run(() => new HtmlWriter(_configuration, endDate, entries).Write()));
}
if (_configuration.OutputFormats.Contains(OutputFormat.Json))
{
tasks.Add(Task.Run(() => new JsonWriter(_configuration, endDate, entries).Write()));
}
if (_configuration.OutputFormats.Contains(OutputFormat.Txt))
{
tasks.Add(Task.Run(() => new TxtWriter(_configuration, endDate, entries).Write()));
}
if (_configuration.OutputFormats.Contains(OutputFormat.Xml))
{
tasks.Add(Task.Run(() => new XmlWriter(_configuration, endDate, entries).Write()));
}
if (_configuration.OutputFormats.Contains(OutputFormat.Md))
{
tasks.Add(Task.Run(() => new MarkdownWriter(_configuration, endDate, entries).Write()));
}
// ReSharper disable once CoVariantArrayConversion
Task.WaitAll(tasks.ToArray());
_outputFiles = tasks.Select(x => x.Result)
.Where(x => !string.IsNullOrWhiteSpace(x)).ToList();
_configuration.Log(TraceLevel.Info, $"{_outputFiles.Count} output file(s) created");
}
internal void OpenFileOrFolder()
{
if (_outputFiles.Count == 1)
{
_configuration.Log(TraceLevel.Info, "Opening the output file with the default viewer");
Process.Start(_outputFiles[0]);
return;
}
_configuration.Log(TraceLevel.Info, "Opening the output folder");
ShowSelectedInExplorer.FilesOrFolders(_configuration.OutputFolder, _outputFiles.Select(Path.GetFileName).ToArray());
}
}
}
| 28.77907 | 119 | 0.723232 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | SanderSade/DirLister | DirLister.Core/Application/OutputFileWriter.cs | 2,477 | C# |
//#define COSMOSDEBUG
using System;
using System.Collections.Generic;
using Cosmos.HAL.BlockDevice;
using Cosmos.System.FileSystem.FAT;
using Cosmos.System.FileSystem.ISO9660;
using Cosmos.System.FileSystem.VFS;
namespace Cosmos.System.FileSystem;
public class Disk
{
private readonly FileSystem[] MountedPartitions = new FileSystem[4];
private readonly List<ManagedPartition> parts = new();
/// <summary>
/// Main blockdevice that has all of the partitions.
/// </summary>
public BlockDevice Host;
public Disk(BlockDevice mainBlockDevice)
{
Host = mainBlockDevice;
foreach (var part in Partition.Partitions)
{
if (part.Host == mainBlockDevice)
{
parts.Add(new ManagedPartition(part));
}
}
Size = (int)(mainBlockDevice.BlockCount * mainBlockDevice.BlockSize);
}
public bool IsMBR => !GPT.IsGPTPartition(Host);
/// <summary>
/// The size of the disk in bytes.
/// </summary>
public int Size { get; }
/// <summary>
/// List of partitions
/// </summary>
public List<ManagedPartition> Partitions
{
get
{
var converted = new List<ManagedPartition>();
if (GPT.IsGPTPartition(Host))
{
var gpt = new GPT(Host);
var i = 0;
foreach (var item in gpt.Partitions)
{
var part = new ManagedPartition(new Partition(Host, item.StartSector, item.SectorCount));
if (MountedPartitions[i] != null)
{
var data = MountedPartitions[i];
part.RootPath = data.RootPath;
part.MountedFS = data;
}
converted.Add(part);
i++;
}
}
else
{
var mbr = new MBR(Host);
var i = 0;
foreach (var item in mbr.Partitions)
{
var part = new ManagedPartition(new Partition(Host, item.StartSector, item.SectorCount));
if (MountedPartitions[i] != null)
{
var data = MountedPartitions[i];
part.RootPath = data.RootPath;
part.MountedFS = data;
}
converted.Add(part);
i++;
}
}
return converted;
}
}
/// <summary>
/// List of file systems.
/// </summary>
public static List<FileSystemFactory> RegisteredFileSystemsTypes { get; } =
new() { new FatFileSystemFactory(), new ISO9660FileSystemFactory() };
public BlockDeviceType Type => Host.Type;
/// <summary>
/// Mounts all of the partitions in the disk
/// </summary>
public void Mount()
{
for (var i = 0; i < Partitions.Count; i++)
{
MountPartition(i);
}
}
/// <summary>
/// Display information about the disk.
/// </summary>
public void DisplayInformation()
{
if (Partitions.Count > 0)
{
for (var i = 0; i < Partitions.Count; i++)
{
Global.mFileSystemDebugger.SendInternal("Partition #: ");
Global.mFileSystemDebugger.SendInternal(i + 1);
global::System.Console.WriteLine("Partition #: " + (i + 1));
Global.mFileSystemDebugger.SendInternal("Block Size:");
Global.mFileSystemDebugger.SendInternal(Partitions[i].Host.BlockSize);
global::System.Console.WriteLine("Block Size: " + Partitions[i].Host.BlockSize + " bytes");
Global.mFileSystemDebugger.SendInternal("Block Count:");
Global.mFileSystemDebugger.SendInternal(Partitions[i].Host.BlockCount);
global::System.Console.WriteLine("Block Partitions: " + Partitions[i].Host.BlockCount);
Global.mFileSystemDebugger.SendInternal("Size:");
Global.mFileSystemDebugger.SendInternal(Partitions[i].Host.BlockCount * Partitions[i].Host.BlockSize /
1024 / 1024);
global::System.Console.WriteLine("Size: " +
Partitions[i].Host.BlockCount * Partitions[i].Host.BlockSize / 1024 /
1024 + " MB");
}
}
else
{
global::System.Console.WriteLine("No partitions found!");
}
}
/// <summary>
/// Create Partition.
/// </summary>
/// <param name="size">Size in MB.</param>
/// <exception cref="ArgumentOutOfRangeException">Thrown if start / end is smaller then 0.</exception>
/// <exception cref="ArgumentException">Thrown if end is smaller or equal to start.</exception>
/// <exception cref="NotImplementedException">Thrown if partition type is GPT.</exception>
public void CreatePartition(int size)
{
if ((size == 0) | (size < 0))
{
throw new ArgumentException("size");
}
if (GPT.IsGPTPartition(Host))
{
throw new Exception("Creating partitions with GPT style not yet supported!");
}
int location;
var startingSector = 63;
var amountOfSectors = (uint)(size * 1024 * 1024 / 512);
//TODO: Check if partition is too big
if (Partitions.Count == 0)
{
location = 446;
startingSector = 63;
}
else if (Partitions.Count == 1)
{
location = 462;
startingSector = (int)(Partitions[0].Host.BlockSize + Partitions[0].Host.BlockCount);
}
else if (Partitions.Count == 2)
{
location = 478;
}
else if (Partitions.Count == 3)
{
location = 494;
}
else
{
throw new NotImplementedException("Extended partitons not yet supported.");
}
//Create MBR
var mbrData = new byte[512];
Host.ReadBlock(0, 1, ref mbrData);
mbrData[location + 0] = 0x80; //bootable
mbrData[location + 1] = 0x1; //starting head
mbrData[location + 2] = 0; //Starting sector
mbrData[location + 3] = 0x0; //Starting Cylinder
mbrData[location + 4] = 83; //normal partition
mbrData[location + 5] = 0xFE; //ending head
mbrData[location + 6] = 0x3F; //Ending Sector
mbrData[location + 7] = 0x40; //Ending Cylinder
//Starting Sector
var startingSectorBytes = BitConverter.GetBytes(startingSector);
mbrData[location + 8] = startingSectorBytes[0];
mbrData[location + 9] = startingSectorBytes[1];
mbrData[location + 10] = startingSectorBytes[2];
mbrData[location + 11] = startingSectorBytes[3];
//Total Sectors in partition
var total = BitConverter.GetBytes(amountOfSectors);
mbrData[location + 12] = total[0];
mbrData[location + 13] = total[1];
mbrData[location + 14] = total[2];
mbrData[location + 15] = total[3];
//Boot flag
var boot = BitConverter.GetBytes((ushort)0xAA55);
mbrData[510] = boot[0];
mbrData[511] = boot[1];
//Save the data
Host.WriteBlock(0, 1, ref mbrData);
}
/// <summary>
/// Deletes a partition
/// </summary>
/// <param name="index">Partition index starting from 0</param>
public void DeletePartition(int index)
{
if (GPT.IsGPTPartition(Host))
{
throw new Exception("Deleting partitions with GPT style not yet supported!");
}
var location = 446 + 16 * index;
var mbr = Host.NewBlockArray(1);
Host.ReadBlock(0, 1, ref mbr);
for (var i = location; i < location + 16; i++)
{
mbr[i] = 0;
}
Host.WriteBlock(0, 1, ref mbr);
}
/// <summary>
/// Deletes all partitions on the disk.
/// </summary>
public void Clear()
{
if (GPT.IsGPTPartition(Host))
{
throw new Exception("Removing all partitions with GPT style not yet supported!");
}
for (var i = 0; i < Partitions.Count; i++)
{
DeletePartition(i);
}
}
public void FormatPartition(int index, string format, bool quick = true)
{
var part = Partitions[index];
var xSize = (long)(Host.BlockCount * Host.BlockSize / 1024 / 1024);
if (format.StartsWith("FAT"))
{
FatFileSystem.CreateFatFileSystem(part.Host, VFSManager.GetNextFilesystemLetter() + ":\\", xSize, format);
Mount();
}
else
{
throw new NotImplementedException(format + " formatting not supported.");
}
}
/// <summary>
/// Mounts a partition
/// </summary>
/// <param name="index">Partiton index</param>
public void MountPartition(int index)
{
var part = Partitions[index];
//Don't remount
if (MountedPartitions[index] != null)
{
//We already mounted this partiton
return;
}
var xRootPath = String.Concat(VFSManager.GetNextFilesystemLetter(), VFSBase.VolumeSeparatorChar,
VFSBase.DirectorySeparatorChar);
var xSize = (long)(Host.BlockCount * Host.BlockSize / 1024 / 1024);
foreach (var item in RegisteredFileSystemsTypes)
{
if (item.IsType(part.Host))
{
Kernel.PrintDebug("Mounted partition.");
//We would have done Partitions[i].MountedFS = item.Create(...), but since the array is not cached, we need to store the mounted partitions in a list
MountedPartitions[index] = item.Create(part.Host, xRootPath, xSize);
return;
}
}
Kernel.PrintDebug("Cannot find file system for partiton.");
}
}
| 32.538217 | 165 | 0.538612 | [
"BSD-3-Clause"
] | Kiirx/Cosmos | source/Cosmos.System2/FileSystem/Disk.cs | 10,219 | C# |
/*
* Copyright 2018 JDCLOUD.COM
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http:#www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
* Anti DDos Pro non-Web Rule Configuration APIs
* Anti DDos Pro non-Web Rule Configuration APIs
*
* OpenAPI spec version: v1
* Contact:
*
* NOTE: This class is auto generated by the jdcloud code generator program.
*/
using System;
using System.Collections.Generic;
using System.Text;
using JDCloudSDK.Core.Service;
namespace JDCloudSDK.Ipanti.Apis
{
/// <summary>
/// 修改转发规则的黑名单规则
/// </summary>
public class ModifyBlackListRuleOfForwardRuleResponse : JdcloudResponse<ModifyBlackListRuleOfForwardRuleResult>
{
}
} | 27.926829 | 115 | 0.735371 | [
"Apache-2.0"
] | jdcloud-api/jdcloud-sdk-net | sdk/src/Service/Ipanti/Apis/ModifyBlackListRuleOfForwardRuleResponse.cs | 1,169 | C# |
public class Rectangle
{
public Rectangle(string id = default(string), double width = 0, double height = 0, double left = 0, double top = 0)
{
this.Id = id;
this.Width = width;
this.Height = height;
this.Left = left;
this.Top = top;
}
public string Id { get; set; }
public double Width { get; set; }
public double Height { get; set; }
public double Left { get; set; }
public double Top { get; set; }
public bool Intersects(Rectangle another)
{
bool leftTop = this.Top <= another.Top &&
this.Top >= another.Top - another.Height &&
this.Left >= another.Left &&
this.Left <= another.Left + another.Width;
bool rightTop = this.Top <= another.Top &&
this.Top >= another.Top - another.Height &&
this.Left + this.Width >= another.Left &&
this.Left + this.Width <= another.Left + another.Width;
bool leftBottom = this.Top - this.Height <= another.Top &&
this.Top - this.Height >= another.Top - another.Height &&
this.Left >= another.Left &&
this.Left <= another.Left + another.Width;
bool rightBottom = this.Top - this.Height <= another.Top &&
this.Top - this.Height >= another.Top - another.Height &&
this.Left + this.Width >= another.Left &&
this.Left + this.Width <= another.Left + another.Width;
if (leftTop || rightTop || leftBottom || rightBottom)
{
return true;
}
return false;
}
}
| 45.823529 | 119 | 0.377835 | [
"MIT"
] | spzvtbg/03-Fundamentals | 02 OOP basics/01.Defining Classes/09. RectangleIntersection/Rectangle.cs | 2,339 | C# |
namespace GranularRecovery.Framework
{
public enum SmoAuthenticationMode
{
WindowsAuthentication = 1,
SqlServerAuthentication = 2
};
}
| 18.222222 | 37 | 0.676829 | [
"MIT"
] | aamshukov/miscellaneous | staging/Gr.Framework/Smo/SmoAuthenticationMode.cs | 166 | C# |
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.RazorPages;
namespace AspNetCore2_1.ExampleAngularWeb.Pages
{
[ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)]
public class ErrorModel : PageModel
{
public string RequestId { get; set; }
public bool ShowRequestId => !string.IsNullOrEmpty(RequestId);
public void OnGet()
{
RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier;
}
}
}
| 26.5 | 88 | 0.709119 | [
"MIT"
] | jakegough/HelloWorld.NetCore | Examples.AspNetCore/AspNetCore2_1.ExampleAngularWeb/AspNetCore2_1.ExampleAngularWeb/Pages/Error.cshtml.cs | 636 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
using Android.App;
// 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("BindingPathDemos.Droid")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("BindingPathDemos.Droid")]
[assembly: AssemblyCopyright("Copyright © 2014")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
[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("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
// Add some common permissions, these can be removed if not needed
[assembly: UsesPermission(Android.Manifest.Permission.Internet)]
[assembly: UsesPermission(Android.Manifest.Permission.WriteExternalStorage)]
| 36.857143 | 84 | 0.758915 | [
"Apache-2.0"
] | DLozanoNavas/xamarin-forms-book-samples | Chapter16/BindingPathDemos/BindingPathDemos/BindingPathDemos.Droid/Properties/AssemblyInfo.cs | 1,291 | 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("04.HexadecimalToDecimal")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("04.HexadecimalToDecimal")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("447a9a62-609a-4b90-9fbf-83635a85db62")]
// 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.351351 | 84 | 0.74771 | [
"MIT"
] | EmilMitev/Telerik-Academy | CSharp - part 2/4.NumeralSystems/04.HexadecimalToDecimal/Properties/AssemblyInfo.cs | 1,422 | C# |
// <auto-generated />
namespace Data.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class AjoutduneligneJPA : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(AjoutduneligneJPA));
string IMigrationMetadata.Id
{
get { return "201603110914281_Ajout d'une ligne JPA"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 27.7 | 100 | 0.622142 | [
"Apache-2.0"
] | NitriKx/M2DL-ACEE-TPs-CSharp | ASP.NET/TP-Web-Rechercher-Recette/TP-Web-Rechercher-Recette/Data/Migrations/201603110914281_Ajout d'une ligne JPA.Designer.cs | 831 | C# |
using System;
using System.ComponentModel.DataAnnotations;
using Abp.Application.Services.Dto;
using Abp.Authorization.Users;
using Abp.AutoMapper;
using DgERM.Authorization.Users;
namespace DgERM.Users.Dto
{
[AutoMapFrom(typeof(User))]
public class UserDto : EntityDto<long>
{
[Required]
[StringLength(AbpUserBase.MaxUserNameLength)]
public string UserName { get; set; }
[Required]
[StringLength(AbpUserBase.MaxNameLength)]
public string Name { get; set; }
[Required]
[StringLength(AbpUserBase.MaxSurnameLength)]
public string Surname { get; set; }
[Required]
[EmailAddress]
[StringLength(AbpUserBase.MaxEmailAddressLength)]
public string EmailAddress { get; set; }
public bool IsActive { get; set; }
public string FullName { get; set; }
public DateTime? LastLoginTime { get; set; }
public DateTime CreationTime { get; set; }
public string[] RoleNames { get; set; }
}
}
| 25.365854 | 57 | 0.649038 | [
"MIT"
] | PowerDG/DgERM | aspnet-core/src/DgERM.Application/Users/Dto/UserDto.cs | 1,040 | C# |
using System;
using Abp.Dependency;
using Abp.Timing;
using Castle.Core.Logging;
namespace CodeYu.AspNetBoilerplateDemo.Migrator
{
public class Log : ITransientDependency
{
public ILogger Logger { get; set; }
public Log()
{
Logger = NullLogger.Instance;
}
public void Write(string text)
{
Console.WriteLine(Clock.Now.ToString("yyyy-MM-dd HH:mm:ss") + " | " + text);
Logger.Info(text);
}
}
} | 22.565217 | 89 | 0.558767 | [
"MIT"
] | codeyu/AspNetBoilerplateDemo | src/CodeYu.AspNetBoilerplateDemo.Migrator/Log.cs | 519 | C# |
using System;
using System.Linq;
namespace Memento {
class BoardPrinter {
public void Print(string memo, Othello othello) {
var width = othello.Board.GetLength(0);
var height = othello.Board.GetLength(1);
Console.WriteLine(memo);
Console.WriteLine($"First: {GetColorString(othello.FirstColor)}, Next: {GetColorString(othello.NextColor)}");
for (var y = 0; y < height; y++) {
var row = Enumerable.Range(0, width)
.Select(i => GetColorString(othello.Board[i, y]))
.Aggregate((b, a) => b + a);
Console.WriteLine(row);
}
}
private string GetColorString(Color color) {
switch (color) {
case Color.None:
return "-";
case Color.White:
return "○";
case Color.Black:
return "●";
default:
throw new ArgumentOutOfRangeException(nameof(color), color, null);
}
}
}
} | 22.342105 | 112 | 0.640754 | [
"MIT"
] | kakureusagi/DesignPattern | Memento/BoardPrinter.cs | 853 | 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 Sfa.Tl.ResultsAndCertification.Web.Content.PostResultsService {
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()]
public class PrsNoAssessmentEntry {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal PrsNoAssessmentEntry() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("Sfa.Tl.ResultsAndCertification.Web.Content.PostResultsService.PrsNoAssessmentEntr" +
"y", typeof(PrsNoAssessmentEntry).Assembly);
resourceMan = temp;
}
return resourceMan;
}
}
/// <summary>
/// Overrides the current thread's CurrentUICulture property for all
/// resource lookups using this strongly typed resource class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
public static global::System.Globalization.CultureInfo Culture {
get {
return resourceCulture;
}
set {
resourceCulture = value;
}
}
/// <summary>
/// Looks up a localized string similar to Back to home.
/// </summary>
public static string Button_Back_To_Home {
get {
return ResourceManager.GetString("Button_Back_To_Home", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Search again.
/// </summary>
public static string Button_Search_Again {
get {
return ResourceManager.GetString("Button_Search_Again", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Learner does not have any registered assessments.
/// </summary>
public static string Heading_Learner_Not_Have_Registered_Assessment {
get {
return ResourceManager.GetString("Heading_Learner_Not_Have_Registered_Assessment", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to This learner does not have any assessments registered in this system. Please contact a registrations editor in your organisation if you need to amend this..
/// </summary>
public static string Inset_Text_Please_Contact_Registration_Editor_If_You_Need {
get {
return ResourceManager.GetString("Inset_Text_Please_Contact_Registration_Editor_If_You_Need", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to No assessment entry.
/// </summary>
public static string Page_Title {
get {
return ResourceManager.GetString("Page_Title", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Date of birth.
/// </summary>
public static string Title_DateofBirth_Text {
get {
return ResourceManager.GetString("Title_DateofBirth_Text", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Name.
/// </summary>
public static string Title_Name_Text {
get {
return ResourceManager.GetString("Title_Name_Text", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to Provider <br/> (UKPRN).
/// </summary>
public static string Title_Provider_Text {
get {
return ResourceManager.GetString("Title_Provider_Text", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to T Level.
/// </summary>
public static string Title_TLevel_Text {
get {
return ResourceManager.GetString("Title_TLevel_Text", resourceCulture);
}
}
/// <summary>
/// Looks up a localized string similar to ULN.
/// </summary>
public static string Title_Uln_Text {
get {
return ResourceManager.GetString("Title_Uln_Text", resourceCulture);
}
}
}
}
| 40.335484 | 209 | 0.586212 | [
"MIT"
] | SkillsFundingAgency/tl-results-and-certification | src/Sfa.Tl.ResultsAndCertification.Web/Content/PostResultsService/PrsNoAssessmentEntry.Designer.cs | 6,254 | C# |
namespace Cake.Issues.Testing
{
using System;
using Cake.Core.IO;
/// <summary>
/// Class for checking issues.
/// </summary>
public static class IssueChecker
{
/// <summary>
/// Checks values of an issue.
/// </summary>
/// <param name="issueToCheck">Issue which should be checked.</param>
/// <param name="expectedIssue">Description of the expected issue.</param>
public static void Check(
IIssue issueToCheck,
IssueBuilder expectedIssue)
{
issueToCheck.NotNull(nameof(issueToCheck));
expectedIssue.NotNull(nameof(expectedIssue));
Check(
issueToCheck,
expectedIssue.Create());
}
/// <summary>
/// Checks values of an issue.
/// </summary>
/// <param name="issueToCheck">Issue which should be checked.</param>
/// <param name="expectedIssue">Description of the expected issue.</param>
public static void Check(
IIssue issueToCheck,
IIssue expectedIssue)
{
issueToCheck.NotNull(nameof(issueToCheck));
expectedIssue.NotNull(nameof(expectedIssue));
Check(
issueToCheck,
expectedIssue.ProviderType,
expectedIssue.ProviderName,
expectedIssue.Run,
expectedIssue.Identifier,
expectedIssue.ProjectFileRelativePath?.ToString(),
expectedIssue.ProjectName,
expectedIssue.AffectedFileRelativePath?.ToString(),
expectedIssue.Line,
expectedIssue.EndLine,
expectedIssue.Column,
expectedIssue.EndColumn,
expectedIssue.FileLink,
expectedIssue.MessageText,
expectedIssue.MessageHtml,
expectedIssue.MessageMarkdown,
expectedIssue.Priority,
expectedIssue.PriorityName,
expectedIssue.Rule,
expectedIssue.RuleUrl);
}
/// <summary>
/// Checks values of an issue.
/// </summary>
/// <param name="issue">Issue which should be checked.</param>
/// <param name="providerType">Expected type of the issue provider.</param>
/// <param name="providerName">Expected human friendly name of the issue provider.</param>
/// <param name="run">Expected name of the run which reported the issue.</param>
/// <param name="identifier">Expected identifier of the issue.</param>
/// <param name="projectFileRelativePath">Expected relative path of the project file.
/// <c>null</c> if the issue is not expected to be related to a project.</param>
/// <param name="projectName">Expected project name.
/// <c>null</c> or <see cref="string.Empty"/> if the issue is not expected to be related to a project.</param>
/// <param name="affectedFileRelativePath">Expected relative path of the affected file.
/// <c>null</c> if the issue is not expected to be related to a change in a file.</param>
/// <param name="line">Expected line number.
/// <c>null</c> if the issue is not expected to be related to a file or specific line.</param>
/// <param name="endLine">Expected end of line range.
/// <c>null</c> if the issue is not expected to be related to a file, specific line or range of lines.</param>
/// <param name="column">Expected column.
/// <c>null</c> if the issue is not expected to be related to a file or specific column.</param>
/// <param name="endColumn">Expected end of column range.
/// <c>null</c> if the issue is not expected to be related to a file, specific column or range of columns.</param>
/// <param name="fileLink">Expected file link.
/// <c>null</c> if the issue is not expected to have a file link.</param>
/// <param name="messageText">Expected message in plain text format.</param>
/// <param name="messageHtml">Expected message in HTML format.</param>
/// <param name="messageMarkdown">Expected message in Markdown format.</param>
/// <param name="priority">Expected priority.
/// <c>null</c> if no priority is expected.</param>
/// <param name="priorityName">Expected priority name.
/// <c>null</c> or <see cref="string.Empty"/> if no priority is expected.</param>
/// <param name="rule">Expected rule identifier.
/// <c>null</c> or <see cref="string.Empty"/> if no rule identifier is expected.</param>
/// <param name="ruleUrl">Expected URL containing information about the failing rule.
/// <c>null</c> if no rule Url is expected.</param>
public static void Check(
IIssue issue,
string providerType,
string providerName,
string run,
string identifier,
string projectFileRelativePath,
string projectName,
string affectedFileRelativePath,
int? line,
int? endLine,
int? column,
int? endColumn,
Uri fileLink,
string messageText,
string messageHtml,
string messageMarkdown,
int? priority,
string priorityName,
string rule,
Uri ruleUrl)
{
issue.NotNull(nameof(issue));
if (issue.ProviderType != providerType)
{
throw new Exception(
$"Expected issue.ProviderType to be '{providerType}' but was '{issue.ProviderType}'.");
}
if (issue.ProviderName != providerName)
{
throw new Exception(
$"Expected issue.ProviderName to be '{providerName}' but was '{issue.ProviderName}'.");
}
if (issue.Run != run)
{
throw new Exception(
$"Expected issue.Run to be '{run}' but was '{issue.Run}'.");
}
if (issue.Identifier != identifier)
{
throw new Exception(
$"Expected issue.Identifier to be '{identifier}' but was '{issue.Identifier}'.");
}
if (issue.ProjectFileRelativePath == null)
{
if (projectFileRelativePath != null)
{
throw new Exception(
$"Expected issue.ProjectFileRelativePath to be '{projectFileRelativePath}' but was 'null'.");
}
}
else
{
if (issue.ProjectFileRelativePath.ToString() != new FilePath(projectFileRelativePath).ToString())
{
throw new Exception(
$"Expected issue.ProjectFileRelativePath to be '{projectFileRelativePath}' but was '{issue.ProjectFileRelativePath}'.");
}
if (!issue.ProjectFileRelativePath.IsRelative)
{
throw new Exception(
$"Expected issue.ProjectFileRelativePath to be a relative path");
}
}
if (issue.ProjectName != projectName)
{
throw new Exception(
$"Expected issue.ProjectName to be '{projectName}' but was '{issue.ProjectName}'.");
}
if (issue.AffectedFileRelativePath == null)
{
if (affectedFileRelativePath != null)
{
throw new Exception(
$"Expected issue.AffectedFileRelativePath to be '{affectedFileRelativePath}' but was 'null'.");
}
}
else
{
if (issue.AffectedFileRelativePath.ToString() != new FilePath(affectedFileRelativePath).ToString())
{
throw new Exception(
$"Expected issue.AffectedFileRelativePath to be '{affectedFileRelativePath}' but was '{issue.AffectedFileRelativePath}'.");
}
if (!issue.AffectedFileRelativePath.IsRelative)
{
throw new Exception(
$"Expected issue.AffectedFileRelativePath to be a relative path");
}
}
if (issue.Line != line)
{
throw new Exception(
$"Expected issue.Line to be '{line}' but was '{issue.Line}'.");
}
if (issue.EndLine != endLine)
{
throw new Exception(
$"Expected issue.EndLine to be '{endLine}' but was '{issue.EndLine}'.");
}
if (issue.Column != column)
{
throw new Exception(
$"Expected issue.Column to be '{column}' but was '{issue.Column}'.");
}
if (issue.EndColumn != endColumn)
{
throw new Exception(
$"Expected issue.EndColumn to be '{endColumn}' but was '{issue.EndColumn}'.");
}
if (issue.FileLink?.ToString() != fileLink?.ToString())
{
throw new Exception(
$"Expected issue.FileLink to be '{fileLink}' but was '{issue.FileLink}'.");
}
if (issue.MessageText != messageText)
{
throw new Exception(
$"Expected issue.MessageText to be '{messageText}' but was '{issue.MessageText}'.");
}
if (issue.MessageHtml != messageHtml)
{
throw new Exception(
$"Expected issue.MessageHtml to be '{messageHtml}' but was '{issue.MessageHtml}'.");
}
if (issue.MessageMarkdown != messageMarkdown)
{
throw new Exception(
$"Expected issue.MessageMarkdown to be '{messageMarkdown}' but was '{issue.MessageMarkdown}'.");
}
if (issue.Priority != priority)
{
throw new Exception(
$"Expected issue.Priority to be '{priority}' but was '{issue.Priority}'.");
}
if (issue.PriorityName != priorityName)
{
throw new Exception(
$"Expected issue.PriorityName to be '{priorityName}' but was '{issue.PriorityName}'.");
}
if (issue.Rule != rule)
{
throw new Exception(
$"Expected issue.Rule to be '{rule}' but was '{issue.Rule}'.");
}
if (issue.RuleUrl?.ToString() != ruleUrl?.ToString())
{
throw new Exception(
$"Expected issue.RuleUrl to be '{ruleUrl?.ToString()}' but was '{issue.RuleUrl?.ToString()}'.");
}
}
}
}
| 40.772059 | 147 | 0.529125 | [
"MIT"
] | janniksam/Cake.Issues | src/Cake.Issues.Testing/IssueChecker.cs | 11,092 | C# |
namespace Todo.Integrations.Serilog.Destructuring
{
using System.Collections.Generic;
using global::Serilog.Core;
using global::Serilog.Events;
using Services.Security;
using Services.TodoItemLifecycleManagement;
/// <summary>
/// Instructs Serilog how to log instances of <seealso cref="NewTodoItemInfo"/> class.
/// </summary>
public class NewTodoItemInfoDestructuringPolicy : IDestructuringPolicy
{
public bool TryDestructure(object value, ILogEventPropertyValueFactory propertyValueFactory,
out LogEventPropertyValue result)
{
result = null;
NewTodoItemInfo newTodoItemInfo = value as NewTodoItemInfo;
if (newTodoItemInfo == null)
{
return false;
}
result = new StructureValue(new List<LogEventProperty>
{
new LogEventProperty(nameof(newTodoItemInfo.Name), new ScalarValue(newTodoItemInfo.Name)),
new LogEventProperty(nameof(newTodoItemInfo.Owner),
new ScalarValue(newTodoItemInfo.Owner.GetNameOrDefault()))
});
return true;
}
}
}
| 31.5 | 106 | 0.636591 | [
"MIT"
] | srvsk/aspnetcorepoc | Sources/Todo.Integrations.Serilog/Destructuring/NewTodoItemInfoDestructuringPolicy.cs | 1,197 | C# |
using Microsoft.AspNetCore.SignalR;
namespace Ordering.Application.HubConfiguration
{
public class OrderStatusHub : Hub
{
// For now we don't need any implementation since we are only sending notification about the changed status from the Commands with IHubContext to Client
// Only one way communication
}
}
| 28.333333 | 160 | 0.738235 | [
"MIT"
] | Ninchuga/AspNetMicroservicesShop | Src/Services/Ordering/Ordering.Application/HubConfiguration/OrderStatusHub.cs | 342 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class PlayerMove : MonoBehaviour
{
// == public fields ==
// refrence to game object enemy spawner
public GameObject enemySpawner;
// refrence to our gameover object
public GameObject gameOver;
// refrence to score text ui object
public GameObject scoreTextUI;
// this is our player bullet prefab
public GameObject PlayerBullet;
public GameObject bulletposition1;
// explosion prefab
public GameObject Explosion;
// == private fields ==
private Rigidbody2D rb;
private Transform t;
[SerializeField] private float speed = 5.0f;
// Refrence to the lives UI text
public Text LivesUIText;
// maximum lives of player
const int MaxLives = 3;
// current lives of player
public int lives;
// == public methods ==
// == private methods ==
void Start()
{
rb = GetComponent<Rigidbody2D>();
lives = MaxLives;
// update the lives UI text
LivesUIText.text = lives.ToString();
// reset the score
scoreTextUI.GetComponent<GameScore>().Score = 0;
// set this player game object to active
gameObject.SetActive(true);
// reset the player position to the centere of the screen
transform.position = new Vector2(0, -2);
}
// Update is called once per frame
void Update()
{
// fire bullets when spacebar is pressed
if(Input.GetKeyDown("space"))
{
// play the laser sound effect
gameObject.GetComponent<AudioSource>().Play();
// instantiate main bullet
GameObject mainBullet = (GameObject)Instantiate(PlayerBullet);
// set the bullet initial position
mainBullet.transform.position = bulletposition1.transform.position;
}
// add horizontal Movement
float hMovement = Input.GetAxis("Horizontal");
// if the player presses the up arrow then move
float vMovement = Input.GetAxis("Vertical");
// apply a force,get the player moving.
rb.velocity = new Vector2(hMovement * speed, vMovement * speed);
/* if(Input.GetKeyDown(KeyCode.Space))
{
FireBullet();
}
if(Input.GetKeyUp(KeyCode.Space))
{
StopFire();
}*/
}
private void OnTriggerEnter2D(Collider2D collision)
{
// Detect collision of the player ship with an enemy ship , or enemy bullet
if((collision.tag == "EnemyShipTag") || (collision.tag == "EnemyBulletTag"))
{
showExplosion();
// subtract a life upon collision
lives--;
// update lives UI text
LivesUIText.text = lives.ToString();
// if the player is dead
if(lives == 0)
{
// destroy player ship
Destroy(gameObject);
// stop enemy spawner after player dies and have 0 remaining lives
enemySpawner.GetComponent<EnemySpawner>().stopEnemySpawner();
// change the game manager state to game over state
gameOver.SetActive(true);
}
}//if
}
// function to instantiate explosion
void showExplosion()
{
GameObject explosion = (GameObject)Instantiate(Explosion);
// setting the position of the explosion
explosion.transform.position = transform.position;
}
}
| 31.910714 | 84 | 0.602686 | [
"MIT"
] | LuqmanFarooq/Shooter-Game-Project | Space Of War/Assets/--Scripts/InGame/PlayerMove.cs | 3,576 | C# |
using BookIt.Data.Models.Contracts;
using BookIt.Data.Models.Model;
namespace BookIt.Data.Models
{
using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
public class StaffUnit : Rateable, IDeletableEntity, IBookItEntity, ICommentable, IRateable
{
private ICollection<Service> providedServices;
private ICollection<DateTime> schedule;
public StaffUnit()
{
this.providedServices = new HashSet<Service>();
this.schedule = new HashSet<DateTime>();
}
//public int Id { get; set; }
[Required]
[MaxLength(50)]
public string Name { get; set; }
public string Descriptoin { get; set; }
public string EmployeeId { get; set; }
public virtual ApplicationUser Employee { get; set; }
public virtual ICollection<Service> ProvidedServices
{
get { return this.providedServices; }
set { this.providedServices = value; }
}
public virtual ICollection<DateTime> Schedule
{
get { return this.schedule; }
set { this.schedule = value; }
}
}
}
| 25.723404 | 95 | 0.610422 | [
"MIT"
] | siderisltd/bookit | BookIT/BookIt.Api/Data/BookIt.Data.Models/StaffUnit.cs | 1,211 | C# |
using DDCImprover.Core;
using System;
using System.IO;
namespace DDCImprover.CLI
{
internal static class Program
{
private static int Main(string[] args)
{
if(args.Length == 1)
{
string configFile = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "config.xml");
Configuration.LoadConfiguration(configFile);
XMLProcessor processor = new XMLProcessor(args[0]);
var status = processor.LoadXMLFile();
if (status == ImproverStatus.LoadError)
{
Console.WriteLine("Error during loading.");
return 1;
}
Console.Write("Processing file.");
var progress = new Progress<ProgressValue>(_ => Console.Write("."));
processor.ProcessFile(progress);
status = processor.Status;
if (status != ImproverStatus.Completed)
{
Console.WriteLine();
Console.WriteLine("Error during processing.");
return 1;
}
Console.WriteLine();
Console.WriteLine("File processed.");
}
else
{
Console.WriteLine("Give an XML file name as an argument.");
}
return 0;
}
}
}
| 29.204082 | 102 | 0.491964 | [
"MIT"
] | iminashi/DDCImprover | DDCImprover.CLI/Program.cs | 1,433 | C# |
using System;
using System.Threading;
using System.Threading.Tasks;
using UtilsTests.Matrix;
namespace Runner
{
class Program
{
private const string LogFolderName = "Log";
static void Main(string[] args)
{
RunCacheSimTests();
RunTimeTests();
}
private static void RunCacheSimTests()
{
CancellationTokenSource cts = new CancellationTokenSource();
Task first = Task.Run(() =>
{
var test = new MatrixGeneratorTests(LogFolderName);
test.CancellationToken.Register(() => cts.Cancel()); // If the test fails, the cts will cancel the other one
test.TestCacheFirstHalf();
},
cts.Token);
Task second = Task.Run(() =>
{
var test = new MatrixGeneratorTests(LogFolderName);
test.CancellationToken.Register(() => cts.Cancel()); // If the test fails, the cts will cancel the other one
test.TestCacheSecondHalf();
},
cts.Token);
while (!Task.WaitAll(new[] { first, second }, 2000))
{
if (Console.KeyAvailable && Console.ReadKey(true).Key == ConsoleKey.Escape)
{
Console.WriteLine("Terminating...");
cts.Cancel();
return;
}
}
}
private static void RunTimeTests()
{
}
}
}
| 26.842105 | 124 | 0.50719 | [
"MIT"
] | Maroslav/DataStructures | 4MatTrans/Runner/Program.cs | 1,532 | C# |
using System.IO;
using System.Text.RegularExpressions;
using DotLiquid.Exceptions;
namespace DotLiquid.FileSystems
{
/// <summary>
/// This implements an abstract file system which retrieves template files named in a manner similar to Rails partials,
/// ie. with the template name prefixed with an underscore. The extension ".liquid" is also added.
///
/// For security reasons, template paths are only allowed to contain letters, numbers, and underscore.
///
/// Example:
///
/// file_system = Liquid::LocalFileSystem.new("/some/path")
///
/// file_system.full_path("mypartial") # => "/some/path/_mypartial.liquid"
/// file_system.full_path("dir/mypartial") # => "/some/path/dir/_mypartial.liquid"
/// </summary>
public class LocalFileSystem : IFileSystem
{
public string Root { get; set; }
private string snippetPath { get; set; }
public LocalFileSystem(string root)
{
Root = root;
}
public string ReadTemplateFile(Context context, string templateName)
{
// remove ""
templateName = templateName.Replace("\"", "").Replace("'", "");
var templatepath = string.Concat(((string)context.Values["asset_url"]).Substring(1), "/snippets/", templateName);
string fullPath = FullPath(templatepath);
if (!File.Exists(fullPath))
throw new FileSystemException(Liquid.ResourceManager.GetString("LocalFileSystemTemplateNotFoundException"), templateName);
return File.ReadAllText(fullPath);
}
public string FullPath(string templatePath)
{
if (!Regex.IsMatch(templatePath, @"^[^.\/][a-zA-Z0-9_\-\/]+$"))
throw new FileSystemException(Liquid.ResourceManager.GetString("LocalFileSystemIllegalTemplateNameException"), templatePath);
string fullPath = templatePath.Contains("/")
? Path.Combine(Path.Combine(Root, Path.GetDirectoryName(snippetPath + templatePath)), string.Format("{0}.liquid", Path.GetFileName(templatePath)))
: Path.Combine(Root, string.Format("{0}{1}.liquid", snippetPath, templatePath));
if (!Regex.IsMatch(Path.GetFullPath(fullPath), string.Format("^{0}", Root.Replace(@"\", @"\\"))))
throw new FileSystemException(Liquid.ResourceManager.GetString("LocalFileSystemIllegalTemplatePathException"), Path.GetFullPath(fullPath));
return fullPath;
}
}
} | 41.589286 | 155 | 0.697295 | [
"Apache-2.0"
] | seanlinmt/tradelr | DotLiquid/FileSystems/LocalFileSystem.cs | 2,331 | C# |
using System.Threading.Tasks;
namespace Pulumi.Azure.Extensions.Tests
{
internal static class TestingExtensions
{
public static Task<T> GetValueAsync<T>(this Output<T> output)
{
var tcs = new TaskCompletionSource<T>();
output.Apply(v =>
{
tcs.SetResult(v);
return v;
});
return tcs.Task;
}
public static T GetValue<T>(this Output<T> output)
{
return output.GetValueAsync().GetAwaiter().GetResult();
}
}
} | 24.791667 | 70 | 0.507563 | [
"MIT"
] | StefH/Pulumi.Azure.Extensions | tests/Pulumi.Azure.Extensions.Tests/TestingExtensions.cs | 597 | C# |
namespace OpenCvSharp
{
#if LANG_JP
/// <summary>
/// cvCopyMakeBorderで指定する, 境界線のタイプ
/// </summary>
#else
/// <summary>
/// Type of the border to create around the copied source image rectangle
/// </summary>
#endif
public enum BorderTypes : int
{
#if LANG_JP
/// <summary>
/// 境界はこの関数の最後のパラメータとして渡された定数 value で埋められる.
/// `iiiiii|abcdefgh|iiiiiii` with some specified `i`
/// </summary>
#else
/// <summary>
/// Border is filled with the fixed value, passed as last parameter of the function.
/// `iiiiii|abcdefgh|iiiiiii` with some specified `i`
/// </summary>
#endif
Constant = 0,
#if LANG_JP
/// <summary>
/// 画像の最も上/下の行と最も左/右の列(画像領域の一番外側の値)を用いて境界線を生成する.
/// `aaaaaa|abcdefgh|hhhhhhh`
/// </summary>
#else
/// <summary>
/// The pixels from the top and bottom rows, the left-most and right-most columns are replicated to fill the border.
/// `aaaaaa|abcdefgh|hhhhhhh`
/// </summary>
#endif
Replicate = 1,
/// <summary>
/// `fedcba|abcdefgh|hgfedcb`
/// </summary>
Reflect = 2,
/// <summary>
/// `cdefgh|abcdefgh|abcdefg`
/// </summary>
Wrap = 3,
/// <summary>
/// `gfedcb|abcdefgh|gfedcba`
/// </summary>
Reflect101 = 4,
/// <summary>
/// `uvwxyz|absdefgh|ijklmno`
/// </summary>
Transparent = 5,
/// <summary>
/// same as BORDER_REFLECT_101
/// </summary>
Default = Reflect101,
/// <summary>
/// do not look outside of ROI
/// </summary>
Isolated = 16,
}
}
| 23.666667 | 124 | 0.535798 | [
"MIT"
] | Atharvap14/SecondaryVision | DepthMap/Assets/OpenCV+Unity/Assets/Scripts/OpenCvSharp/modules/imgproc/Enum/BorderTypes.cs | 1,876 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace aws
{
[JsiiInterface(nativeType: typeof(IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchUriPath), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementOrStatementStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchUriPath")]
public interface IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchUriPath
{
[JsiiTypeProxy(nativeType: typeof(IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchUriPath), fullyQualifiedName: "aws.Wafv2WebAclRuleStatementOrStatementStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchUriPath")]
internal sealed class _Proxy : DeputyBase, aws.IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchUriPath
{
private _Proxy(ByRefValue reference): base(reference)
{
}
}
}
}
| 59.2 | 318 | 0.85473 | [
"MIT"
] | scottenriquez/cdktf-alpha-csharp-testing | resources/.gen/aws/aws/IWafv2WebAclRuleStatementOrStatementStatementNotStatementStatementAndStatementStatementXssMatchStatementFieldToMatchUriPath.cs | 1,184 | C# |
using System.Collections;
using System.Collections.Generic;
using Amazon.CDK;
using Amazon.CDK.AWS.S3;
using Amazon.CDK.AWS.ECS;
using Amazon.CDK.AWS.EC2;
using Amazon.CDK.AWS.ECR;
using Amazon.CDK.AWS.IAM;
using Amazon.CDK.AWS.Logs;
using Amazon.CDK.AWS.EFS;
using Amazon.CDK.AWS.StepFunctions;
using Amazon.CDK.AWS.StepFunctions.Tasks;
using Amazon.CDK.AWS.Lambda;
using Amazon.CDK.AWS.Lambda.Python;
using Amazon.CDK.AWS.DynamoDB;
using Amazon.CDK.AWS.SQS;
using Stack = Amazon.CDK.Stack;
using Queue = Amazon.CDK.AWS.SQS.Queue;
// using HeronPipeline.Go
namespace HeronPipeline
{
public class HeronPipelineStack : Stack
{
internal HeronPipelineStack(Construct scope, string id, IStackProps props = null) : base(scope, id, props)
{
var idToSupply = id + "_";
var testObj = new TestClass(this, "testClass");
var infrastructure = new Infrastructure(this, idToSupply+"infra_");
infrastructure.Create();
var helperFunctions = new HelperFunctions(this, idToSupply+"helper_", infrastructure.ecsExecutionRole, infrastructure.volume, infrastructure.cluster, infrastructure.bucket, infrastructure.sequencesTable, infrastructure.reprocessingQueue, infrastructure.dailyProcessingQueue, infrastructure.sqsAccessPolicyStatement, infrastructure.s3AccessPolicyStatement, infrastructure.dynamoDBAccessPolicyStatement);
helperFunctions.Create();
var prepareSequences = new PrepareSequences(this, idToSupply+"prep_", infrastructure.ecsExecutionRole, infrastructure.volume, infrastructure.cluster, infrastructure.bucket, infrastructure.sequencesTable, infrastructure.reprocessingQueue, infrastructure.dailyProcessingQueue);
prepareSequences.CreateAddSequencesToQueue();
prepareSequences.CreatePrepareSequences();
prepareSequences.CreatePrepareConsenusSequences();
var goFastaAlignment = new GoFastaAlignment(this, idToSupply+"align_", infrastructure.ecsExecutionRole, infrastructure.volume, infrastructure.cluster, infrastructure.bucket, infrastructure.sequencesTable);
goFastaAlignment.Create();
var mutationsModel = new MutationsModel(this, idToSupply+"mutations_", infrastructure.ecsExecutionRole, infrastructure.volume, infrastructure.cluster, infrastructure.bucket, infrastructure.sequencesTable, infrastructure.mutationsTable);
mutationsModel.Create();
var pangolinModel = new PangolinModel(this, idToSupply+"pango_", infrastructure.ecsExecutionRole, infrastructure.volume, infrastructure.cluster, infrastructure.bucket, infrastructure.sequencesTable);
pangolinModel.Create();
var armadillinModel = new ArmadillinModel(this, idToSupply+"armadillin_", infrastructure.ecsExecutionRole, infrastructure.volume, infrastructure.cluster, infrastructure.bucket, infrastructure.sequencesTable);
armadillinModel.Create();
var genotypeVariantsModel = new GenotypeVariantsModel(this, idToSupply+"genotype_", infrastructure.ecsExecutionRole, infrastructure.volume, infrastructure.cluster, infrastructure.bucket, infrastructure.sequencesTable);
genotypeVariantsModel.Create();
var exportResults = new ExportResults(this, idToSupply+"export_", infrastructure);
exportResults.Create();
var mergeExportFiles = new MergeExportFiles(this, idToSupply+"merge_", infrastructure);
mergeExportFiles.Create();
var exportDynamoDBTable = new ExportDynamoDBTable(this, idToSupply+"exportDynamo_", infrastructure);
exportDynamoDBTable.Create();
var stateMachines = new StateMachines(this, idToSupply+"stateMachine_", infrastructure, pangolinModel, armadillinModel, genotypeVariantsModel, mutationsModel, prepareSequences, goFastaAlignment, helperFunctions, exportResults, mergeExportFiles, exportDynamoDBTable);
stateMachines.Create();
}
}
internal sealed class TestClass: Construct
{
public TestClass(Construct scope, string id): base(scope, id)
{
}
}
} | 52.56962 | 414 | 0.748615 | [
"MIT"
] | msinno01/SARSCoV2HeronPipeline | heronPipeline/src/HeronPipeline/HeronPipelineStack.cs | 4,153 | C# |
// This file is auto-generated, don't edit it. Thanks.
using System;
using System.Collections.Generic;
using System.IO;
using Tea;
namespace AlibabaCloud.SDK.Ecs20140526.Models
{
public class CreateAutoSnapshotPolicyRequest : TeaModel {
[NameInMap("regionId")]
[Validation(Required=true)]
public string RegionId { get; set; }
[NameInMap("autoSnapshotPolicyName")]
[Validation(Required=false)]
public string AutoSnapshotPolicyName { get; set; }
[NameInMap("timePoints")]
[Validation(Required=true)]
public string TimePoints { get; set; }
[NameInMap("repeatWeekdays")]
[Validation(Required=true)]
public string RepeatWeekdays { get; set; }
[NameInMap("retentionDays")]
[Validation(Required=true)]
public int? RetentionDays { get; set; }
[NameInMap("EnableCrossRegionCopy")]
[Validation(Required=false)]
public bool? EnableCrossRegionCopy { get; set; }
[NameInMap("TargetCopyRegions")]
[Validation(Required=false)]
public string TargetCopyRegions { get; set; }
[NameInMap("CopiedSnapshotsRetentionDays")]
[Validation(Required=false)]
public int? CopiedSnapshotsRetentionDays { get; set; }
[NameInMap("Tag")]
[Validation(Required=false)]
public List<CreateAutoSnapshotPolicyRequestTag> Tag { get; set; }
public class CreateAutoSnapshotPolicyRequestTag : TeaModel {
[NameInMap("Key")]
[Validation(Required=true)]
public string Key { get; set; }
[NameInMap("Value")]
[Validation(Required=true)]
public string Value { get; set; }
}
}
}
| 28.786885 | 73 | 0.626424 | [
"Apache-2.0"
] | alibabacloud-sdk-swift/alibabacloud-sdk | ecs-20140526/csharp/core/Models/CreateAutoSnapshotPolicyRequest.cs | 1,756 | C# |
/*
* Copyright(c) 2016 - 2018 Puma Security, LLC (https://www.pumascan.com)
*
* Project Leader: Eric Johnson (eric.johnson@pumascan.com)
* Lead Developer: Eric Mead (eric.mead@pumascan.com)
*
* This Source Code Form is subject to the terms of the Mozilla Public
* License, v. 2.0. If a copy of the MPL was not distributed with this
* file, You can obtain one at http://mozilla.org/MPL/2.0/.
*/
using Microsoft.CodeAnalysis;
using Microsoft.CodeAnalysis.CSharp;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Puma.Security.Rules.Common;
namespace Puma.Security.Rules.Analyzer.Core
{
internal class IdentifierNameSyntaxAnalyzer : BaseSyntaxNodeAnalyzer<IdentifierNameSyntax>
{
private readonly ISanitizedSourceAnalyzer _sanitizedSourceAnalyzer;
private readonly ISafeSyntaxTypeAnalyzer _safeSyntaxTypeAnalyzer;
internal IdentifierNameSyntaxAnalyzer()
: this(
new SanitizedSourceAnalyzer(),
new SafeSyntaxTypeAnalyzer())
{
}
internal IdentifierNameSyntaxAnalyzer(ISanitizedSourceAnalyzer sanitizedSourceAnalyzer, ISafeSyntaxTypeAnalyzer safeSyntaxTypeAnalyzer)
{
_sanitizedSourceAnalyzer = sanitizedSourceAnalyzer;
_safeSyntaxTypeAnalyzer = safeSyntaxTypeAnalyzer;
}
public override bool CanIgnore(SemanticModel model, SyntaxNode syntax)
{
var identifierNameSyntax = syntax as IdentifierNameSyntax;
var symbolInfo = model.GetSymbolInfo(identifierNameSyntax);
if (_safeSyntaxTypeAnalyzer.IsSafeSyntaxType(symbolInfo))
return true;
return base.CanIgnore(model, syntax);
}
public override bool CanSuppress(SemanticModel model, SyntaxNode syntax, DiagnosticId ruleId)
{
var identifierNameSyntax = syntax as IdentifierNameSyntax;
var symbolInfo = model.GetSymbolInfo(identifierNameSyntax);
if (_sanitizedSourceAnalyzer.IsSymbolSanitized(symbolInfo, ruleId))
return true;
return base.CanSuppress(model, syntax, ruleId);
}
}
} | 35.540984 | 143 | 0.695111 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | denmilu/puma-scan_code-realtime-scan | Rules/Analyzer/Core/IdentifierNameSyntaxAnalyzer.cs | 2,168 | C# |
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2019 Datadog, Inc.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Serilog.Debugging;
using Serilog.Events;
using Serilog.Sinks.PeriodicBatching;
namespace Serilog.Sinks.Datadog.Logs
{
public class DatadogSink : PeriodicBatchingSink
{
private readonly IDatadogClient _client;
private readonly Action<Exception> _exceptionHandler;
/// <summary>
/// The time to wait before emitting a new event batch.
/// </summary>
private static readonly TimeSpan DefaultBatchPeriod = TimeSpan.FromSeconds(2);
/// <summary>
/// The maximum number of events to emit in a single batch.
/// </summary>
private const int DefaultBatchSizeLimit = 50;
public DatadogSink(string apiKey, string source, string service, string host, string[] tags, DatadogConfiguration config, int? batchSizeLimit = null, TimeSpan? batchPeriod = null, Action<Exception> exceptionHandler = null)
: base(batchSizeLimit ?? DefaultBatchSizeLimit, batchPeriod ?? DefaultBatchPeriod)
{
_client = CreateDatadogClient(apiKey, source, service, host, tags, config);
_exceptionHandler = exceptionHandler;
}
public DatadogSink(string apiKey, string source, string service, string host, string[] tags, DatadogConfiguration config, int queueLimit, int? batchSizeLimit = null, TimeSpan? batchPeriod = null, Action<Exception> exceptionHandler = null)
: base(batchSizeLimit ?? DefaultBatchSizeLimit, batchPeriod ?? DefaultBatchPeriod, queueLimit)
{
_client = CreateDatadogClient(apiKey, source, service, host, tags, config);
_exceptionHandler = exceptionHandler;
}
public static DatadogSink Create(string apiKey, string source, string service, string host, string[] tags, DatadogConfiguration config, int? batchSizeLimit = null, TimeSpan? batchPeriod = null, int? queueLimit = null, Action<Exception> exceptionHandler = null)
{
if (queueLimit.HasValue)
return new DatadogSink(apiKey, source, service, host, tags, config, queueLimit.Value, batchSizeLimit, batchPeriod, exceptionHandler);
return new DatadogSink(apiKey, source, service, host, tags, config, batchSizeLimit, batchPeriod, exceptionHandler);
}
/// <summary>
/// Emit a batch of log events to Datadog logs-backend.
/// </summary>
/// <param name="events">The events to emit.</param>
protected override async Task EmitBatchAsync(IEnumerable<LogEvent> events)
{
try
{
if (!events.Any())
{
return;
}
var task = _client.WriteAsync(events);
await RunTask(task);
}
catch (Exception e)
{
OnException(e);
}
}
/// <summary>
/// Free resources held by the sink.
/// </summary>
/// <param name="disposing">If true, called because the object is being disposed; if false,
/// the object is being disposed from the finalizer.</param>
protected override void Dispose(bool disposing)
{
_client.Close();
base.Dispose(disposing);
}
private static IDatadogClient CreateDatadogClient(string apiKey, string source, string service, string host, string[] tags, DatadogConfiguration configuration)
{
var logFormatter = new LogFormatter(source, service, host, tags);
if (configuration.UseTCP)
{
return new DatadogTcpClient(configuration, logFormatter, apiKey);
}
else
{
return new DatadogHttpClient(configuration, logFormatter, apiKey);
}
}
private async Task RunTask(Task task)
{
try
{
await task.ConfigureAwait(false);
}
catch
{
if (task?.Exception != null)
{
foreach (var innerException in task.Exception.InnerExceptions)
{
OnException(innerException);
}
}
else
{
throw;
}
}
}
private void OnException(Exception e)
{
if (_exceptionHandler != null)
{
_exceptionHandler(e);
}
SelfLog.WriteLine("{0}", e.Message);
}
}
}
| 37.371212 | 268 | 0.590716 | [
"Apache-2.0"
] | BartoszChrostowski/serilog-sinks-datadog-logs | src/Serilog.Sinks.Datadog.Logs/Sinks/Datadog/DatadogSink.cs | 4,935 | C# |
// *** WARNING: this file was generated by crd2pulumi. ***
// *** 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.Kubernetes.Types.Outputs.Enterprise.V1Alpha2
{
[OutputType]
public sealed class StandaloneSpecSparkRef
{
/// <summary>
/// API version of the referent.
/// </summary>
public readonly string ApiVersion;
/// <summary>
/// If referring to a piece of an object instead of an entire object, this string should contain a valid JSON/Go field access statement, such as desiredState.manifest.containers[2]. For example, if the object reference is to a container within a pod, this would take on a value like: "spec.containers{name}" (where "name" refers to the name of the container that triggered the event) or if no container name is specified "spec.containers[2]" (container with index 2 in this pod). This syntax is chosen only to have some well-defined way of referencing a part of an object. TODO: this design is not final and this field is subject to change in the future.
/// </summary>
public readonly string FieldPath;
/// <summary>
/// Kind of the referent. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#types-kinds
/// </summary>
public readonly string Kind;
/// <summary>
/// Name of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#names
/// </summary>
public readonly string Name;
/// <summary>
/// Namespace of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/namespaces/
/// </summary>
public readonly string Namespace;
/// <summary>
/// Specific resourceVersion to which this reference is made, if any. More info: https://git.k8s.io/community/contributors/devel/sig-architecture/api-conventions.md#concurrency-control-and-consistency
/// </summary>
public readonly string ResourceVersion;
/// <summary>
/// UID of the referent. More info: https://kubernetes.io/docs/concepts/overview/working-with-objects/names/#uids
/// </summary>
public readonly string Uid;
[OutputConstructor]
private StandaloneSpecSparkRef(
string apiVersion,
string fieldPath,
string kind,
string name,
string @namespace,
string resourceVersion,
string uid)
{
ApiVersion = apiVersion;
FieldPath = fieldPath;
Kind = kind;
Name = name;
Namespace = @namespace;
ResourceVersion = resourceVersion;
Uid = uid;
}
}
}
| 41.985915 | 662 | 0.649446 | [
"Apache-2.0"
] | pulumi/pulumi-kubernetes-crds | operators/splunk/dotnet/Kubernetes/Crds/Operators/Splunk/Enterprise/V1Alpha2/Outputs/StandaloneSpecSparkRef.cs | 2,981 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Text.Internal;
using System.Text.Unicode;
using Xunit;
namespace System.Text.Encodings.Web.Tests
{
internal static class TextEncoderSettingsExtensions
{
public static AllowedCharactersBitmap GetAllowedCharacters(this TextEncoderSettings settings)
{
object bitmap = settings.GetType().InvokeMember("GetAllowedCharacters", BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.InvokeMethod, null, settings, null);
object underlyingArray = bitmap.GetType().GetField("_allowedCharacters", BindingFlags.Instance | BindingFlags.NonPublic).GetValue(bitmap);
return (AllowedCharactersBitmap)typeof(AllowedCharactersBitmap).GetConstructor(BindingFlags.NonPublic | BindingFlags.Instance, null, new Type[] { typeof(uint[]) }, null).Invoke(new object[] { underlyingArray });
}
public static bool IsCharacterAllowed(this TextEncoderSettings settings, char character)
{
return GetAllowedCharacters(settings).IsCharacterAllowed(character);
}
}
public class TextEncoderSettingsTests
{
[Fact]
public void Ctor_Parameterless_CreatesEmptyFilter()
{
var filter = new TextEncoderSettings();
Assert.Equal(0, filter.GetAllowedCodePoints().Count());
}
[Fact]
public void Ctor_OtherTextEncoderSettingsAsInterface()
{
// Arrange
var originalFilter = new OddTextEncoderSettings();
// Act
var newFilter = new TextEncoderSettings(originalFilter);
// Assert
for (int i = 0; i <= char.MaxValue; i++)
{
Assert.Equal((i % 2) == 1, newFilter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void Ctor_OtherTextEncoderSettingsAsConcreteType_Clones()
{
// Arrange
var originalFilter = new TextEncoderSettings();
originalFilter.AllowCharacter('x');
// Act
var newFilter = new TextEncoderSettings(originalFilter);
newFilter.AllowCharacter('y');
// Assert
Assert.True(originalFilter.IsCharacterAllowed('x'));
Assert.False(originalFilter.IsCharacterAllowed('y'));
Assert.True(newFilter.IsCharacterAllowed('x'));
Assert.True(newFilter.IsCharacterAllowed('y'));
}
[Fact]
public void Ctor_UnicodeRanges()
{
// Act
var filter = new TextEncoderSettings(UnicodeRanges.LatinExtendedA, UnicodeRanges.LatinExtendedC);
// Assert
for (int i = 0; i < 0x0100; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0100; i <= 0x017F; i++)
{
Assert.True(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0180; i < 0x2C60; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x2C60; i <= 0x2C7F; i++)
{
Assert.True(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x2C80; i <= char.MaxValue; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void Ctor_Null_UnicodeRanges()
{
Assert.Throws<ArgumentNullException>("allowedRanges", () => new TextEncoderSettings(default(UnicodeRange[])));
}
[Fact]
public void Ctor_Null_TextEncoderSettings()
{
Assert.Throws<ArgumentNullException>("other", () => new TextEncoderSettings(default(TextEncoderSettings)));
}
[Fact]
public void AllowChar()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowCharacter('\u0100');
// Assert
Assert.True(filter.IsCharacterAllowed('\u0100'));
Assert.False(filter.IsCharacterAllowed('\u0101'));
}
[Fact]
public void AllowChars_Array()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowCharacters('\u0100', '\u0102');
// Assert
Assert.True(filter.IsCharacterAllowed('\u0100'));
Assert.False(filter.IsCharacterAllowed('\u0101'));
Assert.True(filter.IsCharacterAllowed('\u0102'));
Assert.False(filter.IsCharacterAllowed('\u0103'));
}
[Fact]
public void AllowChars_String()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowCharacters('\u0100', '\u0102');
// Assert
Assert.True(filter.IsCharacterAllowed('\u0100'));
Assert.False(filter.IsCharacterAllowed('\u0101'));
Assert.True(filter.IsCharacterAllowed('\u0102'));
Assert.False(filter.IsCharacterAllowed('\u0103'));
}
[Fact]
public void AllowChars_Null()
{
TextEncoderSettings filter = new TextEncoderSettings();
Assert.Throws<ArgumentNullException>("characters", () => filter.AllowCharacters(null));
}
[Fact]
public void AllowFilter()
{
// Arrange
var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin);
filter.AllowCodePoints(new OddTextEncoderSettings().GetAllowedCodePoints());
// Assert
for (int i = 0; i <= 0x007F; i++)
{
Assert.True(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0080; i <= char.MaxValue; i++)
{
Assert.Equal((i % 2) == 1, filter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void AllowFilter_NullCodePoints()
{
TextEncoderSettings filter = new TextEncoderSettings(UnicodeRanges.BasicLatin);
Assert.Throws<ArgumentNullException>("codePoints", () => filter.AllowCodePoints(null));
}
[Fact]
public void AllowFilter_NonBMP()
{
TextEncoderSettings filter = new TextEncoderSettings();
filter.AllowCodePoints(Enumerable.Range(0x10000, 20));
Assert.Empty(filter.GetAllowedCodePoints());
}
[Fact]
public void AllowRange()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowRange(UnicodeRanges.LatinExtendedA);
// Assert
for (int i = 0; i < 0x0100; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0100; i <= 0x017F; i++)
{
Assert.True(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0180; i <= char.MaxValue; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void AllowRange_NullRange()
{
TextEncoderSettings filter = new TextEncoderSettings();
Assert.Throws<ArgumentNullException>("range", () => filter.AllowRange(null));
}
[Fact]
public void AllowRanges()
{
// Arrange
var filter = new TextEncoderSettings();
filter.AllowRanges(UnicodeRanges.LatinExtendedA, UnicodeRanges.LatinExtendedC);
// Assert
for (int i = 0; i < 0x0100; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0100; i <= 0x017F; i++)
{
Assert.True(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0180; i < 0x2C60; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x2C60; i <= 0x2C7F; i++)
{
Assert.True(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x2C80; i <= char.MaxValue; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void AllowRanges_NullRange()
{
TextEncoderSettings filter = new TextEncoderSettings();
Assert.Throws<ArgumentNullException>("ranges", () => filter.AllowRanges(null));
}
[Fact]
public void Clear()
{
// Arrange
var filter = new TextEncoderSettings();
for (int i = 1; i <= char.MaxValue; i++)
{
filter.AllowCharacter((char)i);
}
// Act
filter.Clear();
// Assert
for (int i = 0; i <= char.MaxValue; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void ForbidChar()
{
// Arrange
var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin);
filter.ForbidCharacter('x');
// Assert
Assert.True(filter.IsCharacterAllowed('w'));
Assert.False(filter.IsCharacterAllowed('x'));
Assert.True(filter.IsCharacterAllowed('y'));
Assert.True(filter.IsCharacterAllowed('z'));
}
[Fact]
public void ForbidChars_Array()
{
// Arrange
var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin);
filter.ForbidCharacters('x', 'z');
// Assert
Assert.True(filter.IsCharacterAllowed('w'));
Assert.False(filter.IsCharacterAllowed('x'));
Assert.True(filter.IsCharacterAllowed('y'));
Assert.False(filter.IsCharacterAllowed('z'));
}
[Fact]
public void ForbidChars_String()
{
// Arrange
var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin);
filter.ForbidCharacters('x', 'z');
// Assert
Assert.True(filter.IsCharacterAllowed('w'));
Assert.False(filter.IsCharacterAllowed('x'));
Assert.True(filter.IsCharacterAllowed('y'));
Assert.False(filter.IsCharacterAllowed('z'));
}
[Fact]
public void ForbidChars_Null()
{
TextEncoderSettings filter = new TextEncoderSettings(UnicodeRanges.BasicLatin);
Assert.Throws<ArgumentNullException>("characters", () => filter.ForbidCharacters(null));
}
[Fact]
public void ForbidRange()
{
// Arrange
var filter = new TextEncoderSettings(new OddTextEncoderSettings());
filter.ForbidRange(UnicodeRanges.Specials);
// Assert
for (int i = 0; i <= 0xFFEF; i++)
{
Assert.Equal((i % 2) == 1, filter.IsCharacterAllowed((char)i));
}
for (int i = 0xFFF0; i <= char.MaxValue; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void ForbidRange_Null()
{
TextEncoderSettings filter = new TextEncoderSettings();
Assert.Throws<ArgumentNullException>("range", () => filter.ForbidRange(null));
}
[Fact]
public void ForbidRanges()
{
// Arrange
var filter = new TextEncoderSettings(new OddTextEncoderSettings());
filter.ForbidRanges(UnicodeRanges.BasicLatin, UnicodeRanges.Specials);
// Assert
for (int i = 0; i <= 0x007F; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
for (int i = 0x0080; i <= 0xFFEF; i++)
{
Assert.Equal((i % 2) == 1, filter.IsCharacterAllowed((char)i));
}
for (int i = 0xFFF0; i <= char.MaxValue; i++)
{
Assert.False(filter.IsCharacterAllowed((char)i));
}
}
[Fact]
public void ForbidRanges_Null()
{
TextEncoderSettings filter = new TextEncoderSettings(new OddTextEncoderSettings());
Assert.Throws<ArgumentNullException>("ranges", () => filter.ForbidRanges(null));
}
[Fact]
public void GetAllowedCodePoints()
{
// Arrange
var expected = Enumerable.Range(UnicodeRanges.BasicLatin.FirstCodePoint, UnicodeRanges.BasicLatin.Length)
.Concat(Enumerable.Range(UnicodeRanges.Specials.FirstCodePoint, UnicodeRanges.Specials.Length))
.Except(new int[] { 'x' })
.OrderBy(i => i)
.ToArray();
var filter = new TextEncoderSettings(UnicodeRanges.BasicLatin, UnicodeRanges.Specials);
filter.ForbidCharacter('x');
// Act
var retVal = filter.GetAllowedCodePoints().OrderBy(i => i).ToArray();
// Assert
Assert.Equal<int>(expected, retVal);
}
// a code point filter which allows only odd code points through
private sealed class OddTextEncoderSettings : TextEncoderSettings
{
public override IEnumerable<int> GetAllowedCodePoints()
{
for (int i = 1; i <= char.MaxValue; i += 2)
{
yield return i;
}
}
}
}
}
| 33.327751 | 223 | 0.543249 | [
"MIT"
] | 2m0nd/runtime | src/libraries/System.Text.Encodings.Web/tests/TextEncoderSettingsTests.cs | 13,931 | 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.Rds.Model.V20140815;
namespace Aliyun.Acs.Rds.Transform.V20140815
{
public class DescribeDBInstanceIPArrayListResponseUnmarshaller
{
public static DescribeDBInstanceIPArrayListResponse Unmarshall(UnmarshallerContext _ctx)
{
DescribeDBInstanceIPArrayListResponse describeDBInstanceIPArrayListResponse = new DescribeDBInstanceIPArrayListResponse();
describeDBInstanceIPArrayListResponse.HttpResponse = _ctx.HttpResponse;
describeDBInstanceIPArrayListResponse.RequestId = _ctx.StringValue("DescribeDBInstanceIPArrayList.RequestId");
List<DescribeDBInstanceIPArrayListResponse.DescribeDBInstanceIPArrayList_DBInstanceIPArray> describeDBInstanceIPArrayListResponse_items = new List<DescribeDBInstanceIPArrayListResponse.DescribeDBInstanceIPArrayList_DBInstanceIPArray>();
for (int i = 0; i < _ctx.Length("DescribeDBInstanceIPArrayList.Items.Length"); i++) {
DescribeDBInstanceIPArrayListResponse.DescribeDBInstanceIPArrayList_DBInstanceIPArray dBInstanceIPArray = new DescribeDBInstanceIPArrayListResponse.DescribeDBInstanceIPArrayList_DBInstanceIPArray();
dBInstanceIPArray.DBInstanceIPArrayName = _ctx.StringValue("DescribeDBInstanceIPArrayList.Items["+ i +"].DBInstanceIPArrayName");
dBInstanceIPArray.DBInstanceIPArrayAttribute = _ctx.StringValue("DescribeDBInstanceIPArrayList.Items["+ i +"].DBInstanceIPArrayAttribute");
dBInstanceIPArray.SecurityIPType = _ctx.StringValue("DescribeDBInstanceIPArrayList.Items["+ i +"].SecurityIPType");
dBInstanceIPArray.SecurityIPList = _ctx.StringValue("DescribeDBInstanceIPArrayList.Items["+ i +"].SecurityIPList");
dBInstanceIPArray.WhitelistNetworkType = _ctx.StringValue("DescribeDBInstanceIPArrayList.Items["+ i +"].WhitelistNetworkType");
describeDBInstanceIPArrayListResponse_items.Add(dBInstanceIPArray);
}
describeDBInstanceIPArrayListResponse.Items = describeDBInstanceIPArrayListResponse_items;
return describeDBInstanceIPArrayListResponse;
}
}
}
| 55.132075 | 240 | 0.804244 | [
"Apache-2.0"
] | AxiosCros/aliyun-openapi-net-sdk | aliyun-net-sdk-rds/Rds/Transform/V20140815/DescribeDBInstanceIPArrayListResponseUnmarshaller.cs | 2,922 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
// Runtime Version:4.0.30319.261
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace ImageStreaming.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", "4.0.0.0")]
[global::System.Diagnostics.DebuggerNonUserCodeAttribute()]
[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
internal class Resources {
private static global::System.Resources.ResourceManager resourceMan;
private static global::System.Globalization.CultureInfo resourceCulture;
[global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal Resources() {
}
/// <summary>
/// Returns the cached ResourceManager instance used by this class.
/// </summary>
[global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)]
internal static global::System.Resources.ResourceManager ResourceManager {
get {
if (object.ReferenceEquals(resourceMan, null)) {
global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ImageStreaming.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;
}
}
}
}
| 44.5625 | 181 | 0.600281 | [
"Apache-2.0"
] | SNBnani/Xian | ImageServer/TestApp/ImageStreaming/Properties/Resources.Designer.cs | 2,854 | 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("Ragnarok.DA")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Ragnarok.DA")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("66e5305a-0585-4d38-b35e-b5dcd8b4e296")]
// 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 Revision and Build Numbers
// by using the '*' as shown below:
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.638889 | 84 | 0.746863 | [
"MIT"
] | DiaPasc/ragnarok | Ragnarok.DA/Properties/AssemblyInfo.cs | 1,358 | C# |
using System;
using Blitzy.Tests.Mocks;
using log4net.Core;
using Microsoft.VisualStudio.TestTools.UnitTesting;
namespace Blitzy.Tests.Global
{
[TestClass]
[System.Diagnostics.CodeAnalysis.ExcludeFromCodeCoverage]
public class LogTests : TestBase
{
[TestMethod, TestCategory( "Global" )]
public void LogHelperTest()
{
Type type = GetType();
using( LogChecker log = new LogChecker( Level.Fatal ) )
{
LogHelper.LogDebug( type, "Debug" );
LogHelper.LogInfo( type, "Info" );
LogHelper.LogWarning( type, "Warning" );
LogHelper.LogError( type, "Error" );
LogHelper.LogFatal( type, "Fatal" );
Assert.AreEqual( 1, log.Messages.Count );
Assert.AreEqual( "Fatal", log.Messages[0] );
}
using( LogChecker log = new LogChecker( Level.Error ) )
{
LogHelper.LogDebug( type, "Debug" );
LogHelper.LogInfo( type, "Info" );
LogHelper.LogWarning( type, "Warning" );
LogHelper.LogError( type, "Error" );
LogHelper.LogFatal( type, "Fatal" );
Assert.AreEqual( 2, log.Messages.Count );
Assert.AreEqual( "Error", log.Messages[0] );
Assert.AreEqual( "Fatal", log.Messages[1] );
}
using( LogChecker log = new LogChecker( Level.Warn ) )
{
LogHelper.LogDebug( type, "Debug" );
LogHelper.LogInfo( type, "Info" );
LogHelper.LogWarning( type, "Warning" );
LogHelper.LogError( type, "Error" );
LogHelper.LogFatal( type, "Fatal" );
Assert.AreEqual( 3, log.Messages.Count );
Assert.AreEqual( "Warning", log.Messages[0] );
Assert.AreEqual( "Error", log.Messages[1] );
Assert.AreEqual( "Fatal", log.Messages[2] );
}
using( LogChecker log = new LogChecker( Level.Info ) )
{
LogHelper.LogDebug( type, "Debug" );
LogHelper.LogInfo( type, "Info" );
LogHelper.LogWarning( type, "Warning" );
LogHelper.LogError( type, "Error" );
LogHelper.LogFatal( type, "Fatal" );
Assert.AreEqual( 4, log.Messages.Count );
Assert.AreEqual( "Info", log.Messages[0] );
Assert.AreEqual( "Warning", log.Messages[1] );
Assert.AreEqual( "Error", log.Messages[2] );
Assert.AreEqual( "Fatal", log.Messages[3] );
}
using( LogChecker log = new LogChecker( Level.Debug ) )
{
LogHelper.LogDebug( type, "Debug" );
LogHelper.LogInfo( type, "Info" );
LogHelper.LogWarning( type, "Warning" );
LogHelper.LogError( type, "Error" );
LogHelper.LogFatal( type, "Fatal" );
Assert.AreEqual( 5, log.Messages.Count );
Assert.AreEqual( "Debug", log.Messages[0] );
Assert.AreEqual( "Info", log.Messages[1] );
Assert.AreEqual( "Warning", log.Messages[2] );
Assert.AreEqual( "Error", log.Messages[3] );
Assert.AreEqual( "Fatal", log.Messages[4] );
}
}
[TestMethod, TestCategory( "Global" )]
public void LogObjectTest()
{
using( MockLogObject obj = new MockLogObject() )
{
using( LogChecker log = new LogChecker( Level.Fatal ) )
{
obj.Debug( "Debug" );
obj.Info( "Info" );
obj.Warning( "Warning" );
obj.Error( "Error" );
obj.Fatal( "Fatal" );
Assert.AreEqual( 1, log.Messages.Count );
Assert.AreEqual( "Fatal", log.Messages[0] );
}
using( LogChecker log = new LogChecker( Level.Error ) )
{
obj.Debug( "Debug" );
obj.Info( "Info" );
obj.Warning( "Warning" );
obj.Error( "Error" );
obj.Fatal( "Fatal" );
Assert.AreEqual( 2, log.Messages.Count );
Assert.AreEqual( "Error", log.Messages[0] );
Assert.AreEqual( "Fatal", log.Messages[1] );
}
using( LogChecker log = new LogChecker( Level.Warn ) )
{
obj.Debug( "Debug" );
obj.Info( "Info" );
obj.Warning( "Warning" );
obj.Error( "Error" );
obj.Fatal( "Fatal" );
Assert.AreEqual( 3, log.Messages.Count );
Assert.AreEqual( "Warning", log.Messages[0] );
Assert.AreEqual( "Error", log.Messages[1] );
Assert.AreEqual( "Fatal", log.Messages[2] );
}
using( LogChecker log = new LogChecker( Level.Info ) )
{
obj.Debug( "Debug" );
obj.Info( "Info" );
obj.Warning( "Warning" );
obj.Error( "Error" );
obj.Fatal( "Fatal" );
Assert.AreEqual( 4, log.Messages.Count );
Assert.AreEqual( "Info", log.Messages[0] );
Assert.AreEqual( "Warning", log.Messages[1] );
Assert.AreEqual( "Error", log.Messages[2] );
Assert.AreEqual( "Fatal", log.Messages[3] );
}
using( LogChecker log = new LogChecker( Level.Debug ) )
{
obj.Debug( "Debug" );
obj.Info( "Info" );
obj.Warning( "Warning" );
obj.Error( "Error" );
obj.Fatal( "Fatal" );
Assert.AreEqual( 5, log.Messages.Count );
Assert.AreEqual( "Debug", log.Messages[0] );
Assert.AreEqual( "Info", log.Messages[1] );
Assert.AreEqual( "Warning", log.Messages[2] );
Assert.AreEqual( "Error", log.Messages[3] );
Assert.AreEqual( "Fatal", log.Messages[4] );
}
}
}
[TestMethod, TestCategory( "ViewModel" )]
public void ViewModelLogTests()
{
using( MockViewModel obj = new MockViewModel( "test" ) )
{
using( LogChecker log = new LogChecker( Level.Fatal ) )
{
obj.Debug( "Debug" );
obj.Info( "Info" );
obj.Warning( "Warning" );
obj.Error( "Error" );
obj.Fatal( "Fatal" );
Assert.AreEqual( 1, log.Messages.Count );
Assert.AreEqual( "Fatal", log.Messages[0] );
}
using( LogChecker log = new LogChecker( Level.Error ) )
{
obj.Debug( "Debug" );
obj.Info( "Info" );
obj.Warning( "Warning" );
obj.Error( "Error" );
obj.Fatal( "Fatal" );
Assert.AreEqual( 2, log.Messages.Count );
Assert.AreEqual( "Error", log.Messages[0] );
Assert.AreEqual( "Fatal", log.Messages[1] );
}
using( LogChecker log = new LogChecker( Level.Warn ) )
{
obj.Debug( "Debug" );
obj.Info( "Info" );
obj.Warning( "Warning" );
obj.Error( "Error" );
obj.Fatal( "Fatal" );
Assert.AreEqual( 3, log.Messages.Count );
Assert.AreEqual( "Warning", log.Messages[0] );
Assert.AreEqual( "Error", log.Messages[1] );
Assert.AreEqual( "Fatal", log.Messages[2] );
}
using( LogChecker log = new LogChecker( Level.Info ) )
{
obj.Debug( "Debug" );
obj.Info( "Info" );
obj.Warning( "Warning" );
obj.Error( "Error" );
obj.Fatal( "Fatal" );
Assert.AreEqual( 4, log.Messages.Count );
Assert.AreEqual( "Info", log.Messages[0] );
Assert.AreEqual( "Warning", log.Messages[1] );
Assert.AreEqual( "Error", log.Messages[2] );
Assert.AreEqual( "Fatal", log.Messages[3] );
}
using( LogChecker log = new LogChecker( Level.Debug ) )
{
obj.Debug( "Debug" );
obj.Info( "Info" );
obj.Warning( "Warning" );
obj.Error( "Error" );
obj.Fatal( "Fatal" );
Assert.AreEqual( 5, log.Messages.Count );
Assert.AreEqual( "Debug", log.Messages[0] );
Assert.AreEqual( "Info", log.Messages[1] );
Assert.AreEqual( "Warning", log.Messages[2] );
Assert.AreEqual( "Error", log.Messages[3] );
Assert.AreEqual( "Fatal", log.Messages[4] );
}
}
}
}
} | 29.347107 | 59 | 0.601521 | [
"MIT"
] | TheSylence/Blitzy_old | Blitzy.Tests/Tests/LogTests.cs | 7,104 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace LoRaWan.Tests.Unit.LoRaWanTests
{
using System;
using LoRaTools.Utils;
using Xunit;
/// <summary>
/// Class to test the conversion helper class.
/// </summary>
public class ConversionHelperTest
{
/// <summary>
/// Check conversion helper.
/// </summary>
[Theory]
[InlineData(new byte[] { 1, 2, 3, 4 }, "01020304")]
[InlineData(new byte[] { 0xF1, 0xF2, 0xF3, 0xF4 }, "F1F2F3F4")]
public void Convert_Byte_Array_Should_Return_String(byte[] input, string expected)
{
var actual = ConversionHelper.ByteArrayToString(input);
Assert.Equal(expected, actual);
}
/// <summary>
/// Check conversion helper.
/// </summary>
[Theory]
[InlineData(new byte[] { 1, 2, 3, 4 }, "01020304")]
[InlineData(new byte[] { 0xF1, 0xF2, 0xF3, 0xF4 }, "F1F2F3F4")]
public void Convert_Byte_Memory_Should_Return_String(byte[] input, string expected)
{
var memory = new Memory<byte>(input);
var actual = ConversionHelper.ByteArrayToString(memory);
Assert.Equal(expected, actual);
}
}
}
| 33.170732 | 101 | 0.597794 | [
"MIT"
] | Mandur/iotedge-lorawan-starterk | Tests/Unit/LoRaWanTests/ConversionHelperTest.cs | 1,360 | C# |
using DynamicVsStaticCode.WinPhone.Resources;
namespace DynamicVsStaticCode.WinPhone
{
/// <summary>
/// Provides access to string resources.
/// </summary>
public class LocalizedStrings
{
private static AppResources _localizedResources = new AppResources();
public AppResources LocalizedResources { get { return _localizedResources; } }
}
}
| 25.666667 | 86 | 0.706494 | [
"Apache-2.0"
] | NoleHealth/xamarin-forms-book-preview-2 | Chapter11/DynamicVsStaticCode/DynamicVsStaticCode/DynamicVsStaticCode.WinPhone/LocalizedStrings.cs | 387 | C# |
using System;
using UnityEngine;
namespace Shooter.Scripts
{
[Serializable]
public class AgentStats
{
[SerializeField] private int _maxHp = 20;
[SerializeField] private float _shootDelay = 0.2f;
[SerializeField] private int _defaultDamageAmount = 5;
[SerializeField] private float _movementSpeed = 10f;
[SerializeField] private float _rotationSpeed = 10f;
public float LastShotTime { get; set; }
public int CurrentHp { get; set; }
public int DefaultDamageAmount => _defaultDamageAmount;
public float ShootDelay => _shootDelay;
public float MovementSpeed => _movementSpeed;
public float RotationSpeed => _rotationSpeed;
public int MAXHp => _maxHp;
public bool IsDead()
{
return CurrentHp <= 0;
}
public bool CanShoot()
{
return LastShotTime > ShootDelay;
}
public void Reset()
{
CurrentHp = _maxHp;
LastShotTime = 0f;
}
public void Tick()
{
LastShotTime += Time.deltaTime;
}
}
}
| 23.16 | 63 | 0.583765 | [
"Apache-2.0"
] | Ragueel/ml-agents | Project/Assets/Shooter/Scripts/Stats/AgentStats.cs | 1,160 | C# |
using System.Xml.Serialization;
using static openTRANS.Common;
namespace openTRANS
{
public partial class ProductId
{
[XmlElement("SUPPLIER_PID", Namespace = Common.Namespace.bmecat)]
public string SupplierPid;
[XmlElement("BUYER_PID", Namespace = Common.Namespace.bmecat)]
public TypedItem BuyerPid = new TypedItem();
[XmlElement("DESCRIPTION_SHORT", Namespace = Common.Namespace.bmecat)]
public string DescriptionShort;
[XmlElement("DESCRIPTION_LONG", Namespace = Common.Namespace.bmecat)]
public string DescriptionLong;
}
}
| 27.681818 | 78 | 0.697865 | [
"MIT"
] | DXSdata/openTRANS | openTRANS/SHARED/ProductId.cs | 611 | 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 ZuLuCommerce.Models
{
using System;
using System.Collections.Generic;
public partial class Picture
{
public int Id { get; set; }
public int ProductId { get; set; }
public string URL { get; set; }
public virtual Product Product { get; set; }
}
}
| 30.875 | 85 | 0.504723 | [
"Apache-2.0"
] | lequanganhkhuong/eProject-Sem3 | eProject-Sem3/ZuLuCommerce/ZuLuCommerce/Models/Picture.cs | 741 | C# |
using Autofac;
using Dal;
using WebApplication.Helpers;
namespace WebApplication
{
public class DefaultModule : Module
{
protected override void Load(ContainerBuilder builder)
{
//builder.RegisterInstance<IUserStore>(new UserStoreLocal()).SingleInstance();
builder.Register<UserStoreLocal>(c => new UserStoreLocal()).As<IUserStore>().SingleInstance();
builder.RegisterType<Authenticator>().As<IAuthenticator>();
}
}
}
| 28.352941 | 106 | 0.688797 | [
"MIT"
] | duongphuhiep/chatasp | src/webapp/DefaultModule.cs | 482 | C# |
/*
* Copyright 2010-2014 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 health-2016-08-04.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.AWSHealth.Model
{
/// <summary>
/// This is the response object from the DescribeEventAggregates operation.
/// </summary>
public partial class DescribeEventAggregatesResponse : AmazonWebServiceResponse
{
private List<EventAggregate> _eventAggregates = new List<EventAggregate>();
private string _nextToken;
/// <summary>
/// Gets and sets the property EventAggregates.
/// <para>
/// The number of events in each category that meet the optional filter criteria.
/// </para>
/// </summary>
public List<EventAggregate> EventAggregates
{
get { return this._eventAggregates; }
set { this._eventAggregates = value; }
}
// Check to see if EventAggregates property is set
internal bool IsSetEventAggregates()
{
return this._eventAggregates != null && this._eventAggregates.Count > 0;
}
/// <summary>
/// Gets and sets the property NextToken.
/// <para>
/// If the results of a search are large, only a portion of the results are returned,
/// and a <code>nextToken</code> pagination token is returned in the response. To retrieve
/// the next batch of results, reissue the search request and include the returned token.
/// When all results have been returned, the response does not contain a pagination token
/// value.
/// </para>
/// </summary>
public string NextToken
{
get { return this._nextToken; }
set { this._nextToken = value; }
}
// Check to see if NextToken property is set
internal bool IsSetNextToken()
{
return this._nextToken != null;
}
}
} | 34.164557 | 104 | 0.645054 | [
"Apache-2.0"
] | Bio2hazard/aws-sdk-net | sdk/src/Services/AWSHealth/Generated/Model/DescribeEventAggregatesResponse.cs | 2,699 | 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("03.CountSameValuesInArray")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("03.CountSameValuesInArray")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("d595cb96-5797-4df1-bf4b-7abb3a8f30c4")]
// 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.459459 | 84 | 0.748419 | [
"MIT"
] | George221b/SoftUni-Taks | C#Advanced/02.SetsAndDictionariesLab/03.CountSameValuesInArray/Properties/AssemblyInfo.cs | 1,426 | C# |
/*
* Copyright 2010-2014 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 firehose-2015-08-04.normal.json service model.
*/
using System;
using System.Collections.Generic;
using System.Xml.Serialization;
using System.Text;
using System.IO;
using Amazon.Runtime;
using Amazon.Runtime.Internal;
namespace Amazon.KinesisFirehose.Model
{
/// <summary>
/// Describes a destination in Amazon S3.
/// </summary>
public partial class ExtendedS3DestinationDescription
{
private string _bucketARN;
private BufferingHints _bufferingHints;
private CloudWatchLoggingOptions _cloudWatchLoggingOptions;
private CompressionFormat _compressionFormat;
private DataFormatConversionConfiguration _dataFormatConversionConfiguration;
private EncryptionConfiguration _encryptionConfiguration;
private string _errorOutputPrefix;
private string _prefix;
private ProcessingConfiguration _processingConfiguration;
private string _roleARN;
private S3DestinationDescription _s3BackupDescription;
private S3BackupMode _s3BackupMode;
/// <summary>
/// Gets and sets the property BucketARN.
/// <para>
/// The ARN of the S3 bucket. For more information, see <a href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon
/// Resource Names (ARNs) and AWS Service Namespaces</a>.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=2048)]
public string BucketARN
{
get { return this._bucketARN; }
set { this._bucketARN = value; }
}
// Check to see if BucketARN property is set
internal bool IsSetBucketARN()
{
return this._bucketARN != null;
}
/// <summary>
/// Gets and sets the property BufferingHints.
/// <para>
/// The buffering option.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public BufferingHints BufferingHints
{
get { return this._bufferingHints; }
set { this._bufferingHints = value; }
}
// Check to see if BufferingHints property is set
internal bool IsSetBufferingHints()
{
return this._bufferingHints != null;
}
/// <summary>
/// Gets and sets the property CloudWatchLoggingOptions.
/// <para>
/// The Amazon CloudWatch logging options for your delivery stream.
/// </para>
/// </summary>
public CloudWatchLoggingOptions CloudWatchLoggingOptions
{
get { return this._cloudWatchLoggingOptions; }
set { this._cloudWatchLoggingOptions = value; }
}
// Check to see if CloudWatchLoggingOptions property is set
internal bool IsSetCloudWatchLoggingOptions()
{
return this._cloudWatchLoggingOptions != null;
}
/// <summary>
/// Gets and sets the property CompressionFormat.
/// <para>
/// The compression format. If no value is specified, the default is <code>UNCOMPRESSED</code>.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public CompressionFormat CompressionFormat
{
get { return this._compressionFormat; }
set { this._compressionFormat = value; }
}
// Check to see if CompressionFormat property is set
internal bool IsSetCompressionFormat()
{
return this._compressionFormat != null;
}
/// <summary>
/// Gets and sets the property DataFormatConversionConfiguration.
/// <para>
/// The serializer, deserializer, and schema for converting data from the JSON format
/// to the Parquet or ORC format before writing it to Amazon S3.
/// </para>
/// </summary>
public DataFormatConversionConfiguration DataFormatConversionConfiguration
{
get { return this._dataFormatConversionConfiguration; }
set { this._dataFormatConversionConfiguration = value; }
}
// Check to see if DataFormatConversionConfiguration property is set
internal bool IsSetDataFormatConversionConfiguration()
{
return this._dataFormatConversionConfiguration != null;
}
/// <summary>
/// Gets and sets the property EncryptionConfiguration.
/// <para>
/// The encryption configuration. If no value is specified, the default is no encryption.
/// </para>
/// </summary>
[AWSProperty(Required=true)]
public EncryptionConfiguration EncryptionConfiguration
{
get { return this._encryptionConfiguration; }
set { this._encryptionConfiguration = value; }
}
// Check to see if EncryptionConfiguration property is set
internal bool IsSetEncryptionConfiguration()
{
return this._encryptionConfiguration != null;
}
/// <summary>
/// Gets and sets the property ErrorOutputPrefix.
/// <para>
/// A prefix that Kinesis Data Firehose evaluates and adds to failed records before writing
/// them to S3. This prefix appears immediately following the bucket name. For information
/// about how to specify this prefix, see <a href="https://docs.aws.amazon.com/firehose/latest/dev/s3-prefixes.html">Custom
/// Prefixes for Amazon S3 Objects</a>.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=1024)]
public string ErrorOutputPrefix
{
get { return this._errorOutputPrefix; }
set { this._errorOutputPrefix = value; }
}
// Check to see if ErrorOutputPrefix property is set
internal bool IsSetErrorOutputPrefix()
{
return this._errorOutputPrefix != null;
}
/// <summary>
/// Gets and sets the property Prefix.
/// <para>
/// The "YYYY/MM/DD/HH" time format prefix is automatically used for delivered Amazon
/// S3 files. You can also specify a custom prefix, as described in <a href="https://docs.aws.amazon.com/firehose/latest/dev/s3-prefixes.html">Custom
/// Prefixes for Amazon S3 Objects</a>.
/// </para>
/// </summary>
[AWSProperty(Min=0, Max=1024)]
public string Prefix
{
get { return this._prefix; }
set { this._prefix = value; }
}
// Check to see if Prefix property is set
internal bool IsSetPrefix()
{
return this._prefix != null;
}
/// <summary>
/// Gets and sets the property ProcessingConfiguration.
/// <para>
/// The data processing configuration.
/// </para>
/// </summary>
public ProcessingConfiguration ProcessingConfiguration
{
get { return this._processingConfiguration; }
set { this._processingConfiguration = value; }
}
// Check to see if ProcessingConfiguration property is set
internal bool IsSetProcessingConfiguration()
{
return this._processingConfiguration != null;
}
/// <summary>
/// Gets and sets the property RoleARN.
/// <para>
/// The Amazon Resource Name (ARN) of the AWS credentials. For more information, see <a
/// href="https://docs.aws.amazon.com/general/latest/gr/aws-arns-and-namespaces.html">Amazon
/// Resource Names (ARNs) and AWS Service Namespaces</a>.
/// </para>
/// </summary>
[AWSProperty(Required=true, Min=1, Max=512)]
public string RoleARN
{
get { return this._roleARN; }
set { this._roleARN = value; }
}
// Check to see if RoleARN property is set
internal bool IsSetRoleARN()
{
return this._roleARN != null;
}
/// <summary>
/// Gets and sets the property S3BackupDescription.
/// <para>
/// The configuration for backup in Amazon S3.
/// </para>
/// </summary>
public S3DestinationDescription S3BackupDescription
{
get { return this._s3BackupDescription; }
set { this._s3BackupDescription = value; }
}
// Check to see if S3BackupDescription property is set
internal bool IsSetS3BackupDescription()
{
return this._s3BackupDescription != null;
}
/// <summary>
/// Gets and sets the property S3BackupMode.
/// <para>
/// The Amazon S3 backup mode.
/// </para>
/// </summary>
public S3BackupMode S3BackupMode
{
get { return this._s3BackupMode; }
set { this._s3BackupMode = value; }
}
// Check to see if S3BackupMode property is set
internal bool IsSetS3BackupMode()
{
return this._s3BackupMode != null;
}
}
} | 34.839858 | 157 | 0.602758 | [
"Apache-2.0"
] | NGL321/aws-sdk-net | sdk/src/Services/KinesisFirehose/Generated/Model/ExtendedS3DestinationDescription.cs | 9,790 | 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.Reflection;
using Contoso.GameNetCore.Builder;
using Contoso.GameNetCore.Builder.Internal;
using Contoso.GameNetCore.Hosting.Internal;
using Microsoft.Extensions.DependencyInjection;
using Xunit;
namespace Contoso.GameNetCore.Hosting.Tests
{
public class ConfigureBuilderTests
{
[Fact]
public void CapturesServiceExceptionDetails()
{
var methodInfo = GetType().GetMethod(nameof(InjectedMethod), BindingFlags.NonPublic | BindingFlags.Static);
Assert.NotNull(methodInfo);
var services = new ServiceCollection()
.AddSingleton<CrasherService>()
.BuildServiceProvider();
var applicationBuilder = new ApplicationBuilder(services);
var builder = new ConfigureBuilder(methodInfo);
Action<IApplicationBuilder> action = builder.Build(instance:null);
var ex = Assert.Throws<Exception>(() => action.Invoke(applicationBuilder));
Assert.NotNull(ex);
Assert.Equal($"Could not resolve a service of type '{typeof(CrasherService).FullName}' for the parameter"
+ $" 'service' of method '{methodInfo.Name}' on type '{methodInfo.DeclaringType.FullName}'.", ex.Message);
// the inner exception contains the root cause
Assert.NotNull(ex.InnerException);
Assert.Equal("Service instantiation failed", ex.InnerException.Message);
Assert.Contains(nameof(CrasherService), ex.InnerException.StackTrace);
}
private static void InjectedMethod(CrasherService service)
{
Assert.NotNull(service);
}
private class CrasherService
{
public CrasherService()
{
throw new Exception("Service instantiation failed");
}
}
}
} | 38.163636 | 123 | 0.639828 | [
"Apache-2.0"
] | bclnet/GameNetCore | src/Hosting/Hosting/test/ConfigureBuilderTests.cs | 2,099 | C# |
using Newtonsoft.Json;
namespace Akinator.Api.Net.Model.External
{
internal class NewGameParameters : IBaseParameters
{
[JsonProperty("identification")]
internal Identification Identification { get; set; }
[JsonProperty("step_information")]
public Question StepInformation { get; set; }
}
} | 25.923077 | 60 | 0.68546 | [
"MIT"
] | Forevka/Akinator.Api.Net | Akinator.Api.Net/Model/External/NewGameParameters.cs | 339 | C# |
// Copyright 2007-2011 Chris Patterson, Dru Sellers, Travis Smith, et. al.
//
// 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 MassTransit.Exceptions
{
using System;
using System.Runtime.Serialization;
[Serializable]
public class MassTransitException : Exception
{
public MassTransitException()
{
}
public MassTransitException(string message)
: base(message)
{
}
public MassTransitException(string message, Exception innerException)
: base(message, innerException)
{
}
protected MassTransitException(SerializationInfo info, StreamingContext context)
: base(info, context)
{
}
}
} | 32.55 | 89 | 0.650538 | [
"Apache-2.0"
] | SeanKilleen/MassTransit | src/MassTransit/Exceptions/MassTransitException.cs | 1,302 | C# |
using Castle.DynamicProxy;
using TddXt.AnyExtensibility;
using TddXt.AnyGenerators.AutoFixtureWrapper;
using TddXt.AnyGenerators.Generic;
using TddXt.TypeResolution;
using TddXt.TypeResolution.CustomCollections;
using TddXt.TypeResolution.FakeChainElements;
namespace TddXt.AnyGenerators.Root.ImplementationDetails
{
public static class AllGeneratorFactory
{
public static BasicGenerator Create()
{
var valueGenerator = CreateValueGenerator();
var proxyGenerator = new ProxyGenerator();
var cachedReturnValueGeneration = new CachedReturnValueGeneration(new PerMethodCache<object>());
var specialCasesOfResolutions = new SpecialCasesOfResolutions();
var fallbackTypeGenerator = new FallbackTypeGenerator(
new IFallbackGeneratedObjectCustomization[]
{
new FillPropertiesCustomization(),
new FillFieldsCustomization()
});
var resolutionsFactory = new ResolutionsFactory(
specialCasesOfResolutions, fallbackTypeGenerator);
var unconstrainedChain = new TemporaryChainForCollection(new[]
{
ResolutionsFactory.ResolveTheMostSpecificCases(valueGenerator),
resolutionsFactory.ResolveAsArray(),
resolutionsFactory.ResolveAsImmutableArray(),
resolutionsFactory.ResolveAsSimpleEnumerableAndList(),
resolutionsFactory.ResolveAsImmutableList(),
resolutionsFactory.ResolveAsSimpleSet(),
resolutionsFactory.ResolveAsImmutableHashSet(),
resolutionsFactory.ResolveAsImmutableSortedSet(),
resolutionsFactory.ResolveAsSimpleDictionary(),
resolutionsFactory.ResolveAsImmutableDictionary(),
resolutionsFactory.ResolveAsImmutableSortedDictionary(),
resolutionsFactory.ResolveAsSortedList(),
resolutionsFactory.ResolveAsImmutableQueue(),
resolutionsFactory.ResolveAsImmutableStack(),
ResolutionsFactory.ResolveAsDelegate(),
resolutionsFactory.ResolveAsSortedSet(),
resolutionsFactory.ResolveAsSortedDictionary(),
resolutionsFactory.ResolveAsConcurrentDictionary(),
resolutionsFactory.ResolveAsConcurrentBag(),
resolutionsFactory.ResolveAsConcurrentQueue(),
resolutionsFactory.ResolveAsConcurrentStack(),
resolutionsFactory.ResolveAsKeyValuePair(),
ResolutionsFactory.ResolveAsOptionalOption(),
resolutionsFactory.ResolveAsGenericEnumerator(),
ResolutionsFactory.ResolveAsObjectEnumerator(),
ResolutionsFactory.ResolveAsCollectionWithHeuristics(),
ResolutionsFactory.ResolveAsInterfaceImplementationWhere(
cachedReturnValueGeneration,
proxyGenerator),
resolutionsFactory.ResolveAsAbstractClassImplementationWhere(
cachedReturnValueGeneration,
proxyGenerator),
resolutionsFactory.ResolveAsConcreteTypeWithNonConcreteTypesInConstructorSignature(),
ResolutionsFactory.ResolveAsVoidTask(),
ResolutionsFactory.ResolveAsTypedTask(),
resolutionsFactory.ResolveAsConcreteClass()
});
var limitedGenerationChain = new LimitedGenerationChain(unconstrainedChain);
var fakeOrdinaryInterfaceGenerator = new FakeOrdinaryInterface(cachedReturnValueGeneration, proxyGenerator);
var allGenerator = new AllGenerator(
valueGenerator,
limitedGenerationChain,
unconstrainedChain,
fakeOrdinaryInterfaceGenerator);
return allGenerator;
}
private static ValueGenerator CreateValueGenerator()
{
var fixtureWrapper = FixtureWrapper.CreateUnconfiguredInstance();
var fixtureConfiguration = new AutoFixtureConfiguration();
fixtureConfiguration.ApplyTo(fixtureWrapper);
var valueGenerator = new ValueGenerator(fixtureWrapper);
return valueGenerator;
}
}
}
| 43.602273 | 114 | 0.755799 | [
"MIT"
] | grzesiek-galezowski/any | src/netstandard2.0/AnyGenerators/Root/ImplementationDetails/AllGeneratorFactory.cs | 3,839 | C# |
namespace BuddyApiClient.Projects.Models
{
internal static class StatusJsonConverter
{
public const string ActiveAsJson = "ACTIVE";
public const string ClosedAsJson = "CLOSED";
public static Status ConvertFrom(string? json)
{
return json switch
{
ActiveAsJson => Status.Active,
ClosedAsJson => Status.Closed,
_ => throw new NotSupportedException()
};
}
public static string ConvertTo(Status? enumValue)
{
return enumValue switch
{
Status.Active => ActiveAsJson,
Status.Closed => ClosedAsJson,
_ => throw new NotSupportedException()
};
}
}
} | 28.107143 | 57 | 0.532402 | [
"MIT"
] | logikfabrik/BuddyApiClient | src/BuddyApiClient/Projects/Models/StatusJsonConverter.cs | 789 | C# |
// <auto-generated />
namespace GigHub.Migrations
{
using System.CodeDom.Compiler;
using System.Data.Entity.Migrations;
using System.Data.Entity.Migrations.Infrastructure;
using System.Resources;
[GeneratedCode("EntityFramework.Migrations", "6.1.3-40302")]
public sealed partial class OverrideConventionsGigGenres : IMigrationMetadata
{
private readonly ResourceManager Resources = new ResourceManager(typeof(OverrideConventionsGigGenres));
string IMigrationMetadata.Id
{
get { return "201710271130209_OverrideConventionsGigGenres"; }
}
string IMigrationMetadata.Source
{
get { return null; }
}
string IMigrationMetadata.Target
{
get { return Resources.GetString("Target"); }
}
}
}
| 28.733333 | 111 | 0.640371 | [
"Apache-2.0"
] | antcalatayud/GigHub | GigHub/Persistence/Migrations/201710271130209_OverrideConventionsGigGenres.Designer.cs | 862 | C# |
using System;
using System.ComponentModel;
using System.ComponentModel.DataAnnotations;
using FreeSql.DataAnnotations;
namespace Admin.Core.Common.BaseModel
{
/// <summary>
/// 实体创建审计
/// </summary>
public class EntityAdd<TKey> : Entity<TKey>, IEntityAdd<TKey> where TKey : struct
{
/// <summary>
/// 创建者Id
/// </summary>
[Description("创建者Id")]
[Column(Position = -3, CanUpdate = false)]
public TKey? CreatedUserId { get; set; }
/// <summary>
/// 创建者
/// </summary>
[Description("创建者")]
[Column(Position = -2, CanUpdate = false), MaxLength(50)]
public string CreatedUserName { get; set; }
/// <summary>
/// 创建时间
/// </summary>
[Description("创建时间")]
[Column(Position = -1, CanUpdate = false, ServerTime = DateTimeKind.Local)]
public DateTime? CreatedTime { get; set; }
}
public class EntityAdd : EntityAdd<long>
{
}
}
| 25.075 | 85 | 0.567298 | [
"MIT"
] | DotNetExample/Admin.Core | Admin.Core.Common/BaseModel/EntityAdd.cs | 1,057 | C# |
// ------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
// ------------------------------------------------------------------------------
#nullable enable
#pragma warning disable CS1591
#pragma warning disable CS0108
#pragma warning disable 618
using System;
using System.Collections.Generic;
using System.Collections.Specialized;
using System.ComponentModel.DataAnnotations;
using System.Globalization;
using System.Linq;
using System.Runtime.Serialization;
using System.Text.Json.Serialization;
using System.Threading;
using System.Threading.Tasks;
using JetBrains.Space.Common;
using JetBrains.Space.Common.Json.Serialization;
using JetBrains.Space.Common.Json.Serialization.Polymorphism;
using JetBrains.Space.Common.Types;
namespace JetBrains.Space.Client;
public sealed class BGStats
: IPropagatePropertyAccessPath
{
public BGStats() { }
public BGStats(int totalBlogs, List<Pair<TDTeam, int>> teams, List<Pair<TDLocation, int>> locations, List<Pair<PRProject, int>>? projects = null)
{
TotalBlogs = totalBlogs;
Teams = teams;
Projects = projects;
Locations = locations;
}
private PropertyValue<int> _totalBlogs = new PropertyValue<int>(nameof(BGStats), nameof(TotalBlogs));
[Required]
[JsonPropertyName("totalBlogs")]
public int TotalBlogs
{
get => _totalBlogs.GetValue();
set => _totalBlogs.SetValue(value);
}
private PropertyValue<List<Pair<TDTeam, int>>> _teams = new PropertyValue<List<Pair<TDTeam, int>>>(nameof(BGStats), nameof(Teams), new List<Pair<TDTeam, int>>());
[Required]
[JsonPropertyName("teams")]
public List<Pair<TDTeam, int>> Teams
{
get => _teams.GetValue();
set => _teams.SetValue(value);
}
private PropertyValue<List<Pair<PRProject, int>>?> _projects = new PropertyValue<List<Pair<PRProject, int>>?>(nameof(BGStats), nameof(Projects));
[JsonPropertyName("projects")]
public List<Pair<PRProject, int>>? Projects
{
get => _projects.GetValue();
set => _projects.SetValue(value);
}
private PropertyValue<List<Pair<TDLocation, int>>> _locations = new PropertyValue<List<Pair<TDLocation, int>>>(nameof(BGStats), nameof(Locations), new List<Pair<TDLocation, int>>());
[Required]
[JsonPropertyName("locations")]
public List<Pair<TDLocation, int>> Locations
{
get => _locations.GetValue();
set => _locations.SetValue(value);
}
public void SetAccessPath(string path, bool validateHasBeenSet)
{
_totalBlogs.SetAccessPath(path, validateHasBeenSet);
_teams.SetAccessPath(path, validateHasBeenSet);
_projects.SetAccessPath(path, validateHasBeenSet);
_locations.SetAccessPath(path, validateHasBeenSet);
}
}
| 32.287234 | 186 | 0.658979 | [
"Apache-2.0"
] | JetBrains/space-dotnet-sdk | src/JetBrains.Space.Client/Generated/Dtos/BGStats.generated.cs | 3,035 | C# |
using System;
using System.Globalization;
using System.Linq;
using System.Security.Claims;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using Microsoft.AspNet.Identity;
using Microsoft.AspNet.Identity.Owin;
using Microsoft.Owin.Security;
using ACMWeb.Models;
namespace ACMWeb.Controllers
{
[Authorize]
public class AccountController : Controller
{
private ApplicationSignInManager _signInManager;
private ApplicationUserManager _userManager;
public AccountController()
{
}
public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager )
{
UserManager = userManager;
SignInManager = signInManager;
}
public ApplicationSignInManager SignInManager
{
get
{
return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>();
}
private set
{
_signInManager = value;
}
}
public ApplicationUserManager UserManager
{
get
{
return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>();
}
private set
{
_userManager = value;
}
}
//
// GET: /Account/Login
[AllowAnonymous]
public ActionResult Login(string returnUrl)
{
ViewBag.ReturnUrl = returnUrl;
return View();
}
//
// POST: /Account/Login
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Login(LoginViewModel model, string returnUrl)
{
if (!ModelState.IsValid)
{
return View(model);
}
// This doesn't count login failures towards account lockout
// To enable password failures to trigger account lockout, change to shouldLockout: true
var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe });
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid login attempt.");
return View(model);
}
}
//
// GET: /Account/VerifyCode
[AllowAnonymous]
public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe)
{
// Require that the user has already logged in via username/password or external login
if (!await SignInManager.HasBeenVerifiedAsync())
{
return View("Error");
}
return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/VerifyCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
// The following code protects for brute force attacks against the two factor codes.
// If a user enters incorrect codes for a specified amount of time then the user account
// will be locked out for a specified amount of time.
// You can configure the account lockout settings in IdentityConfig
var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(model.ReturnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.Failure:
default:
ModelState.AddModelError("", "Invalid code.");
return View(model);
}
}
//
// GET: /Account/Register
[AllowAnonymous]
public ActionResult Register()
{
return View();
}
//
// POST: /Account/Register
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> Register(RegisterViewModel model)
{
if (ModelState.IsValid)
{
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user, model.Password);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent:false, rememberBrowser:false);
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id);
// var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Confirm your account", "Please confirm your account by clicking <a href=\"" + callbackUrl + "\">here</a>");
return RedirectToAction("Index", "Home");
}
AddErrors(result);
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ConfirmEmail
[AllowAnonymous]
public async Task<ActionResult> ConfirmEmail(string userId, string code)
{
if (userId == null || code == null)
{
return View("Error");
}
var result = await UserManager.ConfirmEmailAsync(userId, code);
return View(result.Succeeded ? "ConfirmEmail" : "Error");
}
//
// GET: /Account/ForgotPassword
[AllowAnonymous]
public ActionResult ForgotPassword()
{
return View();
}
//
// POST: /Account/ForgotPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model)
{
if (ModelState.IsValid)
{
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id)))
{
// Don't reveal that the user does not exist or is not confirmed
return View("ForgotPasswordConfirmation");
}
// For more information on how to enable account confirmation and password reset please visit https://go.microsoft.com/fwlink/?LinkID=320771
// Send an email with this link
// string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id);
// var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme);
// await UserManager.SendEmailAsync(user.Id, "Reset Password", "Please reset your password by clicking <a href=\"" + callbackUrl + "\">here</a>");
// return RedirectToAction("ForgotPasswordConfirmation", "Account");
}
// If we got this far, something failed, redisplay form
return View(model);
}
//
// GET: /Account/ForgotPasswordConfirmation
[AllowAnonymous]
public ActionResult ForgotPasswordConfirmation()
{
return View();
}
//
// GET: /Account/ResetPassword
[AllowAnonymous]
public ActionResult ResetPassword(string code)
{
return code == null ? View("Error") : View();
}
//
// POST: /Account/ResetPassword
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model)
{
if (!ModelState.IsValid)
{
return View(model);
}
var user = await UserManager.FindByNameAsync(model.Email);
if (user == null)
{
// Don't reveal that the user does not exist
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password);
if (result.Succeeded)
{
return RedirectToAction("ResetPasswordConfirmation", "Account");
}
AddErrors(result);
return View();
}
//
// GET: /Account/ResetPasswordConfirmation
[AllowAnonymous]
public ActionResult ResetPasswordConfirmation()
{
return View();
}
//
// POST: /Account/ExternalLogin
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public ActionResult ExternalLogin(string provider, string returnUrl)
{
// Request a redirect to the external login provider
return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl }));
}
//
// GET: /Account/SendCode
[AllowAnonymous]
public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe)
{
var userId = await SignInManager.GetVerifiedUserIdAsync();
if (userId == null)
{
return View("Error");
}
var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId);
var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList();
return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe });
}
//
// POST: /Account/SendCode
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> SendCode(SendCodeViewModel model)
{
if (!ModelState.IsValid)
{
return View();
}
// Generate the token and send it
if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider))
{
return View("Error");
}
return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe });
}
//
// GET: /Account/ExternalLoginCallback
[AllowAnonymous]
public async Task<ActionResult> ExternalLoginCallback(string returnUrl)
{
var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync();
if (loginInfo == null)
{
return RedirectToAction("Login");
}
// Sign in the user with this external login provider if the user already has a login
var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false);
switch (result)
{
case SignInStatus.Success:
return RedirectToLocal(returnUrl);
case SignInStatus.LockedOut:
return View("Lockout");
case SignInStatus.RequiresVerification:
return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false });
case SignInStatus.Failure:
default:
// If the user does not have an account, then prompt the user to create an account
ViewBag.ReturnUrl = returnUrl;
ViewBag.LoginProvider = loginInfo.Login.LoginProvider;
return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email });
}
}
//
// POST: /Account/ExternalLoginConfirmation
[HttpPost]
[AllowAnonymous]
[ValidateAntiForgeryToken]
public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl)
{
if (User.Identity.IsAuthenticated)
{
return RedirectToAction("Index", "Manage");
}
if (ModelState.IsValid)
{
// Get the information about the user from the external login provider
var info = await AuthenticationManager.GetExternalLoginInfoAsync();
if (info == null)
{
return View("ExternalLoginFailure");
}
var user = new ApplicationUser { UserName = model.Email, Email = model.Email };
var result = await UserManager.CreateAsync(user);
if (result.Succeeded)
{
result = await UserManager.AddLoginAsync(user.Id, info.Login);
if (result.Succeeded)
{
await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false);
return RedirectToLocal(returnUrl);
}
}
AddErrors(result);
}
ViewBag.ReturnUrl = returnUrl;
return View(model);
}
//
// POST: /Account/LogOff
[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult LogOff()
{
AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie);
return RedirectToAction("Index", "Home");
}
//
// GET: /Account/ExternalLoginFailure
[AllowAnonymous]
public ActionResult ExternalLoginFailure()
{
return View();
}
protected override void Dispose(bool disposing)
{
if (disposing)
{
if (_userManager != null)
{
_userManager.Dispose();
_userManager = null;
}
if (_signInManager != null)
{
_signInManager.Dispose();
_signInManager = null;
}
}
base.Dispose(disposing);
}
#region Helpers
// Used for XSRF protection when adding external logins
private const string XsrfKey = "XsrfId";
private IAuthenticationManager AuthenticationManager
{
get
{
return HttpContext.GetOwinContext().Authentication;
}
}
private void AddErrors(IdentityResult result)
{
foreach (var error in result.Errors)
{
ModelState.AddModelError("", error);
}
}
private ActionResult RedirectToLocal(string returnUrl)
{
if (Url.IsLocalUrl(returnUrl))
{
return Redirect(returnUrl);
}
return RedirectToAction("Index", "Home");
}
internal class ChallengeResult : HttpUnauthorizedResult
{
public ChallengeResult(string provider, string redirectUri)
: this(provider, redirectUri, null)
{
}
public ChallengeResult(string provider, string redirectUri, string userId)
{
LoginProvider = provider;
RedirectUri = redirectUri;
UserId = userId;
}
public string LoginProvider { get; set; }
public string RedirectUri { get; set; }
public string UserId { get; set; }
public override void ExecuteResult(ControllerContext context)
{
var properties = new AuthenticationProperties { RedirectUri = RedirectUri };
if (UserId != null)
{
properties.Dictionary[XsrfKey] = UserId;
}
context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider);
}
}
#endregion
}
} | 35.843299 | 173 | 0.553037 | [
"MIT"
] | Ali-HA/APMS | ACMWeb/Controllers/AccountController.cs | 17,386 | 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("Interact")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Interact")]
[assembly: AssemblyCopyright("Copyright © 2018")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("cef054af-95b7-4b88-934e-02705feea554")]
// 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.405405 | 84 | 0.746387 | [
"MIT"
] | mattuylee/stormchat | stormchat-client-csharp/Interact/Properties/AssemblyInfo.cs | 1,387 | C# |
using System;
using System.Net;
namespace webservice.Library.Exceptions
{
public class HttpException : Exception
{
public HttpStatusCode status;
public HttpException(HttpStatusCode status, string message)
: base(message)
{
this.status = status;
}
}
}
| 17.944444 | 67 | 0.616099 | [
"CC0-1.0"
] | brandonmpetty/Hydra | dotnetcore-webservice/webservice/Library/Exceptions/HttpException.cs | 325 | C# |
using Microsoft.AspNetCore.Mvc.Rendering;
using Microsoft.AspNetCore.Mvc.TagHelpers;
using Microsoft.AspNetCore.Mvc.ViewFeatures;
using Microsoft.AspNetCore.Razor.TagHelpers;
using Microsoft.Extensions.DependencyInjection;
using Mozlite.Extensions.Groups;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
namespace Mozlite.Mvc.TagHelpers
{
/// <summary>
/// 下拉列表标签基类。
/// </summary>
public abstract class DropdownListTagHelper : ViewContextableTagHelperBase
{
/// <summary>
/// 模型属性。
/// </summary>
[HtmlAttributeName("for")]
public ModelExpression For { get; set; }
/// <summary>
/// 默认显示字符串:如“请选择”。
/// </summary>
[HtmlAttributeName("default-text")]
public string DefaultText { get; set; }
/// <summary>
/// 默认值。
/// </summary>
[HtmlAttributeName("default-value")]
public object DefaultValue { get; set; }
/// <summary>
/// 值。
/// </summary>
[HtmlAttributeName("value")]
public object Value { get; set; }
/// <summary>
/// 异步访问并呈现当前标签实例。
/// </summary>
/// <param name="context">当前HTML标签上下文,包含当前HTML相关信息。</param>
/// <param name="output">当前标签输出实例,用于呈现标签相关信息。</param>
public override async Task ProcessAsync(TagHelperContext context, TagHelperOutput output)
{
output.TagName = "select";
var items = Init() ?? await InitAsync() ?? Enumerable.Empty<SelectListItem>();
items = items.ToList();
if (!string.IsNullOrEmpty(DefaultText))//添加默认选项
items = new[] { new SelectListItem { Text = DefaultText, Value = DefaultValue?.ToString() ?? "" } }.Concat(items).ToList();
if (For != null)
{
var htmlGenerator = HttpContext.RequestServices.GetRequiredService<IHtmlGenerator>();
var tagHelper = new SelectTagHelper(htmlGenerator);
tagHelper.ViewContext = ViewContext;
tagHelper.For = For;
tagHelper.Items = items;
tagHelper.Init(context);
await tagHelper.ProcessAsync(context, output);
}
else
{
var value = Value?.ToString();
if (value != null) output.SetAttribute("value", value);
foreach (var item in items)
{
output.AppendHtml("option", option =>
{
if (string.Equals(item.Value, value, StringComparison.OrdinalIgnoreCase))
option.MergeAttribute("selected", "selected", true);
option.MergeAttribute("value", item.Value);
option.InnerHtml.AppendHtml(item.Text);
});
}
}
}
/// <summary>
/// 初始化选项列表。
/// </summary>
/// <returns>返回选项列表。</returns>
protected virtual IEnumerable<SelectListItem> Init()
{
return null;
}
/// <summary>
/// 初始化选项列表。
/// </summary>
/// <returns>返回选项列表。</returns>
protected virtual Task<IEnumerable<SelectListItem>> InitAsync()
{
return Task.FromResult<IEnumerable<SelectListItem>>(null);
}
/// <summary>
/// 迭代循环列表。
/// </summary>
/// <typeparam name="TGroup">分组列表。</typeparam>
/// <param name="items">选项列表。</param>
/// <param name="groups">当前分组。</param>
/// <param name="filter">过滤器。</param>
/// <param name="func">获取值代理方法,默认为Id。</param>
protected void InitChildren<TGroup>(List<SelectListItem> items, IEnumerable<TGroup> groups,
Predicate<TGroup> filter = null, Func<TGroup, string> func = null)
where TGroup : GroupBase<TGroup>
{
if (filter != null)
groups = groups.Where(x => filter(x)).ToList();
foreach (var group in groups)
{
items.Add(new SelectListItem { Text = group.Name, Value = func?.Invoke(group) ?? group.Id.ToString() });
InitChildren(items, group.Children, filter, func, null);
}
}
private void InitChildren<TGroup>(List<SelectListItem> items, IEnumerable<TGroup> groups, Predicate<TGroup> filter, Func<TGroup, string> func, string header)
where TGroup : GroupBase<TGroup>
{
var index = 0;
if (filter != null)
groups = groups.Where(x => filter(x)).ToList();
var count = groups.Count();
if (count == 0)
return;
foreach (var group in groups)
{
index++;
var current = header;
if (index < count)
current += " ├─";
else
current += " └─";
items.Add(new SelectListItem { Text = $"{current} {group.Name}", Value = func?.Invoke(group) ?? group.Id.ToString() });
current = current.Replace("└─", " ").Replace("├─", index < count ? "│ " : " ");
InitChildren(items, group.Children, filter, func, current);
}
}
}
} | 37.340278 | 165 | 0.528362 | [
"Apache-2.0"
] | Mozlite/Docs | src/Mozlite.Mvc/TagHelpers/DropdownListTagHelper.cs | 5,725 | C# |
using System;
public class GFG
{
public static int Fib(int n)
{
if (n <= 1)
{
return n;
}
else
{
return Fib(n - 1) + Fib(n - 2);
}
}
public static void Main(string[] args)
{
int n = 9;
Console.Write(Fib(n));
}
}
| 12.285714 | 40 | 0.5 | [
"MIT"
] | Abhi-4793/Ultimate-Logic | Fibonacci/fibonacci.cs | 258 | 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.Linq;
namespace Microsoft.VisualStudio.ProjectSystem.VS.Automation
{
internal static class VisualBasicNamespaceImportsListFactory
{
public static VisualBasicNamespaceImportsList CreateInstance(params string[] list)
{
var newList = new VisualBasicNamespaceImportsList();
newList.SetList(list.ToList());
return newList;
}
}
}
| 31.888889 | 161 | 0.705575 | [
"Apache-2.0"
] | 333fred/roslyn-project-system | src/Microsoft.VisualStudio.ProjectSystem.VisualBasic.VS.UnitTests/Mocks/VisualBasicNamespaceImportsListFactory.cs | 576 | C# |
using System;
using Microsoft.Extensions.Logging;
using Orleans.Runtime;
namespace Orleans.ServiceBus
{
/// <summary>
/// Orleans ServiceBus error codes
/// </summary>
internal enum OrleansServiceBusErrorCode
{
/// <summary>
/// Start of orlean servicebus error codes
/// </summary>
ServiceBus = 1<<16,
FailedPartitionRead = ServiceBus + 1,
RetryReceiverInit = ServiceBus + 2,
}
internal static class LoggerExtensions
{
internal static void Debug(this ILogger logger, OrleansServiceBusErrorCode errorCode, string format, params object[] args)
{
logger.LogDebug((int) errorCode, format, args);
}
internal static void Trace(this ILogger logger, OrleansServiceBusErrorCode errorCode, string format, params object[] args)
{
logger.LogTrace((int) errorCode, format, args);
}
internal static void Info(this ILogger logger, OrleansServiceBusErrorCode errorCode, string format, params object[] args)
{
logger.LogInformation((int) errorCode, format, args);
}
internal static void Warn(this ILogger logger, OrleansServiceBusErrorCode errorCode, string format, params object[] args)
{
logger.LogWarning((int) errorCode, format, args);
}
internal static void Warn(this ILogger logger, OrleansServiceBusErrorCode errorCode, string message, Exception exception)
{
logger.LogWarning((int) errorCode, exception, message);
}
internal static void Error(this ILogger logger, OrleansServiceBusErrorCode errorCode, string message, Exception exception = null)
{
logger.LogError((int) errorCode, exception, message);
}
}
}
| 33.537037 | 137 | 0.652678 | [
"MIT"
] | 1007lu/orleans | src/Azure/Orleans.Streaming.EventHubs/OrleansServiceBusErrorCode.cs | 1,813 | C# |
using NUnit.Framework;
using SepaWriter.Utils;
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml;
namespace SepaWriter.Test
{
[TestFixture]
public class SepaCreditTransferTest
{
private static readonly SepaIbanData Debtor = new SepaIbanData
{
Bic = "SOGEFRPPXXX",
Iban = "FR7030002005500000157845Z02",
Name = "My Corp"
};
private readonly string FILENAME = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location) + "/sepa_credit_test_result.xml";
private const string ONE_ROW_RESULT =
"<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><Document xmlns=\"urn:iso:std:iso:20022:tech:xsd:pain.001.001.03\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"urn:iso:std:iso:20022:tech:xsd:pain.001.001.03pain.001.001.03.xsd\"><CstmrCdtTrfInitn><GrpHdr><MsgId>transferID</MsgId><CreDtTm>2013-02-17T22:38:12</CreDtTm><NbOfTxs>1</NbOfTxs><CtrlSum>23.45</CtrlSum><InitgPty><Nm>Me</Nm><Id><OrgId><Othr><Id>MyId</Id></Othr></OrgId></Id></InitgPty></GrpHdr><PmtInf><PmtInfId>paymentInfo</PmtInfId><PmtMtd>TRF</PmtMtd><NbOfTxs>1</NbOfTxs><CtrlSum>23.45</CtrlSum><PmtTpInf><SvcLvl><Cd>SEPA</Cd></SvcLvl><LclInstr><Cd>MyCode</Cd></LclInstr></PmtTpInf><ReqdExctnDt>2013-02-17</ReqdExctnDt><Dbtr><Nm>My Corp</Nm><Id><OrgId><Othr><Id>MyId</Id></Othr></OrgId></Id></Dbtr><DbtrAcct><Id><IBAN>FR7030002005500000157845Z02</IBAN></Id><Ccy>EUR</Ccy></DbtrAcct><DbtrAgt><FinInstnId><BIC>SOGEFRPPXXX</BIC></FinInstnId></DbtrAgt><ChrgBr>SLEV</ChrgBr><CdtTrfTxInf><PmtId><InstrId>Transaction Id 1</InstrId><EndToEndId>paymentInfo/1</EndToEndId></PmtId><Amt><InstdAmt Ccy=\"EUR\">23.45</InstdAmt></Amt><CdtrAgt><FinInstnId><BIC>AGRIFRPPXXX</BIC></FinInstnId></CdtrAgt><Cdtr><Nm>THEIR_NAME</Nm></Cdtr><CdtrAcct><Id><IBAN>FR1420041010050500013M02606</IBAN></Id></CdtrAcct><RmtInf><Ustrd>Transaction description</Ustrd></RmtInf></CdtTrfTxInf></PmtInf></CstmrCdtTrfInitn></Document>";
private const string MULTIPLE_ROW_RESULT =
"<?xml version=\"1.0\" encoding=\"utf-8\" standalone=\"yes\"?><Document xmlns=\"urn:iso:std:iso:20022:tech:xsd:pain.001.001.03\" xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"urn:iso:std:iso:20022:tech:xsd:pain.001.001.03pain.001.001.03.xsd\"><CstmrCdtTrfInitn><GrpHdr><MsgId>transferID</MsgId><CreDtTm>2013-02-17T22:38:12</CreDtTm><NbOfTxs>3</NbOfTxs><CtrlSum>63.36</CtrlSum><InitgPty><Nm>Me</Nm></InitgPty></GrpHdr><PmtInf><PmtInfId>paymentInfo</PmtInfId><PmtMtd>TRF</PmtMtd><NbOfTxs>3</NbOfTxs><CtrlSum>63.36</CtrlSum><PmtTpInf><SvcLvl><Cd>SEPA</Cd></SvcLvl></PmtTpInf><ReqdExctnDt>2013-02-18</ReqdExctnDt><Dbtr><Nm>My Corp</Nm><PstlAdr><AdrLine>address</AdrLine></PstlAdr></Dbtr><DbtrAcct><Id><IBAN>FR7030002005500000157845Z02</IBAN></Id><Ccy>EUR</Ccy></DbtrAcct><DbtrAgt><FinInstnId><BIC>SOGEFRPPXXX</BIC></FinInstnId></DbtrAgt><ChrgBr>SLEV</ChrgBr><CdtTrfTxInf><PmtId><InstrId>Transaction Id 1</InstrId><EndToEndId>multiple1</EndToEndId></PmtId><Amt><InstdAmt Ccy=\"EUR\">23.45</InstdAmt></Amt><CdtrAgt><FinInstnId><BIC>AGRIFRPPXXX</BIC></FinInstnId></CdtrAgt><Cdtr><Nm>THEIR_NAME</Nm><PstlAdr><AdrLine>add1</AdrLine><AdrLine>add2</AdrLine></PstlAdr></Cdtr><CdtrAcct><Id><IBAN>FR1420041010050500013M02606</IBAN></Id></CdtrAcct><RmtInf><Ustrd>Transaction description</Ustrd></RmtInf></CdtTrfTxInf><CdtTrfTxInf><PmtId><InstrId>Transaction Id 2</InstrId><EndToEndId>paymentInfo/2</EndToEndId></PmtId><Amt><InstdAmt Ccy=\"EUR\">12.56</InstdAmt></Amt><CdtrAgt><FinInstnId><BIC>AGRIFRPPXXX</BIC></FinInstnId></CdtrAgt><Cdtr><Nm>THEIR_SECOND_NAME</Nm><PstlAdr><AdrLine>add3</AdrLine><AdrLine>add4</AdrLine></PstlAdr></Cdtr><CdtrAcct><Id><IBAN>FR1420041010050500013M02606</IBAN></Id></CdtrAcct><RmtInf><Ustrd>Transaction description 2</Ustrd></RmtInf></CdtTrfTxInf><CdtTrfTxInf><PmtId><InstrId>Transaction Id 3</InstrId><EndToEndId>paymentInfo/3</EndToEndId></PmtId><Amt><InstdAmt Ccy=\"EUR\">27.35</InstdAmt></Amt><CdtrAgt><FinInstnId><BIC>BANK_BIC</BIC></FinInstnId></CdtrAgt><Cdtr><Nm>NAME</Nm></Cdtr><CdtrAcct><Id><IBAN>ACCOUNT_IBAN_SAMPLE</IBAN></Id></CdtrAcct><RmtInf><Ustrd>Transaction description 3</Ustrd></RmtInf></CdtTrfTxInf></PmtInf></CstmrCdtTrfInitn></Document>";
private static SepaCreditTransferTransaction CreateTransaction(string id, decimal amount, string information)
{
return new SepaCreditTransferTransaction
{
Id = id,
Creditor = new SepaIbanData
{
Bic = "AGRIFRPPXXX",
Iban = "FR1420041010050500013M02606",
Name = "THEIR_NAME"
},
Amount = amount,
RemittanceInformation = information
};
}
private static SepaCreditTransfer GetEmptyCreditTransfert()
{
return new SepaCreditTransfer
{
CreationDate = new DateTime(2013, 02, 17, 22, 38, 12),
RequestedExecutionDate = new DateTime(2013, 02, 17),
MessageIdentification = "transferID",
PaymentInfoId = "paymentInfo",
InitiatingPartyName = "Me",
Debtor = Debtor
};
}
private static SepaCreditTransfer GetOneTransactionCreditTransfert(decimal amount)
{
var transfert = GetEmptyCreditTransfert();
transfert.InitiatingPartyId = "MyId";
transfert.LocalInstrumentCode = "MyCode";
transfert.AddCreditTransfer(CreateTransaction("Transaction Id 1", amount, "Transaction description"));
return transfert;
}
[OneTimeTearDown]
public void Cleanup()
{
if (File.Exists(FILENAME))
File.Delete(FILENAME);
}
[Test]
public void ShouldAllowMultipleNullIdTransations()
{
const decimal amount = 23.45m;
SepaCreditTransfer transfert = GetOneTransactionCreditTransfert(amount);
transfert.AddCreditTransfer(CreateTransaction(null, amount, "Transaction description 1"));
transfert.AddCreditTransfer(CreateTransaction(null, amount, "Transaction description 2"));
}
[Test]
public void ShouldAllowTransactionWithoutRemittanceInformation()
{
var transfert = GetEmptyCreditTransfert();
transfert.AddCreditTransfer(CreateTransaction(null, 12m, null));
transfert.AddCreditTransfer(CreateTransaction(null, 13m, null));
string result = transfert.AsXmlString();
Assert.False(result.Contains("<RmtInf>"));
}
[Test]
public void ShouldKeepEndToEndIdIfSet()
{
const decimal amount = 23.45m;
SepaCreditTransfer transfert = GetOneTransactionCreditTransfert(amount);
var trans = CreateTransaction(null, amount, "Transaction description 2");
trans.EndToEndId = "endToendId1";
transfert.AddCreditTransfer(trans);
trans = CreateTransaction(null, amount, "Transaction description 3");
trans.EndToEndId = "endToendId2";
transfert.AddCreditTransfer(trans);
string result = transfert.AsXmlString();
Assert.True(result.Contains("<EndToEndId>endToendId1</EndToEndId>"));
Assert.True(result.Contains("<EndToEndId>endToendId2</EndToEndId>"));
}
[Test]
public void ShouldManageMultipleTransactionsTransfer()
{
var transfert = new SepaCreditTransfer
{
CreationDate = new DateTime(2013, 02, 17, 22, 38, 12),
RequestedExecutionDate = new DateTime(2013, 02, 18),
MessageIdentification = "transferID",
PaymentInfoId = "paymentInfo",
InitiatingPartyName = "Me",
Debtor = new SepaIbanData
{
Bic = Debtor.Bic,
Iban = Debtor.Iban,
Name = Debtor.Name,
Address = new SepaPostalAddress { AdrLine = new List<string>() { "address" } },
}
};
const decimal amount = 23.45m;
var trans = CreateTransaction("Transaction Id 1", amount, "Transaction description");
trans.Creditor.Address = new SepaPostalAddress { AdrLine = new List<string>() { "add1", "add2" } };
trans.EndToEndId = "multiple1";
transfert.AddCreditTransfer(trans);
const decimal amount2 = 12.56m;
trans = CreateTransaction("Transaction Id 2", amount2, "Transaction description 2");
trans.Creditor.Name = "THEIR_SECOND_NAME";
trans.Creditor.Address = new SepaPostalAddress { AdrLine = new List<string>() { "add3", "add4" } };
transfert.AddCreditTransfer(trans);
const decimal amount3 = 27.35m;
transfert.AddCreditTransfer(new SepaCreditTransferTransaction
{
Id = "Transaction Id 3",
Creditor = new SepaIbanData
{
Bic = "BANK_BIC",
Iban = "ACCOUNT_IBAN_SAMPLE",
Name = "NAME"
},
Amount = amount3,
RemittanceInformation = "Transaction description 3"
});
const decimal total = (amount + amount2 + amount3)*100;
Assert.AreEqual(total, transfert.HeaderControlSumInCents);
Assert.AreEqual(total, transfert.PaymentControlSumInCents);
Assert.AreEqual(MULTIPLE_ROW_RESULT, transfert.AsXmlString());
}
[Test]
public void ShouldValidateThePain00100103XmlSchema()
{
var transfert = new SepaCreditTransfer
{
CreationDate = new DateTime(2013, 02, 17, 22, 38, 12),
RequestedExecutionDate = new DateTime(2013, 02, 18),
MessageIdentification = "transferID",
PaymentInfoId = "paymentInfo",
InitiatingPartyName = "Me",
Debtor = Debtor
};
const decimal amount = 23.45m;
var trans = CreateTransaction("Transaction Id 1", amount, "Transaction description");
trans.EndToEndId = "multiple1";
transfert.AddCreditTransfer(trans);
const decimal amount2 = 12.56m;
trans = CreateTransaction("Transaction Id 2", amount2, "Transaction description 2");
transfert.AddCreditTransfer(trans);
const decimal amount3 = 27.35m;
transfert.AddCreditTransfer(new SepaCreditTransferTransaction
{
Id = "Transaction Id 3",
Creditor = new SepaIbanData
{
Bic = "BANK_BIC",
Iban = "ACCOUNT_IBAN_SAMPLE",
Name = "NAME"
},
Amount = amount3,
RemittanceInformation = "Transaction description 3"
});
var validator = XmlValidator.GetValidator(transfert.Schema);
validator.Validate(transfert.AsXmlString());
}
[Test]
public void ShouldValidateThePain00100104XmlSchema()
{
var transfert = new SepaCreditTransfer
{
CreationDate = new DateTime(2013, 02, 17, 22, 38, 12),
RequestedExecutionDate = new DateTime(2013, 02, 18),
MessageIdentification = "transferID",
PaymentInfoId = "paymentInfo",
InitiatingPartyName = "Me",
Debtor = Debtor,
Schema = SepaSchema.Pain00100104
};
const decimal amount = 23.45m;
var trans = CreateTransaction("Transaction Id 1", amount, "Transaction description");
trans.EndToEndId = "multiple1";
transfert.AddCreditTransfer(trans);
const decimal amount2 = 12.56m;
trans = CreateTransaction("Transaction Id 2", amount2, "Transaction description 2");
transfert.AddCreditTransfer(trans);
const decimal amount3 = 27.35m;
transfert.AddCreditTransfer(new SepaCreditTransferTransaction
{
Id = "Transaction Id 3",
Creditor = new SepaIbanData
{
Bic = "BANK_BIC",
Iban = "ACCOUNT_IBAN_SAMPLE",
Name = "NAME"
},
Amount = amount3,
RemittanceInformation = "Transaction description 3"
});
var validator = XmlValidator.GetValidator(transfert.Schema);
validator.Validate(transfert.AsXmlString());
}
[Test]
public void ShouldRejectNotAllowedXmlSchema()
{
Assert.That(() => { new SepaCreditTransfer { Schema = SepaSchema.Pain00800102 }; },
Throws.TypeOf<ArgumentException>().With.Property("Message").Contains("schema is not allowed!"));
}
[Test]
public void ShouldManageOneTransactionTransfer()
{
const decimal amount = 23.45m;
SepaCreditTransfer transfert = GetOneTransactionCreditTransfert(amount);
const decimal total = amount*100;
Assert.AreEqual(total, transfert.HeaderControlSumInCents);
Assert.AreEqual(total, transfert.PaymentControlSumInCents);
Assert.AreEqual(ONE_ROW_RESULT, transfert.AsXmlString());
}
[Test]
public void ShouldRejectIfNoDebtor()
{
var transfert = new SepaCreditTransfer
{
MessageIdentification = "transferID",
PaymentInfoId = "paymentInfo",
InitiatingPartyName = "Me"
};
transfert.AddCreditTransfer(CreateTransaction("Transaction Id 1", 100m, "Transaction description"));
Assert.That(() => { transfert.AsXmlString(); }, Throws.TypeOf<SepaRuleException>().With.Property("Message").EqualTo("The debtor is mandatory."));
}
[Test]
public void ShouldAcceptNoInitiatingPartyName()
{
SepaCreditTransfer transfert = GetOneTransactionCreditTransfert(100m);
transfert.InitiatingPartyName = null;
Assert.DoesNotThrow(() => { transfert.AsXmlString(); });
}
[Test]
public void ShouldRejectIfNoMessageIdentification()
{
SepaCreditTransfer transfert = GetOneTransactionCreditTransfert(100m);
transfert.MessageIdentification = null;
Assert.That(() => { transfert.AsXmlString(); }, Throws.TypeOf<SepaRuleException>().With.Property("Message").EqualTo("The message identification is mandatory."));
}
[Test]
public void ShouldUseMessageIdentificationAsPaymentInfoIdIfNotDefined()
{
SepaCreditTransfer transfert = GetOneTransactionCreditTransfert(100m);
transfert.PaymentInfoId = null;
string result = transfert.AsXmlString();
Assert.True(result.Contains("<PmtInfId>"+ transfert.MessageIdentification + "</PmtInfId>"));
}
[Test]
public void ShouldRejectIfNoTransaction()
{
var transfert = new SepaCreditTransfer
{
MessageIdentification = "transferID",
PaymentInfoId = "paymentInfo",
InitiatingPartyName = "Me",
Debtor = Debtor
};
Assert.That(() => { transfert.AsXmlString(); }, Throws.TypeOf<SepaRuleException>().With.Property("Message").EqualTo("At least one transaction is needed in a transfer."));
}
[Test]
public void ShouldRejectInvalidDebtor()
{
Assert.That(() => { new SepaCreditTransfer { Debtor = new SepaIbanData() }; }, Throws.TypeOf<SepaRuleException>().With.Property("Message").EqualTo("Debtor IBAN data are invalid."));
}
[Test]
public void ShouldRejectDebtorWithoutBic()
{
var iban = (SepaIbanData)Debtor.Clone();
iban.UnknownBic = true;
Assert.That(() => { new SepaCreditTransfer { Debtor = iban }; }, Throws.TypeOf<SepaRuleException>().With.Property("Message").EqualTo("Debtor IBAN data are invalid."));
}
[Test]
public void ShouldRejectNullTransactionTransfer()
{
var transfert = new SepaCreditTransfer();
Assert.That(() => { transfert.AddCreditTransfer(null); }, Throws.TypeOf<ArgumentNullException>().With.Property("Message").Contains("transfer"));
}
[Test]
public void ShouldRejectTwoTransationsWithSameId()
{
SepaCreditTransfer transfert = GetOneTransactionCreditTransfert(100m);
transfert.AddCreditTransfer(CreateTransaction("UniqueId", 23.45m, "Transaction description 2"));
Assert.That(() => { transfert.AddCreditTransfer(CreateTransaction("UniqueId", 23.45m, "Transaction description 2")); }, Throws.TypeOf<SepaRuleException>().With.Property("Message").Contains("must be unique in a transfer"));
}
[Test]
public void ShouldRejectTwoTransationsWithSameEndToEndId()
{
const decimal amount = 23.45m;
SepaCreditTransfer transfert = GetOneTransactionCreditTransfert(amount);
var trans = CreateTransaction("Transaction Id 2", 23.45m, "Transaction description 2");
trans.EndToEndId = "uniqueValue";
transfert.AddCreditTransfer(trans);
trans = CreateTransaction("Transaction Id 3", 23.45m, "Transaction description 2");
trans.EndToEndId = "uniqueValue";
Assert.That(() => { transfert.AddCreditTransfer(trans); }, Throws.TypeOf<SepaRuleException>().With.Property("Message").Contains("must be unique in a transfer"));
}
[Test]
public void ShouldSaveCreditInXmlFile()
{
const decimal amount = 23.45m;
SepaCreditTransfer transfert = GetOneTransactionCreditTransfert(amount);
transfert.Save(FILENAME);
var doc = new XmlDocument();
doc.Load(FILENAME);
Assert.AreEqual(ONE_ROW_RESULT, doc.OuterXml);
}
[Test]
public void ShouldUseEuroAsDefaultCurrency()
{
var transfert = new SepaCreditTransfer();
Assert.AreEqual("EUR", transfert.DebtorAccountCurrency);
}
}
} | 48.508816 | 2,220 | 0.599958 | [
"Apache-2.0"
] | openMCW/sepawriter | SepaWriter.Test/SepaCreditTransferTest.cs | 19,260 | C# |
// -----------------------------------------------------------------------
// <copyright file="UserFunctionController.cs" company="OSharp开源团队">
// Copyright (c) 2014-2018 OSharp. All rights reserved.
// </copyright>
// <site>http://www.osharp.org</site>
// <last-editor>郭明锋</last-editor>
// <last-date>2018-06-27 4:49</last-date>
// -----------------------------------------------------------------------
using System;
using System.ComponentModel;
using System.Linq;
using System.Linq.Expressions;
using Microsoft.AspNetCore.Identity;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.DependencyInjection;
using OSharp.AspNetCore.UI;
using OSharp.Authorization.Functions;
using OSharp.Authorization.Modules;
using OSharp.Entity;
using OSharp.Filter;
using OSharp.Hosting.Authorization;
using OSharp.Hosting.Authorization.Dtos;
using OSharp.Hosting.Identity.Dtos;
using OSharp.Hosting.Identity.Entities;
using OSharp.Linq;
namespace OSharp.Hosting.Apis.Areas.Admin.Controllers
{
[ModuleInfo(Order = 4, Position = "Auth", PositionName = "权限授权模块")]
[Description("管理-用户功能")]
public class UserFunctionController : AdminApiControllerBase
{
private readonly IServiceProvider _provider;
public UserFunctionController(IServiceProvider provider) : base(provider)
{
_provider = provider;
}
/// <summary>
/// 读取用户信息
/// </summary>
/// <returns>用户信息</returns>
[HttpPost]
[ModuleInfo]
[Description("读取")]
public AjaxResult Read(PageRequest request)
{
request.FilterGroup.Rules.Add(new FilterRule("IsLocked", false, FilterOperate.Equal));
Expression<Func<User, bool>> predicate = FilterService.GetExpression<User>(request.FilterGroup);
UserManager<User> userManager = _provider.GetRequiredService<UserManager<User>>();
var page = userManager.Users.ToPage<User, UserOutputDto2>(predicate, request.PageCondition);
return new AjaxResult(page.ToPageData());
}
/// <summary>
/// 读取用户功能信息
/// </summary>
/// <returns>用户功能信息</returns>
[HttpPost]
[ModuleInfo]
[DependOnFunction(nameof(Read))]
[Description("读取功能")]
public AjaxResult ReadFunctions(int userId, [FromBody] PageRequest request)
{
var empty = new PageData<FunctionOutputDto2>();
if (userId == 0)
{
return new AjaxResult(empty);
}
FunctionAuthManager functionAuthManager = _provider.GetRequiredService<FunctionAuthManager>();
int[] moduleIds = functionAuthManager.GetUserWithRoleModuleIds(userId);
Guid[] functionIds = functionAuthManager.ModuleFunctions.Where(m => moduleIds.Contains(m.ModuleId)).Select(m => m.FunctionId).Distinct()
.ToArray();
if (functionIds.Length == 0)
{
return new AjaxResult(empty);
}
Expression<Func<Function, bool>> funcExp = FilterService.GetExpression<Function>(request.FilterGroup);
funcExp = funcExp.And(m => functionIds.Contains(m.Id));
if (request.PageCondition.SortConditions.Length == 0)
{
request.PageCondition.SortConditions = new[] { new SortCondition("Area"), new SortCondition("Controller") };
}
PageResult<FunctionOutputDto2> page = functionAuthManager.Functions.ToPage<Function, FunctionOutputDto2>(funcExp, request.PageCondition);
return new AjaxResult(page.ToPageData());
}
}
}
| 37.628866 | 149 | 0.625479 | [
"Apache-2.0"
] | chunjieyaya/osharp | src/OSharp.Hosting.Apis/Areas/Admin/Controllers/Auth/UserFunctionController.cs | 3,748 | C# |
using System;
using System.Windows.Forms;
namespace TextToKeystrokes
{
static class Program
{
/// <summary>
/// The main entry point for the application.
/// </summary>
[STAThread]
static void Main()
{
Application.EnableVisualStyles();
Application.SetCompatibleTextRenderingDefault(false);
Application.Run(new Form1());
}
}
}
| 21.6 | 65 | 0.574074 | [
"MIT"
] | samuelwilliams/TextToKeystrokes | Program.cs | 434 | C# |
// Copyright (c) 2019 .NET Foundation and Contributors. All rights reserved.
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for full license information.
using System;
using System.ComponentModel;
using System.Diagnostics.CodeAnalysis;
using System.Reactive;
using System.Runtime.Serialization;
using System.Threading;
namespace ReactiveUI
{
/// <summary>
/// ReactiveObject is the base object for ViewModel classes, and it
/// implements INotifyPropertyChanged. In addition, ReactiveObject provides
/// Changing and Changed Observables to monitor object changes.
/// </summary>
[DataContract]
public class ReactiveObject : IReactiveNotifyPropertyChanged<IReactiveObject>, IHandleObservableErrors, IReactiveObject
{
private readonly Lazy<IObservable<IReactivePropertyChangedEventArgs<IReactiveObject>>> _changing;
private readonly Lazy<IObservable<IReactivePropertyChangedEventArgs<IReactiveObject>>> _changed;
private readonly Lazy<Unit> _propertyChangingEventsSubscribed;
private readonly Lazy<Unit> _propertyChangedEventsSubscribed;
private readonly Lazy<IObservable<Exception>> _thrownExceptions;
/// <summary>
/// Initializes a new instance of the <see cref="ReactiveObject"/> class.
/// </summary>
public ReactiveObject()
{
_changing = new Lazy<IObservable<IReactivePropertyChangedEventArgs<IReactiveObject>>>(() => ((IReactiveObject)this).GetChangingObservable(), LazyThreadSafetyMode.PublicationOnly);
_changed = new Lazy<IObservable<IReactivePropertyChangedEventArgs<IReactiveObject>>>(() => ((IReactiveObject)this).GetChangedObservable(), LazyThreadSafetyMode.PublicationOnly);
_propertyChangingEventsSubscribed = new Lazy<Unit>(
() =>
{
this.SubscribePropertyChangingEvents();
return Unit.Default;
}, LazyThreadSafetyMode.PublicationOnly);
_propertyChangedEventsSubscribed = new Lazy<Unit>(
() =>
{
this.SubscribePropertyChangedEvents();
return Unit.Default;
}, LazyThreadSafetyMode.PublicationOnly);
_thrownExceptions = new Lazy<IObservable<Exception>>(this.GetThrownExceptionsObservable, LazyThreadSafetyMode.PublicationOnly);
}
/// <inheritdoc/>
public event PropertyChangingEventHandler PropertyChanging
{
add
{
_ = _propertyChangingEventsSubscribed.Value;
PropertyChangingHandler += value;
}
remove => PropertyChangingHandler -= value;
}
/// <inheritdoc/>
public event PropertyChangedEventHandler PropertyChanged
{
add
{
_ = _propertyChangedEventsSubscribed.Value;
PropertyChangedHandler += value;
}
remove => PropertyChangedHandler -= value;
}
private event PropertyChangingEventHandler? PropertyChangingHandler;
private event PropertyChangedEventHandler? PropertyChangedHandler;
/// <inheritdoc />
[IgnoreDataMember]
public IObservable<IReactivePropertyChangedEventArgs<IReactiveObject>> Changing => _changing.Value;
/// <inheritdoc />
[IgnoreDataMember]
public IObservable<IReactivePropertyChangedEventArgs<IReactiveObject>> Changed => _changed.Value;
/// <inheritdoc/>
[IgnoreDataMember]
public IObservable<Exception> ThrownExceptions => _thrownExceptions.Value;
/// <inheritdoc/>
void IReactiveObject.RaisePropertyChanging(PropertyChangingEventArgs args) => PropertyChangingHandler?.Invoke(this, args);
/// <inheritdoc/>
void IReactiveObject.RaisePropertyChanged(PropertyChangedEventArgs args) => PropertyChangedHandler?.Invoke(this, args);
/// <inheritdoc/>
public IDisposable SuppressChangeNotifications() => IReactiveObjectExtensions.SuppressChangeNotifications(this);
/// <summary>
/// Determines if change notifications are enabled or not.
/// </summary>
/// <returns>A value indicating whether change notifications are enabled.</returns>
public bool AreChangeNotificationsEnabled() => IReactiveObjectExtensions.AreChangeNotificationsEnabled(this);
/// <summary>
/// Delays notifications until the return IDisposable is disposed.
/// </summary>
/// <returns>A disposable which when disposed will send delayed notifications.</returns>
public IDisposable DelayChangeNotifications() => IReactiveObjectExtensions.DelayChangeNotifications(this);
}
}
// vim: tw=120 ts=4 sw=4 et :
| 47.362832 | 191 | 0.628176 | [
"MIT"
] | Noggog/ReactiveUI | src/ReactiveUI/ReactiveObject/ReactiveObject.cs | 5,354 | 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 MusikApp
{
using System;
using System.Collections.Generic;
public partial class users
{
public int Id { get; set; }
public string username { get; set; }
public string name { get; set; }
public string password { get; set; }
public string is_admin { get; set; }
}
}
| 31.666667 | 84 | 0.505263 | [
"MIT"
] | houssems/boombox | MusikApp/users.cs | 760 | 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.Collections.Immutable;
using System.ComponentModel;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;
using System.Xml.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.Syntax;
using Microsoft.CodeAnalysis.Text;
using Roslyn.Utilities;
using InternalSyntax = Microsoft.CodeAnalysis.CSharp.Syntax.InternalSyntax;
namespace Microsoft.CodeAnalysis.CSharp
{
/// <summary>
/// A class containing factory methods for constructing syntax nodes, tokens and trivia.
/// </summary>
public static partial class SyntaxFactory
{
/// <summary>
/// A trivia with kind EndOfLineTrivia containing both the carriage return and line feed characters.
/// </summary>
public static SyntaxTrivia CarriageReturnLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.CarriageReturnLineFeed;
/// <summary>
/// A trivia with kind EndOfLineTrivia containing a single line feed character.
/// </summary>
public static SyntaxTrivia LineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.LineFeed;
/// <summary>
/// A trivia with kind EndOfLineTrivia containing a single carriage return character.
/// </summary>
public static SyntaxTrivia CarriageReturn { get; } = Syntax.InternalSyntax.SyntaxFactory.CarriageReturn;
/// <summary>
/// A trivia with kind WhitespaceTrivia containing a single space character.
/// </summary>
public static SyntaxTrivia Space { get; } = Syntax.InternalSyntax.SyntaxFactory.Space;
/// <summary>
/// A trivia with kind WhitespaceTrivia containing a single tab character.
/// </summary>
public static SyntaxTrivia Tab { get; } = Syntax.InternalSyntax.SyntaxFactory.Tab;
/// <summary>
/// An elastic trivia with kind EndOfLineTrivia containing both the carriage return and line feed characters.
/// Elastic trivia are used to denote trivia that was not produced by parsing source text, and are usually not
/// preserved during formatting.
/// </summary>
public static SyntaxTrivia ElasticCarriageReturnLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticCarriageReturnLineFeed;
/// <summary>
/// An elastic trivia with kind EndOfLineTrivia containing a single line feed character. Elastic trivia are used
/// to denote trivia that was not produced by parsing source text, and are usually not preserved during
/// formatting.
/// </summary>
public static SyntaxTrivia ElasticLineFeed { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticLineFeed;
/// <summary>
/// An elastic trivia with kind EndOfLineTrivia containing a single carriage return character. Elastic trivia
/// are used to denote trivia that was not produced by parsing source text, and are usually not preserved during
/// formatting.
/// </summary>
public static SyntaxTrivia ElasticCarriageReturn { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticCarriageReturn;
/// <summary>
/// An elastic trivia with kind WhitespaceTrivia containing a single space character. Elastic trivia are used to
/// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting.
/// </summary>
public static SyntaxTrivia ElasticSpace { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticSpace;
/// <summary>
/// An elastic trivia with kind WhitespaceTrivia containing a single tab character. Elastic trivia are used to
/// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting.
/// </summary>
public static SyntaxTrivia ElasticTab { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticTab;
/// <summary>
/// An elastic trivia with kind WhitespaceTrivia containing no characters. Elastic marker trivia are included
/// automatically by factory methods when trivia is not specified. Syntax formatting will replace elastic
/// markers with appropriate trivia.
/// </summary>
public static SyntaxTrivia ElasticMarker { get; } = Syntax.InternalSyntax.SyntaxFactory.ElasticZeroSpace;
/// <summary>
/// Creates a trivia with kind EndOfLineTrivia containing the specified text.
/// </summary>
/// <param name="text">The text of the end of line. Any text can be specified here, however only carriage return and
/// line feed characters are recognized by the parser as end of line.</param>
public static SyntaxTrivia EndOfLine(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic: false);
}
/// <summary>
/// Creates a trivia with kind EndOfLineTrivia containing the specified text. Elastic trivia are used to
/// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting.
/// </summary>
/// <param name="text">The text of the end of line. Any text can be specified here, however only carriage return and
/// line feed characters are recognized by the parser as end of line.</param>
public static SyntaxTrivia ElasticEndOfLine(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic: true);
}
[Obsolete("Use SyntaxFactory.EndOfLine or SyntaxFactory.ElasticEndOfLine")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static SyntaxTrivia EndOfLine(string text, bool elastic)
{
return Syntax.InternalSyntax.SyntaxFactory.EndOfLine(text, elastic);
}
/// <summary>
/// Creates a trivia with kind WhitespaceTrivia containing the specified text.
/// </summary>
/// <param name="text">The text of the whitespace. Any text can be specified here, however only specific
/// whitespace characters are recognized by the parser.</param>
public static SyntaxTrivia Whitespace(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic: false);
}
/// <summary>
/// Creates a trivia with kind WhitespaceTrivia containing the specified text. Elastic trivia are used to
/// denote trivia that was not produced by parsing source text, and are usually not preserved during formatting.
/// </summary>
/// <param name="text">The text of the whitespace. Any text can be specified here, however only specific
/// whitespace characters are recognized by the parser.</param>
public static SyntaxTrivia ElasticWhitespace(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic: false);
}
[Obsolete("Use SyntaxFactory.Whitespace or SyntaxFactory.ElasticWhitespace")]
[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
public static SyntaxTrivia Whitespace(string text, bool elastic)
{
return Syntax.InternalSyntax.SyntaxFactory.Whitespace(text, elastic);
}
/// <summary>
/// Creates a trivia with kind either SingleLineCommentTrivia or MultiLineCommentTrivia containing the specified
/// text.
/// </summary>
/// <param name="text">The entire text of the comment including the leading '//' token for single line comments
/// or stop or start tokens for multiline comments.</param>
public static SyntaxTrivia Comment(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.Comment(text);
}
/// <summary>
/// Creates a trivia with kind DisabledTextTrivia. Disabled text corresponds to any text between directives that
/// is not considered active.
/// </summary>
public static SyntaxTrivia DisabledText(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.DisabledText(text);
}
/// <summary>
/// Creates a trivia with kind PreprocessingMessageTrivia.
/// </summary>
public static SyntaxTrivia PreprocessingMessage(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.PreprocessingMessage(text);
}
/// <summary>
/// Trivia nodes represent parts of the program text that are not parts of the
/// syntactic grammar, such as spaces, newlines, comments, preprocessor
/// directives, and disabled code.
/// </summary>
/// <param name="kind">
/// A <see cref="SyntaxKind"/> representing the specific kind of <see cref="SyntaxTrivia"/>. One of
/// <see cref="SyntaxKind.WhitespaceTrivia"/>, <see cref="SyntaxKind.EndOfLineTrivia"/>,
/// <see cref="SyntaxKind.SingleLineCommentTrivia"/>, <see cref="SyntaxKind.MultiLineCommentTrivia"/>,
/// <see cref="SyntaxKind.DocumentationCommentExteriorTrivia"/>, <see cref="SyntaxKind.DisabledTextTrivia"/>
/// </param>
/// <param name="text">
/// The actual text of this token.
/// </param>
public static SyntaxTrivia SyntaxTrivia(SyntaxKind kind, string text)
{
if (text == null)
{
throw new ArgumentNullException(nameof(text));
}
switch (kind)
{
case SyntaxKind.DisabledTextTrivia:
case SyntaxKind.DocumentationCommentExteriorTrivia:
case SyntaxKind.EndOfLineTrivia:
case SyntaxKind.MultiLineCommentTrivia:
case SyntaxKind.SingleLineCommentTrivia:
case SyntaxKind.WhitespaceTrivia:
return new SyntaxTrivia(default(SyntaxToken), new Syntax.InternalSyntax.SyntaxTrivia(kind, text, null, null), 0, 0);
default:
throw new ArgumentException("kind");
}
}
/// <summary>
/// Creates a token corresponding to a syntax kind. This method can be used for token syntax kinds whose text
/// can be inferred by the kind alone.
/// </summary>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
/// <returns></returns>
public static SyntaxToken Token(SyntaxKind kind)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(ElasticMarker.UnderlyingNode, kind, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token corresponding to syntax kind. This method can be used for token syntax kinds whose text can
/// be inferred by the kind alone.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Token(SyntaxTriviaList leading, SyntaxKind kind, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(leading.Node, kind, trailing.Node));
}
/// <summary>
/// Creates a token corresponding to syntax kind. This method gives control over token Text and ValueText.
///
/// For example, consider the text '<see cref="operator &#43;"/>'. To create a token for the value of
/// the operator symbol (&#43;), one would call
/// Token(default(SyntaxTriviaList), SyntaxKind.PlusToken, "&#43;", "+", default(SyntaxTriviaList)).
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
/// <param name="text">The text from which this token was created (e.g. lexed).</param>
/// <param name="valueText">How C# should interpret the text of this token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Token(SyntaxTriviaList leading, SyntaxKind kind, string text, string valueText, SyntaxTriviaList trailing)
{
switch (kind)
{
case SyntaxKind.IdentifierToken:
// Have a different representation.
throw new ArgumentException(CSharpResources.UseVerbatimIdentifier, nameof(kind));
case SyntaxKind.CharacterLiteralToken:
// Value should not have type string.
throw new ArgumentException(CSharpResources.UseLiteralForTokens, nameof(kind));
case SyntaxKind.NumericLiteralToken:
// Value should not have type string.
throw new ArgumentException(CSharpResources.UseLiteralForNumeric, nameof(kind));
}
if (!SyntaxFacts.IsAnyToken(kind))
{
throw new ArgumentException(string.Format(CSharpResources.ThisMethodCanOnlyBeUsedToCreateTokens, kind), nameof(kind));
}
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Token(leading.Node, kind, text, valueText, trailing.Node));
}
/// <summary>
/// Creates a missing token corresponding to syntax kind. A missing token is produced by the parser when an
/// expected token is not found. A missing token has no text and normally has associated diagnostics.
/// </summary>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
public static SyntaxToken MissingToken(SyntaxKind kind)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.MissingToken(ElasticMarker.UnderlyingNode, kind, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a missing token corresponding to syntax kind. A missing token is produced by the parser when an
/// expected token is not found. A missing token has no text and normally has associated diagnostics.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="kind">A syntax kind value for a token. These have the suffix Token or Keyword.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken MissingToken(SyntaxTriviaList leading, SyntaxKind kind, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.MissingToken(leading.Node, kind, trailing.Node));
}
/// <summary>
/// Creates a token with kind IdentifierToken containing the specified text.
/// <param name="text">The raw text of the identifier name, including any escapes or leading '@'
/// character.</param>
/// </summary>
public static SyntaxToken Identifier(string text)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(ElasticMarker.UnderlyingNode, text, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind IdentifierToken containing the specified text.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the identifier name, including any escapes or leading '@'
/// character.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Identifier(SyntaxTriviaList leading, string text, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(leading.Node, text, trailing.Node));
}
/// <summary>
/// Creates a verbatim token with kind IdentifierToken containing the specified text.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the identifier name, including any escapes or leading '@'
/// character as it is in source.</param>
/// <param name="valueText">The canonical value of the token's text.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken VerbatimIdentifier(SyntaxTriviaList leading, string text, string valueText, SyntaxTriviaList trailing)
{
if (text.StartsWith("@", StringComparison.Ordinal))
{
throw new ArgumentException("text should not start with an @ character.");
}
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Identifier(SyntaxKind.IdentifierName, leading.Node, "@" + text, valueText, trailing.Node));
}
/// <summary>
/// Creates a token with kind IdentifierToken containing the specified text.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="contextualKind">An alternative SyntaxKind that can be inferred for this token in special
/// contexts. These are usually keywords.</param>
/// <param name="text">The raw text of the identifier name, including any escapes or leading '@'
/// character.</param>
/// <param name="valueText">The text of the identifier name without escapes or leading '@' character.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
/// <returns></returns>
public static SyntaxToken Identifier(SyntaxTriviaList leading, SyntaxKind contextualKind, string text, string valueText, SyntaxTriviaList trailing)
{
return new SyntaxToken(InternalSyntax.SyntaxFactory.Identifier(contextualKind, leading.Node, text, valueText, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from a 4-byte signed integer value.
/// </summary>
/// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(int value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte signed integer value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, int value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte signed integer value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte signed integer value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, int value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from a 4-byte unsigned integer value.
/// </summary>
/// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(uint value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte unsigned integer value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, uint value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte unsigned integer value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte unsigned integer value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, uint value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from an 8-byte signed integer value.
/// </summary>
/// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(long value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte signed integer value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, long value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte signed integer value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte signed integer value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, long value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from an 8-byte unsigned integer value.
/// </summary>
/// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(ulong value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte unsigned integer value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, ulong value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte unsigned integer value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte unsigned integer value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, ulong value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from a 4-byte floating point value.
/// </summary>
/// <param name="value">The 4-byte floating point value to be represented by the returned token.</param>
public static SyntaxToken Literal(float value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte floating point value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte floating point value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, float value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 4-byte floating point value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 4-byte floating point value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, float value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from an 8-byte floating point value.
/// </summary>
/// <param name="value">The 8-byte floating point value to be represented by the returned token.</param>
public static SyntaxToken Literal(double value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.None), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte floating point value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte floating point value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, double value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding 8-byte floating point value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The 8-byte floating point value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, double value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from a decimal value.
/// </summary>
/// <param name="value">The decimal value to be represented by the returned token.</param>
public static SyntaxToken Literal(decimal value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.IncludeTypeSuffix), value);
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding decimal value.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The decimal value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, decimal value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind NumericLiteralToken from the text and corresponding decimal value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The decimal value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, decimal value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind StringLiteralToken from a string value.
/// </summary>
/// <param name="value">The string value to be represented by the returned token.</param>
public static SyntaxToken Literal(string value)
{
return Literal(SymbolDisplay.FormatLiteral(value, quote: true), value);
}
/// <summary>
/// Creates a token with kind StringLiteralToken from the text and corresponding string value.
/// </summary>
/// <param name="text">The raw text of the literal, including quotes and escape sequences.</param>
/// <param name="value">The string value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, string value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind StringLiteralToken from the text and corresponding string value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal, including quotes and escape sequences.</param>
/// <param name="value">The string value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind CharacterLiteralToken from a character value.
/// </summary>
/// <param name="value">The character value to be represented by the returned token.</param>
public static SyntaxToken Literal(char value)
{
return Literal(ObjectDisplay.FormatLiteral(value, ObjectDisplayOptions.UseQuotes | ObjectDisplayOptions.EscapeNonPrintableCharacters), value);
}
/// <summary>
/// Creates a token with kind CharacterLiteralToken from the text and corresponding character value.
/// </summary>
/// <param name="text">The raw text of the literal, including quotes and escape sequences.</param>
/// <param name="value">The character value to be represented by the returned token.</param>
public static SyntaxToken Literal(string text, char value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Creates a token with kind CharacterLiteralToken from the text and corresponding character value.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal, including quotes and escape sequences.</param>
/// <param name="value">The character value to be represented by the returned token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken Literal(SyntaxTriviaList leading, string text, char value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.Literal(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind BadToken.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the bad token.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken BadToken(SyntaxTriviaList leading, string text, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.BadToken(leading.Node, text, trailing.Node));
}
/// <summary>
/// Creates a token with kind XmlTextLiteralToken.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The xml text value.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken XmlTextLiteral(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlTextLiteral(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates a token with kind XmlEntityLiteralToken.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The xml entity value.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken XmlEntity(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlEntity(leading.Node, text, value, trailing.Node));
}
/// <summary>
/// Creates an xml documentation comment that abstracts xml syntax creation.
/// </summary>
/// <param name="content">
/// A list of xml node syntax that will be the content within the xml documentation comment
/// (e.g. a summary element, a returns element, exception element and so on).
/// </param>
public static DocumentationCommentTriviaSyntax DocumentationComment(params XmlNodeSyntax[] content)
{
return DocumentationCommentTrivia(SyntaxKind.SingleLineDocumentationCommentTrivia, List(content))
.WithLeadingTrivia(DocumentationCommentExterior("/// "))
.WithTrailingTrivia(EndOfLine(""));
}
/// <summary>
/// Creates a summary element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the summary element.</param>
public static XmlElementSyntax XmlSummaryElement(params XmlNodeSyntax[] content)
{
return XmlSummaryElement(List(content));
}
/// <summary>
/// Creates a summary element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the summary element.</param>
public static XmlElementSyntax XmlSummaryElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(DocumentationCommentXmlNames.SummaryElementName, content);
}
/// <summary>
/// Creates a see element within an xml documentation comment.
/// </summary>
/// <param name="cref">A cref syntax node that points to the referenced item (e.g. a class, struct).</param>
public static XmlEmptyElementSyntax XmlSeeElement(CrefSyntax cref)
{
return XmlEmptyElement(DocumentationCommentXmlNames.SeeElementName).AddAttributes(XmlCrefAttribute(cref));
}
/// <summary>
/// Creates a seealso element within an xml documentation comment.
/// </summary>
/// <param name="cref">A cref syntax node that points to the referenced item (e.g. a class, struct).</param>
public static XmlEmptyElementSyntax XmlSeeAlsoElement(CrefSyntax cref)
{
return XmlEmptyElement(DocumentationCommentXmlNames.SeeAlsoElementName).AddAttributes(XmlCrefAttribute(cref));
}
/// <summary>
/// Creates a seealso element within an xml documentation comment.
/// </summary>
/// <param name="linkAddress">The uri of the referenced item.</param>
/// <param name="linkText">A list of xml node syntax that will be used as the link text for the referenced item.</param>
public static XmlElementSyntax XmlSeeAlsoElement(Uri linkAddress, SyntaxList<XmlNodeSyntax> linkText)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.SeeAlsoElementName, linkText);
return element.WithStartTag(element.StartTag.AddAttributes(XmlTextAttribute(DocumentationCommentXmlNames.CrefAttributeName, linkAddress.ToString())));
}
/// <summary>
/// Creates a threadsafety element within an xml documentation comment.
/// </summary>
public static XmlEmptyElementSyntax XmlThreadSafetyElement()
{
return XmlThreadSafetyElement(true, false);
}
/// <summary>
/// Creates a threadsafety element within an xml documentation comment.
/// </summary>
/// <param name="isStatic">Indicates whether static member of this type are safe for multi-threaded operations.</param>
/// <param name="isInstance">Indicates whether instance members of this type are safe for multi-threaded operations.</param>
public static XmlEmptyElementSyntax XmlThreadSafetyElement(bool isStatic, bool isInstance)
{
return XmlEmptyElement(DocumentationCommentXmlNames.ThreadSafetyElementName).AddAttributes(
XmlTextAttribute(DocumentationCommentXmlNames.StaticAttributeName, isStatic.ToString().ToLowerInvariant()),
XmlTextAttribute(DocumentationCommentXmlNames.InstanceAttributeName, isInstance.ToString().ToLowerInvariant()));
}
/// <summary>
/// Creates a syntax node for a name attribute in a xml element within a xml documentation comment.
/// </summary>
/// <param name="parameterName">The value of the name attribute.</param>
public static XmlNameAttributeSyntax XmlNameAttribute(string parameterName)
{
return XmlNameAttribute(
XmlName(DocumentationCommentXmlNames.NameAttributeName),
Token(SyntaxKind.DoubleQuoteToken),
parameterName,
Token(SyntaxKind.DoubleQuoteToken))
.WithLeadingTrivia(Whitespace(" "));
}
/// <summary>
/// Creates a syntax node for a preliminary element within a xml documentation comment.
/// </summary>
public static XmlEmptyElementSyntax XmlPreliminaryElement()
{
return XmlEmptyElement(DocumentationCommentXmlNames.PreliminaryElementName);
}
/// <summary>
/// Creates a syntax node for a cref attribute within a xml documentation comment.
/// </summary>
/// <param name="cref">The <see cref="CrefSyntax"/> used for the xml cref attribute syntax.</param>
public static XmlCrefAttributeSyntax XmlCrefAttribute(CrefSyntax cref)
{
return XmlCrefAttribute(cref, SyntaxKind.DoubleQuoteToken);
}
/// <summary>
/// Creates a syntax node for a cref attribute within a xml documentation comment.
/// </summary>
/// <param name="cref">The <see cref="CrefSyntax"/> used for the xml cref attribute syntax.</param>
/// <param name="quoteKind">The kind of the quote for the referenced item in the cref attribute.</param>
public static XmlCrefAttributeSyntax XmlCrefAttribute(CrefSyntax cref, SyntaxKind quoteKind)
{
cref = cref.ReplaceTokens(cref.DescendantTokens(), XmlReplaceBracketTokens);
return XmlCrefAttribute(
XmlName(DocumentationCommentXmlNames.CrefAttributeName),
Token(quoteKind),
cref,
Token(quoteKind))
.WithLeadingTrivia(Whitespace(" "));
}
/// <summary>
/// Creates a remarks element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the remarks element.</param>
public static XmlElementSyntax XmlRemarksElement(params XmlNodeSyntax[] content)
{
return XmlRemarksElement(List(content));
}
/// <summary>
/// Creates a remarks element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the remarks element.</param>
public static XmlElementSyntax XmlRemarksElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(DocumentationCommentXmlNames.RemarksElementName, content);
}
/// <summary>
/// Creates a returns element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the returns element.</param>
public static XmlElementSyntax XmlReturnsElement(params XmlNodeSyntax[] content)
{
return XmlReturnsElement(List(content));
}
/// <summary>
/// Creates a returns element within an xml documentation comment.
/// </summary>
/// <param name="content">A list of xml node syntax that will be the content within the returns element.</param>
public static XmlElementSyntax XmlReturnsElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(DocumentationCommentXmlNames.ReturnsElementName, content);
}
/// <summary>
/// Creates the syntax representation of an xml value element (e.g. for xml documentation comments).
/// </summary>
/// <param name="content">A list of xml syntax nodes that represents the content of the value element.</param>
public static XmlElementSyntax XmlValueElement(params XmlNodeSyntax[] content)
{
return XmlValueElement(List(content));
}
/// <summary>
/// Creates the syntax representation of an xml value element (e.g. for xml documentation comments).
/// </summary>
/// <param name="content">A list of xml syntax nodes that represents the content of the value element.</param>
public static XmlElementSyntax XmlValueElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(DocumentationCommentXmlNames.ValueElementName, content);
}
/// <summary>
/// Creates the syntax representation of an exception element within xml documentation comments.
/// </summary>
/// <param name="cref">Syntax representation of the reference to the exception type.</param>
/// <param name="content">A list of syntax nodes that represents the content of the exception element.</param>
public static XmlElementSyntax XmlExceptionElement(CrefSyntax cref, params XmlNodeSyntax[] content)
{
return XmlExceptionElement(cref, List(content));
}
/// <summary>
/// Creates the syntax representation of an exception element within xml documentation comments.
/// </summary>
/// <param name="cref">Syntax representation of the reference to the exception type.</param>
/// <param name="content">A list of syntax nodes that represents the content of the exception element.</param>
public static XmlElementSyntax XmlExceptionElement(CrefSyntax cref, SyntaxList<XmlNodeSyntax> content)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ExceptionElementName, content);
return element.WithStartTag(element.StartTag.AddAttributes(XmlCrefAttribute(cref)));
}
/// <summary>
/// Creates the syntax representation of a permission element within xml documentation comments.
/// </summary>
/// <param name="cref">Syntax representation of the reference to the permission type.</param>
/// <param name="content">A list of syntax nodes that represents the content of the permission element.</param>
public static XmlElementSyntax XmlPermissionElement(CrefSyntax cref, params XmlNodeSyntax[] content)
{
return XmlPermissionElement(cref, List(content));
}
/// <summary>
/// Creates the syntax representation of a permission element within xml documentation comments.
/// </summary>
/// <param name="cref">Syntax representation of the reference to the permission type.</param>
/// <param name="content">A list of syntax nodes that represents the content of the permission element.</param>
public static XmlElementSyntax XmlPermissionElement(CrefSyntax cref, SyntaxList<XmlNodeSyntax> content)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.PermissionElementName, content);
return element.WithStartTag(element.StartTag.AddAttributes(XmlCrefAttribute(cref)));
}
/// <summary>
/// Creates the syntax representation of an example element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the example element.</param>
public static XmlElementSyntax XmlExampleElement(params XmlNodeSyntax[] content)
{
return XmlExampleElement(List(content));
}
/// <summary>
/// Creates the syntax representation of an example element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the example element.</param>
public static XmlElementSyntax XmlExampleElement(SyntaxList<XmlNodeSyntax> content)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ExampleElementName, content);
return element.WithStartTag(element.StartTag);
}
/// <summary>
/// Creates the syntax representation of a para element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the para element.</param>
public static XmlElementSyntax XmlParaElement(params XmlNodeSyntax[] content)
{
return XmlParaElement(List(content));
}
/// <summary>
/// Creates the syntax representation of a para element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the para element.</param>
public static XmlElementSyntax XmlParaElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(DocumentationCommentXmlNames.ParaElementName, content);
}
/// <summary>
/// Creates the syntax representation of a param element within xml documentation comments (e.g. for
/// documentation of method parameters).
/// </summary>
/// <param name="parameterName">The name of the parameter.</param>
/// <param name="content">A list of syntax nodes that represents the content of the param element (e.g.
/// the description and meaning of the parameter).</param>
public static XmlElementSyntax XmlParamElement(string parameterName, params XmlNodeSyntax[] content)
{
return XmlParamElement(parameterName, List(content));
}
/// <summary>
/// Creates the syntax representation of a param element within xml documentation comments (e.g. for
/// documentation of method parameters).
/// </summary>
/// <param name="parameterName">The name of the parameter.</param>
/// <param name="content">A list of syntax nodes that represents the content of the param element (e.g.
/// the description and meaning of the parameter).</param>
public static XmlElementSyntax XmlParamElement(string parameterName, SyntaxList<XmlNodeSyntax> content)
{
XmlElementSyntax element = XmlElement(DocumentationCommentXmlNames.ParameterElementName, content);
return element.WithStartTag(element.StartTag.AddAttributes(XmlNameAttribute(parameterName)));
}
/// <summary>
/// Creates the syntax representation of a paramref element within xml documentation comments (e.g. for
/// referencing particular parameters of a method).
/// </summary>
/// <param name="parameterName">The name of the referenced parameter.</param>
public static XmlEmptyElementSyntax XmlParamRefElement(string parameterName)
{
return XmlEmptyElement(DocumentationCommentXmlNames.ParameterReferenceElementName).AddAttributes(XmlNameAttribute(parameterName));
}
/// <summary>
/// Creates the syntax representation of a see element within xml documentation comments,
/// that points to the 'null' language keyword.
/// </summary>
public static XmlEmptyElementSyntax XmlNullKeywordElement()
{
return XmlKeywordElement("null");
}
/// <summary>
/// Creates the syntax representation of a see element within xml documentation comments,
/// that points to a language keyword.
/// </summary>
/// <param name="keyword">The language keyword to which the see element points to.</param>
private static XmlEmptyElementSyntax XmlKeywordElement(string keyword)
{
return XmlEmptyElement(DocumentationCommentXmlNames.SeeElementName).AddAttributes(
XmlTextAttribute(DocumentationCommentXmlNames.LangwordAttributeName, keyword));
}
/// <summary>
/// Creates the syntax representation of a placeholder element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the placeholder element.</param>
public static XmlElementSyntax XmlPlaceholderElement(params XmlNodeSyntax[] content)
{
return XmlPlaceholderElement(List(content));
}
/// <summary>
/// Creates the syntax representation of a placeholder element within xml documentation comments.
/// </summary>
/// <param name="content">A list of syntax nodes that represents the content of the placeholder element.</param>
public static XmlElementSyntax XmlPlaceholderElement(SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(DocumentationCommentXmlNames.PlaceholderElementName, content);
}
/// <summary>
/// Creates the syntax representation of a named empty xml element within xml documentation comments.
/// </summary>
/// <param name="localName">The name of the empty xml element.</param>
public static XmlEmptyElementSyntax XmlEmptyElement(string localName)
{
return XmlEmptyElement(XmlName(localName));
}
/// <summary>
/// Creates the syntax representation of a named xml element within xml documentation comments.
/// </summary>
/// <param name="localName">The name of the empty xml element.</param>
/// <param name="content">A list of syntax nodes that represents the content of the xml element.</param>
public static XmlElementSyntax XmlElement(string localName, SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(XmlName(localName), content);
}
/// <summary>
/// Creates the syntax representation of a named xml element within xml documentation comments.
/// </summary>
/// <param name="name">The name of the empty xml element.</param>
/// <param name="content">A list of syntax nodes that represents the content of the xml element.</param>
public static XmlElementSyntax XmlElement(XmlNameSyntax name, SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(
XmlElementStartTag(name),
content,
XmlElementEndTag(name));
}
/// <summary>
/// Creates the syntax representation of an xml text attribute.
/// </summary>
/// <param name="name">The name of the xml text attribute.</param>
/// <param name="value">The value of the xml text attribute.</param>
public static XmlTextAttributeSyntax XmlTextAttribute(string name, string value)
{
return XmlTextAttribute(name, XmlTextLiteral(value));
}
/// <summary>
/// Creates the syntax representation of an xml text attribute.
/// </summary>
/// <param name="name">The name of the xml text attribute.</param>
/// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param>
public static XmlTextAttributeSyntax XmlTextAttribute(string name, params SyntaxToken[] textTokens)
{
return XmlTextAttribute(XmlName(name), SyntaxKind.DoubleQuoteToken, TokenList(textTokens));
}
/// <summary>
/// Creates the syntax representation of an xml text attribute.
/// </summary>
/// <param name="name">The name of the xml text attribute.</param>
/// <param name="quoteKind">The kind of the quote token to be used to quote the value (e.g. " or ').</param>
/// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param>
public static XmlTextAttributeSyntax XmlTextAttribute(string name, SyntaxKind quoteKind, SyntaxTokenList textTokens)
{
return XmlTextAttribute(XmlName(name), quoteKind, textTokens);
}
/// <summary>
/// Creates the syntax representation of an xml text attribute.
/// </summary>
/// <param name="name">The name of the xml text attribute.</param>
/// <param name="quoteKind">The kind of the quote token to be used to quote the value (e.g. " or ').</param>
/// <param name="textTokens">A list of tokens used for the value of the xml text attribute.</param>
public static XmlTextAttributeSyntax XmlTextAttribute(XmlNameSyntax name, SyntaxKind quoteKind, SyntaxTokenList textTokens)
{
return XmlTextAttribute(name, Token(quoteKind), textTokens, Token(quoteKind))
.WithLeadingTrivia(Whitespace(" "));
}
/// <summary>
/// Creates the syntax representation of an xml element that spans multiple text lines.
/// </summary>
/// <param name="localName">The name of the xml element.</param>
/// <param name="content">A list of syntax nodes that represents the content of the xml multi line element.</param>
public static XmlElementSyntax XmlMultiLineElement(string localName, SyntaxList<XmlNodeSyntax> content)
{
return XmlMultiLineElement(XmlName(localName), content);
}
/// <summary>
/// Creates the syntax representation of an xml element that spans multiple text lines.
/// </summary>
/// <param name="name">The name of the xml element.</param>
/// <param name="content">A list of syntax nodes that represents the content of the xml multi line element.</param>
public static XmlElementSyntax XmlMultiLineElement(XmlNameSyntax name, SyntaxList<XmlNodeSyntax> content)
{
return XmlElement(
XmlElementStartTag(name),
content,
XmlElementEndTag(name));
}
/// <summary>
/// Creates the syntax representation of an xml text that contains a newline token with a documentation comment
/// exterior trivia at the end (continued documentation comment).
/// </summary>
/// <param name="text">The raw text within the new line.</param>
public static XmlTextSyntax XmlNewLine(string text)
{
return XmlText(XmlTextNewLine(text));
}
/// <summary>
/// Creates the syntax representation of an xml newline token with a documentation comment exterior trivia at
/// the end (continued documentation comment).
/// </summary>
/// <param name="text">The raw text within the new line.</param>
public static SyntaxToken XmlTextNewLine(string text)
{
return XmlTextNewLine(text, true);
}
/// <summary>
/// Creates a token with kind XmlTextLiteralNewLineToken.
/// </summary>
/// <param name="leading">A list of trivia immediately preceding the token.</param>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The xml text new line value.</param>
/// <param name="trailing">A list of trivia immediately following the token.</param>
public static SyntaxToken XmlTextNewLine(SyntaxTriviaList leading, string text, string value, SyntaxTriviaList trailing)
{
return new SyntaxToken(
InternalSyntax.SyntaxFactory.XmlTextNewLine(
leading.Node,
text,
value,
trailing.Node));
}
/// <summary>
/// Creates the syntax representation of an xml newline token for xml documentation comments.
/// </summary>
/// <param name="text">The raw text within the new line.</param>
/// <param name="continueXmlDocumentationComment">
/// If set to true, a documentation comment exterior token will be added to the trailing trivia
/// of the new token.</param>
public static SyntaxToken XmlTextNewLine(string text, bool continueXmlDocumentationComment)
{
var token = new SyntaxToken(
InternalSyntax.SyntaxFactory.XmlTextNewLine(
ElasticMarker.UnderlyingNode,
text,
text,
ElasticMarker.UnderlyingNode));
if (continueXmlDocumentationComment)
token = token.WithTrailingTrivia(token.TrailingTrivia.Add(DocumentationCommentExterior("/// ")));
return token;
}
/// <summary>
/// Generates the syntax representation of a xml text node (e.g. for xml documentation comments).
/// </summary>
/// <param name="value">The string literal used as the text of the xml text node.</param>
public static XmlTextSyntax XmlText(string value)
{
return XmlText(XmlTextLiteral(value));
}
/// <summary>
/// Generates the syntax representation of a xml text node (e.g. for xml documentation comments).
/// </summary>
/// <param name="textTokens">A list of text tokens used as the text of the xml text node.</param>
public static XmlTextSyntax XmlText(params SyntaxToken[] textTokens)
{
return XmlText(TokenList(textTokens));
}
/// <summary>
/// Generates the syntax representation of an xml text literal.
/// </summary>
/// <param name="value">The text used within the xml text literal.</param>
public static SyntaxToken XmlTextLiteral(string value)
{
// TODO: [RobinSedlaczek] It is no compiler hot path here I think. But the contribution guide
// states to avoid LINQ (https://github.com/dotnet/roslyn/wiki/Contributing-Code). With
// XText we have a reference to System.Xml.Linq. Isn't this rule valid here?
string encoded = new XText(value).ToString();
return XmlTextLiteral(
TriviaList(),
encoded,
value,
TriviaList());
}
/// <summary>
/// Generates the syntax representation of an xml text literal.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
/// <param name="value">The text used within the xml text literal.</param>
public static SyntaxToken XmlTextLiteral(string text, string value)
{
return new SyntaxToken(Syntax.InternalSyntax.SyntaxFactory.XmlTextLiteral(ElasticMarker.UnderlyingNode, text, value, ElasticMarker.UnderlyingNode));
}
/// <summary>
/// Helper method that replaces less-than and greater-than characters with brackets.
/// </summary>
/// <param name="originalToken">The original token that is to be replaced.</param>
/// <param name="rewrittenToken">The new rewritten token.</param>
/// <returns>Returns the new rewritten token with replaced characters.</returns>
private static SyntaxToken XmlReplaceBracketTokens(SyntaxToken originalToken, SyntaxToken rewrittenToken)
{
if (rewrittenToken.IsKind(SyntaxKind.LessThanToken) && string.Equals("<", rewrittenToken.Text, StringComparison.Ordinal))
return Token(rewrittenToken.LeadingTrivia, SyntaxKind.LessThanToken, "{", rewrittenToken.ValueText, rewrittenToken.TrailingTrivia);
if (rewrittenToken.IsKind(SyntaxKind.GreaterThanToken) && string.Equals(">", rewrittenToken.Text, StringComparison.Ordinal))
return Token(rewrittenToken.LeadingTrivia, SyntaxKind.GreaterThanToken, "}", rewrittenToken.ValueText, rewrittenToken.TrailingTrivia);
return rewrittenToken;
}
/// <summary>
/// Creates a trivia with kind DocumentationCommentExteriorTrivia.
/// </summary>
/// <param name="text">The raw text of the literal.</param>
public static SyntaxTrivia DocumentationCommentExterior(string text)
{
return Syntax.InternalSyntax.SyntaxFactory.DocumentationCommentExteriorTrivia(text);
}
/// <summary>
/// Creates an empty list of syntax nodes.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
public static SyntaxList<TNode> List<TNode>() where TNode : SyntaxNode
{
return default(SyntaxList<TNode>);
}
/// <summary>
/// Creates a singleton list of syntax nodes.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
/// <param name="node">The single element node.</param>
/// <returns></returns>
public static SyntaxList<TNode> SingletonList<TNode>(TNode node) where TNode : SyntaxNode
{
return new SyntaxList<TNode>(node);
}
/// <summary>
/// Creates a list of syntax nodes.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
/// <param name="nodes">A sequence of element nodes.</param>
public static SyntaxList<TNode> List<TNode>(IEnumerable<TNode> nodes) where TNode : SyntaxNode
{
return new SyntaxList<TNode>(nodes);
}
/// <summary>
/// Creates an empty list of tokens.
/// </summary>
public static SyntaxTokenList TokenList()
{
return default(SyntaxTokenList);
}
/// <summary>
/// Creates a singleton list of tokens.
/// </summary>
/// <param name="token">The single token.</param>
public static SyntaxTokenList TokenList(SyntaxToken token)
{
return new SyntaxTokenList(token);
}
/// <summary>
/// Creates a list of tokens.
/// </summary>
/// <param name="tokens">An array of tokens.</param>
public static SyntaxTokenList TokenList(params SyntaxToken[] tokens)
{
return new SyntaxTokenList(tokens);
}
/// <summary>
/// Creates a list of tokens.
/// </summary>
/// <param name="tokens"></param>
/// <returns></returns>
public static SyntaxTokenList TokenList(IEnumerable<SyntaxToken> tokens)
{
return new SyntaxTokenList(tokens);
}
/// <summary>
/// Creates a trivia from a StructuredTriviaSyntax node.
/// </summary>
public static SyntaxTrivia Trivia(StructuredTriviaSyntax node)
{
return new SyntaxTrivia(default(SyntaxToken), node.Green, position: 0, index: 0);
}
/// <summary>
/// Creates an empty list of trivia.
/// </summary>
public static SyntaxTriviaList TriviaList()
{
return default(SyntaxTriviaList);
}
/// <summary>
/// Creates a singleton list of trivia.
/// </summary>
/// <param name="trivia">A single trivia.</param>
public static SyntaxTriviaList TriviaList(SyntaxTrivia trivia)
{
return new SyntaxTriviaList(trivia);
}
/// <summary>
/// Creates a list of trivia.
/// </summary>
/// <param name="trivias">An array of trivia.</param>
public static SyntaxTriviaList TriviaList(params SyntaxTrivia[] trivias)
=> new SyntaxTriviaList(trivias);
/// <summary>
/// Creates a list of trivia.
/// </summary>
/// <param name="trivias">A sequence of trivia.</param>
public static SyntaxTriviaList TriviaList(IEnumerable<SyntaxTrivia> trivias)
=> new SyntaxTriviaList(trivias);
/// <summary>
/// Creates an empty separated list.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
public static SeparatedSyntaxList<TNode> SeparatedList<TNode>() where TNode : SyntaxNode
{
return default(SeparatedSyntaxList<TNode>);
}
/// <summary>
/// Creates a singleton separated list.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
/// <param name="node">A single node.</param>
public static SeparatedSyntaxList<TNode> SingletonSeparatedList<TNode>(TNode node) where TNode : SyntaxNode
{
return new SeparatedSyntaxList<TNode>(new SyntaxNodeOrTokenList(node, index: 0));
}
/// <summary>
/// Creates a separated list of nodes from a sequence of nodes, synthesizing comma separators in between.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
/// <param name="nodes">A sequence of syntax nodes.</param>
public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<TNode>? nodes) where TNode : SyntaxNode
{
if (nodes == null)
{
return default(SeparatedSyntaxList<TNode>);
}
var collection = nodes as ICollection<TNode>;
if (collection != null && collection.Count == 0)
{
return default(SeparatedSyntaxList<TNode>);
}
using (var enumerator = nodes.GetEnumerator())
{
if (!enumerator.MoveNext())
{
return default(SeparatedSyntaxList<TNode>);
}
var firstNode = enumerator.Current;
if (!enumerator.MoveNext())
{
return SingletonSeparatedList<TNode>(firstNode);
}
var builder = new SeparatedSyntaxListBuilder<TNode>(collection != null ? collection.Count : 3);
builder.Add(firstNode);
var commaToken = Token(SyntaxKind.CommaToken);
do
{
builder.AddSeparator(commaToken);
builder.Add(enumerator.Current);
}
while (enumerator.MoveNext());
return builder.ToList();
}
}
/// <summary>
/// Creates a separated list of nodes from a sequence of nodes and a sequence of separator tokens.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
/// <param name="nodes">A sequence of syntax nodes.</param>
/// <param name="separators">A sequence of token to be interleaved between the nodes. The number of tokens must
/// be one less than the number of nodes.</param>
public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<TNode>? nodes, IEnumerable<SyntaxToken>? separators) where TNode : SyntaxNode
{
// Interleave the nodes and the separators. The number of separators must be equal to or 1 less than the number of nodes or
// an argument exception is thrown.
if (nodes != null)
{
IEnumerator<TNode> enumerator = nodes.GetEnumerator();
SeparatedSyntaxListBuilder<TNode> builder = SeparatedSyntaxListBuilder<TNode>.Create();
if (separators != null)
{
foreach (SyntaxToken token in separators)
{
if (!enumerator.MoveNext())
{
throw new ArgumentException($"{nameof(nodes)} must not be empty.", nameof(nodes));
}
builder.Add(enumerator.Current);
builder.AddSeparator(token);
}
}
if (enumerator.MoveNext())
{
builder.Add(enumerator.Current);
if (enumerator.MoveNext())
{
throw new ArgumentException($"{nameof(separators)} must have 1 fewer element than {nameof(nodes)}", nameof(separators));
}
}
return builder.ToList();
}
if (separators != null)
{
throw new ArgumentException($"When {nameof(nodes)} is null, {nameof(separators)} must also be null.", nameof(separators));
}
return default(SeparatedSyntaxList<TNode>);
}
/// <summary>
/// Creates a separated list from a sequence of nodes and tokens, starting with a node and alternating between additional nodes and separator tokens.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
/// <param name="nodesAndTokens">A sequence of nodes or tokens, alternating between nodes and separator tokens.</param>
public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(IEnumerable<SyntaxNodeOrToken> nodesAndTokens) where TNode : SyntaxNode
{
return SeparatedList<TNode>(NodeOrTokenList(nodesAndTokens));
}
/// <summary>
/// Creates a separated list from a <see cref="SyntaxNodeOrTokenList"/>, where the list elements start with a node and then alternate between
/// additional nodes and separator tokens.
/// </summary>
/// <typeparam name="TNode">The specific type of the element nodes.</typeparam>
/// <param name="nodesAndTokens">The list of nodes and tokens.</param>
public static SeparatedSyntaxList<TNode> SeparatedList<TNode>(SyntaxNodeOrTokenList nodesAndTokens) where TNode : SyntaxNode
{
if (!HasSeparatedNodeTokenPattern(nodesAndTokens))
{
throw new ArgumentException(CodeAnalysisResources.NodeOrTokenOutOfSequence);
}
if (!NodesAreCorrectType<TNode>(nodesAndTokens))
{
throw new ArgumentException(CodeAnalysisResources.UnexpectedTypeOfNodeInList);
}
return new SeparatedSyntaxList<TNode>(nodesAndTokens);
}
private static bool NodesAreCorrectType<TNode>(SyntaxNodeOrTokenList list)
{
for (int i = 0, n = list.Count; i < n; i++)
{
var element = list[i];
if (element.IsNode && !(element.AsNode() is TNode))
{
return false;
}
}
return true;
}
private static bool HasSeparatedNodeTokenPattern(SyntaxNodeOrTokenList list)
{
for (int i = 0, n = list.Count; i < n; i++)
{
var element = list[i];
if (element.IsToken == ((i & 1) == 0))
{
return false;
}
}
return true;
}
/// <summary>
/// Creates an empty <see cref="SyntaxNodeOrTokenList"/>.
/// </summary>
public static SyntaxNodeOrTokenList NodeOrTokenList()
{
return default(SyntaxNodeOrTokenList);
}
/// <summary>
/// Create a <see cref="SyntaxNodeOrTokenList"/> from a sequence of <see cref="SyntaxNodeOrToken"/>.
/// </summary>
/// <param name="nodesAndTokens">The sequence of nodes and tokens</param>
public static SyntaxNodeOrTokenList NodeOrTokenList(IEnumerable<SyntaxNodeOrToken> nodesAndTokens)
{
return new SyntaxNodeOrTokenList(nodesAndTokens);
}
/// <summary>
/// Create a <see cref="SyntaxNodeOrTokenList"/> from one or more <see cref="SyntaxNodeOrToken"/>.
/// </summary>
/// <param name="nodesAndTokens">The nodes and tokens</param>
public static SyntaxNodeOrTokenList NodeOrTokenList(params SyntaxNodeOrToken[] nodesAndTokens)
{
return new SyntaxNodeOrTokenList(nodesAndTokens);
}
/// <summary>
/// Creates an IdentifierNameSyntax node.
/// </summary>
/// <param name="name">The identifier name.</param>
public static IdentifierNameSyntax IdentifierName(string name)
{
return IdentifierName(Identifier(name));
}
// direct access to parsing for common grammar areas
/// <summary>
/// Create a new syntax tree from a syntax node.
/// </summary>
public static SyntaxTree SyntaxTree(SyntaxNode root, ParseOptions? options = null, string path = "", Encoding? encoding = null)
{
return CSharpSyntaxTree.Create((CSharpSyntaxNode)root, (CSharpParseOptions?)options, path, encoding);
}
#pragma warning disable RS0026 // Do not add multiple public overloads with optional parameters
#pragma warning disable RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads.
/// <inheritdoc cref="CSharpSyntaxTree.ParseText(string, CSharpParseOptions?, string, Encoding?, CancellationToken)"/>
public static SyntaxTree ParseSyntaxTree(
string text,
ParseOptions? options = null,
string path = "",
Encoding? encoding = null,
CancellationToken cancellationToken = default)
{
return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, encoding, cancellationToken);
}
/// <inheritdoc cref="CSharpSyntaxTree.ParseText(SourceText, CSharpParseOptions?, string, CancellationToken)"/>
public static SyntaxTree ParseSyntaxTree(
SourceText text,
ParseOptions? options = null,
string path = "",
CancellationToken cancellationToken = default)
{
return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, cancellationToken);
}
#pragma warning restore RS0027 // Public API with optional parameter(s) should have the most parameters amongst its public overloads.
#pragma warning restore RS0026 // Do not add multiple public overloads with optional parameters
/// <summary>
/// Parse a list of trivia rules for leading trivia.
/// </summary>
public static SyntaxTriviaList ParseLeadingTrivia(string text, int offset = 0)
{
return ParseLeadingTrivia(text, CSharpParseOptions.Default, offset);
}
/// <summary>
/// Parse a list of trivia rules for leading trivia.
/// </summary>
internal static SyntaxTriviaList ParseLeadingTrivia(string text, CSharpParseOptions? options, int offset = 0)
{
using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), options))
{
return lexer.LexSyntaxLeadingTrivia();
}
}
/// <summary>
/// Parse a list of trivia using the parsing rules for trailing trivia.
/// </summary>
public static SyntaxTriviaList ParseTrailingTrivia(string text, int offset = 0)
{
using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), CSharpParseOptions.Default))
{
return lexer.LexSyntaxTrailingTrivia();
}
}
// TODO: If this becomes a real API, we'll need to add an offset parameter to
// match the pattern followed by the other ParseX methods.
internal static CrefSyntax? ParseCref(string text)
{
// NOTE: Conceivably, we could introduce a new code path that directly calls
// DocumentationCommentParser.ParseCrefAttributeValue, but that method won't
// work unless the lexer makes the appropriate mode transitions. Rather than
// introducing a new code path that will have to be kept in sync with other
// mode changes distributed throughout Lexer, SyntaxParser, and
// DocumentationCommentParser, we'll just wrap the text in some lexable syntax
// and then extract the piece we want.
string commentText = string.Format(@"/// <see cref=""{0}""/>", text);
SyntaxTriviaList leadingTrivia = ParseLeadingTrivia(commentText, CSharpParseOptions.Default.WithDocumentationMode(DocumentationMode.Diagnose));
Debug.Assert(leadingTrivia.Count == 1);
SyntaxTrivia trivia = leadingTrivia.First();
DocumentationCommentTriviaSyntax structure = (DocumentationCommentTriviaSyntax)trivia.GetStructure()!;
Debug.Assert(structure.Content.Count == 2);
XmlEmptyElementSyntax elementSyntax = (XmlEmptyElementSyntax)structure.Content[1];
Debug.Assert(elementSyntax.Attributes.Count == 1);
XmlAttributeSyntax attributeSyntax = (XmlAttributeSyntax)elementSyntax.Attributes[0];
return attributeSyntax.Kind() == SyntaxKind.XmlCrefAttribute ? ((XmlCrefAttributeSyntax)attributeSyntax).Cref : null;
}
/// <summary>
/// Parse a C# language token.
/// </summary>
/// <param name="text">The text of the token including leading and trailing trivia.</param>
/// <param name="offset">Optional offset into text.</param>
public static SyntaxToken ParseToken(string text, int offset = 0)
{
using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), CSharpParseOptions.Default))
{
return new SyntaxToken(lexer.Lex(InternalSyntax.LexerMode.Syntax));
}
}
/// <summary>
/// Parse a sequence of C# language tokens.
/// Since this API does not create a <see cref="SyntaxNode"/> that owns all produced tokens,
/// the <see cref="SyntaxToken.GetLocation"/> API may yield surprising results for
/// the produced tokens and its behavior is generally unspecified.
/// </summary>
/// <param name="text">The text of all the tokens.</param>
/// <param name="initialTokenPosition">An integer to use as the starting position of the first token.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">Parse options.</param>
public static IEnumerable<SyntaxToken> ParseTokens(string text, int offset = 0, int initialTokenPosition = 0, CSharpParseOptions? options = null)
{
using (var lexer = new InternalSyntax.Lexer(MakeSourceText(text, offset), options ?? CSharpParseOptions.Default))
{
var position = initialTokenPosition;
while (true)
{
var token = lexer.Lex(InternalSyntax.LexerMode.Syntax);
yield return new SyntaxToken(parent: null, token: token, position: position, index: 0);
position += token.FullWidth;
if (token.Kind == SyntaxKind.EndOfFileToken)
{
break;
}
}
}
}
/// <summary>
/// Parse a NameSyntax node using the grammar rule for names.
/// </summary>
public static NameSyntax ParseName(string text, int offset = 0, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseName();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (NameSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a TypeNameSyntax node using the grammar rule for type names.
/// </summary>
// Backcompat overload, do not remove
[EditorBrowsable(EditorBrowsableState.Never)]
public static TypeSyntax ParseTypeName(string text, int offset, bool consumeFullText)
{
return ParseTypeName(text, offset, options: null, consumeFullText);
}
/// <summary>
/// Parse a TypeNameSyntax node using the grammar rule for type names.
/// </summary>
public static TypeSyntax ParseTypeName(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseTypeName();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (TypeSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse an ExpressionSyntax node using the lowest precedence grammar rule for expressions.
/// </summary>
/// <param name="text">The text of the expression.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static ExpressionSyntax ParseExpression(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseExpression();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (ExpressionSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a StatementSyntaxNode using grammar rule for statements.
/// </summary>
/// <param name="text">The text of the statement.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static StatementSyntax ParseStatement(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseStatement();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (StatementSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a MemberDeclarationSyntax. This includes all of the kinds of members that could occur in a type declaration.
/// If nothing resembling a valid member declaration is found in the input, returns null.
/// </summary>
/// <param name="text">The text of the declaration.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input following a declaration should be treated as an error</param>
public static MemberDeclarationSyntax? ParseMemberDeclaration(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseMemberDeclaration();
if (node == null)
{
return null;
}
return (MemberDeclarationSyntax)(consumeFullText ? parser.ConsumeUnexpectedTokens(node) : node).CreateRed();
}
}
/// <summary>
/// Parse a CompilationUnitSyntax using the grammar rule for an entire compilation unit (file). To produce a
/// SyntaxTree instance, use CSharpSyntaxTree.ParseText instead.
/// </summary>
/// <param name="text">The text of the compilation unit.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
public static CompilationUnitSyntax ParseCompilationUnit(string text, int offset = 0, CSharpParseOptions? options = null)
{
// note that we do not need a "consumeFullText" parameter, because parsing a compilation unit always must
// consume input until the end-of-file
using (var lexer = MakeLexer(text, offset, options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseCompilationUnit();
return (CompilationUnitSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a ParameterListSyntax node.
/// </summary>
/// <param name="text">The text of the parenthesized parameter list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static ParameterListSyntax ParseParameterList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseParenthesizedParameterList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (ParameterListSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a BracketedParameterListSyntax node.
/// </summary>
/// <param name="text">The text of the bracketed parameter list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static BracketedParameterListSyntax ParseBracketedParameterList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseBracketedParameterList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (BracketedParameterListSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse an ArgumentListSyntax node.
/// </summary>
/// <param name="text">The text of the parenthesized argument list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static ArgumentListSyntax ParseArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseParenthesizedArgumentList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (ArgumentListSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse a BracketedArgumentListSyntax node.
/// </summary>
/// <param name="text">The text of the bracketed argument list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static BracketedArgumentListSyntax ParseBracketedArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseBracketedArgumentList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (BracketedArgumentListSyntax)node.CreateRed();
}
}
/// <summary>
/// Parse an AttributeArgumentListSyntax node.
/// </summary>
/// <param name="text">The text of the attribute argument list.</param>
/// <param name="offset">Optional offset into text.</param>
/// <param name="options">The optional parse options to use. If no options are specified default options are
/// used.</param>
/// <param name="consumeFullText">True if extra tokens in the input should be treated as an error</param>
public static AttributeArgumentListSyntax ParseAttributeArgumentList(string text, int offset = 0, ParseOptions? options = null, bool consumeFullText = true)
{
using (var lexer = MakeLexer(text, offset, (CSharpParseOptions?)options))
using (var parser = MakeParser(lexer))
{
var node = parser.ParseAttributeArgumentList();
if (consumeFullText) node = parser.ConsumeUnexpectedTokens(node);
return (AttributeArgumentListSyntax)node.CreateRed();
}
}
/// <summary>
/// Helper method for wrapping a string in a SourceText.
/// </summary>
private static SourceText MakeSourceText(string text, int offset)
{
return SourceText.From(text, Encoding.UTF8).GetSubText(offset);
}
private static InternalSyntax.Lexer MakeLexer(string text, int offset, CSharpParseOptions? options = null)
{
return new InternalSyntax.Lexer(
text: MakeSourceText(text, offset),
options: options ?? CSharpParseOptions.Default);
}
private static InternalSyntax.LanguageParser MakeParser(InternalSyntax.Lexer lexer)
{
return new InternalSyntax.LanguageParser(lexer, oldTree: null, changes: null);
}
/// <summary>
/// Determines if two trees are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldTree">The original tree.</param>
/// <param name="newTree">The new tree.</param>
/// <param name="topLevel">
/// If true then the trees are equivalent if the contained nodes and tokens declaring
/// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies
/// or initializer expressions, otherwise all nodes and tokens must be equivalent.
/// </param>
public static bool AreEquivalent(SyntaxTree? oldTree, SyntaxTree? newTree, bool topLevel)
{
if (oldTree == null && newTree == null)
{
return true;
}
if (oldTree == null || newTree == null)
{
return false;
}
return SyntaxEquivalence.AreEquivalent(oldTree, newTree, ignoreChildNode: null, topLevel: topLevel);
}
/// <summary>
/// Determines if two syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldNode">The old node.</param>
/// <param name="newNode">The new node.</param>
/// <param name="topLevel">
/// If true then the nodes are equivalent if the contained nodes and tokens declaring
/// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies
/// or initializer expressions, otherwise all nodes and tokens must be equivalent.
/// </param>
public static bool AreEquivalent(SyntaxNode? oldNode, SyntaxNode? newNode, bool topLevel)
{
return SyntaxEquivalence.AreEquivalent(oldNode, newNode, ignoreChildNode: null, topLevel: topLevel);
}
/// <summary>
/// Determines if two syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldNode">The old node.</param>
/// <param name="newNode">The new node.</param>
/// <param name="ignoreChildNode">
/// If specified called for every child syntax node (not token) that is visited during the comparison.
/// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded.
/// </param>
public static bool AreEquivalent(SyntaxNode? oldNode, SyntaxNode? newNode, Func<SyntaxKind, bool>? ignoreChildNode = null)
{
return SyntaxEquivalence.AreEquivalent(oldNode, newNode, ignoreChildNode: ignoreChildNode, topLevel: false);
}
/// <summary>
/// Determines if two syntax tokens are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldToken">The old token.</param>
/// <param name="newToken">The new token.</param>
public static bool AreEquivalent(SyntaxToken oldToken, SyntaxToken newToken)
{
return SyntaxEquivalence.AreEquivalent(oldToken, newToken);
}
/// <summary>
/// Determines if two lists of tokens are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old token list.</param>
/// <param name="newList">The new token list.</param>
public static bool AreEquivalent(SyntaxTokenList oldList, SyntaxTokenList newList)
{
return SyntaxEquivalence.AreEquivalent(oldList, newList);
}
/// <summary>
/// Determines if two lists of syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old list.</param>
/// <param name="newList">The new list.</param>
/// <param name="topLevel">
/// If true then the nodes are equivalent if the contained nodes and tokens declaring
/// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies
/// or initializer expressions, otherwise all nodes and tokens must be equivalent.
/// </param>
public static bool AreEquivalent<TNode>(SyntaxList<TNode> oldList, SyntaxList<TNode> newList, bool topLevel)
where TNode : CSharpSyntaxNode
{
return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, null, topLevel);
}
/// <summary>
/// Determines if two lists of syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old list.</param>
/// <param name="newList">The new list.</param>
/// <param name="ignoreChildNode">
/// If specified called for every child syntax node (not token) that is visited during the comparison.
/// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded.
/// </param>
public static bool AreEquivalent<TNode>(SyntaxList<TNode> oldList, SyntaxList<TNode> newList, Func<SyntaxKind, bool>? ignoreChildNode = null)
where TNode : SyntaxNode
{
return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, ignoreChildNode, topLevel: false);
}
/// <summary>
/// Determines if two lists of syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old list.</param>
/// <param name="newList">The new list.</param>
/// <param name="topLevel">
/// If true then the nodes are equivalent if the contained nodes and tokens declaring
/// metadata visible symbolic information are equivalent, ignoring any differences of nodes inside method bodies
/// or initializer expressions, otherwise all nodes and tokens must be equivalent.
/// </param>
public static bool AreEquivalent<TNode>(SeparatedSyntaxList<TNode> oldList, SeparatedSyntaxList<TNode> newList, bool topLevel)
where TNode : SyntaxNode
{
return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, null, topLevel);
}
/// <summary>
/// Determines if two lists of syntax nodes are the same, disregarding trivia differences.
/// </summary>
/// <param name="oldList">The old list.</param>
/// <param name="newList">The new list.</param>
/// <param name="ignoreChildNode">
/// If specified called for every child syntax node (not token) that is visited during the comparison.
/// If it returns true the child is recursively visited, otherwise the child and its subtree is disregarded.
/// </param>
public static bool AreEquivalent<TNode>(SeparatedSyntaxList<TNode> oldList, SeparatedSyntaxList<TNode> newList, Func<SyntaxKind, bool>? ignoreChildNode = null)
where TNode : SyntaxNode
{
return SyntaxEquivalence.AreEquivalent(oldList.Node, newList.Node, ignoreChildNode, topLevel: false);
}
internal static TypeSyntax? GetStandaloneType(TypeSyntax? node)
{
if (node != null)
{
var parent = node.Parent as ExpressionSyntax;
if (parent != null && (node.Kind() == SyntaxKind.IdentifierName || node.Kind() == SyntaxKind.GenericName))
{
switch (parent.Kind())
{
case SyntaxKind.QualifiedName:
var qualifiedName = (QualifiedNameSyntax)parent;
if (qualifiedName.Right == node)
{
return qualifiedName;
}
break;
case SyntaxKind.AliasQualifiedName:
var aliasQualifiedName = (AliasQualifiedNameSyntax)parent;
if (aliasQualifiedName.Name == node)
{
return aliasQualifiedName;
}
break;
}
}
}
return node;
}
/// <summary>
/// Gets the containing expression that is actually a language expression and not just typed
/// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side
/// of qualified names and member access expressions are not language expressions, yet the
/// containing qualified names or member access expressions are indeed expressions.
/// </summary>
public static ExpressionSyntax GetStandaloneExpression(ExpressionSyntax expression)
{
return SyntaxFactory.GetStandaloneNode(expression) as ExpressionSyntax ?? expression;
}
/// <summary>
/// Gets the containing expression that is actually a language expression (or something that
/// GetSymbolInfo can be applied to) and not just typed
/// as an ExpressionSyntax for convenience. For example, NameSyntax nodes on the right side
/// of qualified names and member access expressions are not language expressions, yet the
/// containing qualified names or member access expressions are indeed expressions.
/// Similarly, if the input node is a cref part that is not independently meaningful, then
/// the result will be the full cref. Besides an expression, an input that is a NameSyntax
/// of a SubpatternSyntax, e.g. in `name: 3` may cause this method to return the enclosing
/// SubpatternSyntax.
/// </summary>
internal static CSharpSyntaxNode? GetStandaloneNode(CSharpSyntaxNode? node)
{
if (node == null || !(node is ExpressionSyntax || node is CrefSyntax))
{
return node;
}
switch (node.Kind())
{
case SyntaxKind.IdentifierName:
case SyntaxKind.GenericName:
case SyntaxKind.NameMemberCref:
case SyntaxKind.IndexerMemberCref:
case SyntaxKind.OperatorMemberCref:
case SyntaxKind.ConversionOperatorMemberCref:
case SyntaxKind.ArrayType:
case SyntaxKind.NullableType:
// Adjustment may be required.
break;
default:
return node;
}
CSharpSyntaxNode? parent = node.Parent;
if (parent == null)
{
return node;
}
switch (parent.Kind())
{
case SyntaxKind.QualifiedName:
if (((QualifiedNameSyntax)parent).Right == node)
{
return parent;
}
break;
case SyntaxKind.AliasQualifiedName:
if (((AliasQualifiedNameSyntax)parent).Name == node)
{
return parent;
}
break;
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
if (((MemberAccessExpressionSyntax)parent).Name == node)
{
return parent;
}
break;
case SyntaxKind.MemberBindingExpression:
{
if (((MemberBindingExpressionSyntax)parent).Name == node)
{
return parent;
}
break;
}
// Only care about name member crefs because the other cref members
// are identifier by keywords, not syntax nodes.
case SyntaxKind.NameMemberCref:
if (((NameMemberCrefSyntax)parent).Name == node)
{
CSharpSyntaxNode? grandparent = parent.Parent;
return grandparent != null && grandparent.Kind() == SyntaxKind.QualifiedCref
? grandparent
: parent;
}
break;
case SyntaxKind.QualifiedCref:
if (((QualifiedCrefSyntax)parent).Member == node)
{
return parent;
}
break;
case SyntaxKind.ArrayCreationExpression:
if (((ArrayCreationExpressionSyntax)parent).Type == node)
{
return parent;
}
break;
case SyntaxKind.ObjectCreationExpression:
if (node.Kind() == SyntaxKind.NullableType && ((ObjectCreationExpressionSyntax)parent).Type == node)
{
return parent;
}
break;
case SyntaxKind.StackAllocArrayCreationExpression:
if (((StackAllocArrayCreationExpressionSyntax)parent).Type == node)
{
return parent;
}
break;
case SyntaxKind.NameColon:
if (parent.Parent.IsKind(SyntaxKind.Subpattern))
{
return parent.Parent;
}
break;
}
return node;
}
/// <summary>
/// Given a conditional binding expression, find corresponding conditional access node.
/// </summary>
internal static ConditionalAccessExpressionSyntax? FindConditionalAccessNodeForBinding(CSharpSyntaxNode node)
{
var currentNode = node;
Debug.Assert(currentNode.Kind() == SyntaxKind.MemberBindingExpression ||
currentNode.Kind() == SyntaxKind.ElementBindingExpression);
// In a well formed tree, the corresponding access node should be one of the ancestors
// and its "?" token should precede the binding syntax.
while (currentNode != null)
{
currentNode = currentNode.Parent;
Debug.Assert(currentNode != null, "binding should be enclosed in a conditional access");
if (currentNode.Kind() == SyntaxKind.ConditionalAccessExpression)
{
var condAccess = (ConditionalAccessExpressionSyntax)currentNode;
if (condAccess.OperatorToken.EndPosition == node.Position)
{
return condAccess;
}
}
}
return null;
}
/// <summary>
/// Converts a generic name expression into one without the generic arguments.
/// </summary>
/// <param name="expression"></param>
/// <returns></returns>
public static ExpressionSyntax? GetNonGenericExpression(ExpressionSyntax expression)
{
if (expression != null)
{
switch (expression.Kind())
{
case SyntaxKind.SimpleMemberAccessExpression:
case SyntaxKind.PointerMemberAccessExpression:
var max = (MemberAccessExpressionSyntax)expression;
if (max.Name.Kind() == SyntaxKind.GenericName)
{
var gn = (GenericNameSyntax)max.Name;
return SyntaxFactory.BinaryExpression(expression.Kind(), max.Expression, max.OperatorToken, SyntaxFactory.IdentifierName(gn.Identifier));
}
break;
case SyntaxKind.QualifiedName:
var qn = (QualifiedNameSyntax)expression;
if (qn.Right.Kind() == SyntaxKind.GenericName)
{
var gn = (GenericNameSyntax)qn.Right;
return SyntaxFactory.QualifiedName(qn.Left, qn.DotToken, SyntaxFactory.IdentifierName(gn.Identifier));
}
break;
case SyntaxKind.AliasQualifiedName:
var an = (AliasQualifiedNameSyntax)expression;
if (an.Name.Kind() == SyntaxKind.GenericName)
{
var gn = (GenericNameSyntax)an.Name;
return SyntaxFactory.AliasQualifiedName(an.Alias, an.ColonColonToken, SyntaxFactory.IdentifierName(gn.Identifier));
}
break;
}
}
return expression;
}
/// <summary>
/// Determines whether the given text is considered a syntactically complete submission.
/// Throws <see cref="ArgumentException"/> if the tree was not compiled as an interactive submission.
/// </summary>
public static bool IsCompleteSubmission(SyntaxTree tree)
{
if (tree == null)
{
throw new ArgumentNullException(nameof(tree));
}
if (tree.Options.Kind != SourceCodeKind.Script)
{
throw new ArgumentException(CSharpResources.SyntaxTreeIsNotASubmission);
}
if (!tree.HasCompilationUnitRoot)
{
return false;
}
var compilation = (CompilationUnitSyntax)tree.GetRoot();
if (!compilation.HasErrors)
{
return true;
}
foreach (var error in compilation.EndOfFileToken.GetDiagnostics())
{
switch ((ErrorCode)error.Code)
{
case ErrorCode.ERR_OpenEndedComment:
case ErrorCode.ERR_EndifDirectiveExpected:
case ErrorCode.ERR_EndRegionDirectiveExpected:
return false;
}
}
var lastNode = compilation.ChildNodes().LastOrDefault();
if (lastNode == null)
{
return true;
}
// unterminated multi-line comment:
if (lastNode.HasTrailingTrivia && lastNode.ContainsDiagnostics && HasUnterminatedMultiLineComment(lastNode.GetTrailingTrivia()))
{
return false;
}
if (lastNode.IsKind(SyntaxKind.IncompleteMember))
{
return false;
}
// All top-level constructs but global statement (i.e. extern alias, using directive, global attribute, and declarations)
// should have a closing token (semicolon, closing brace or bracket) to be complete.
if (!lastNode.IsKind(SyntaxKind.GlobalStatement))
{
var closingToken = lastNode.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true);
return !closingToken.IsMissing;
}
var globalStatement = (GlobalStatementSyntax)lastNode;
var token = lastNode.GetLastToken(includeZeroWidth: true, includeSkipped: true, includeDirectives: true, includeDocumentationComments: true);
if (token.IsMissing)
{
// expression statement terminating semicolon might be missing in script code:
if (tree.Options.Kind == SourceCodeKind.Regular ||
!globalStatement.Statement.IsKind(SyntaxKind.ExpressionStatement) ||
!token.IsKind(SyntaxKind.SemicolonToken))
{
return false;
}
token = token.GetPreviousToken(predicate: SyntaxToken.Any, stepInto: CodeAnalysis.SyntaxTrivia.Any);
if (token.IsMissing)
{
return false;
}
}
foreach (var error in token.GetDiagnostics())
{
switch ((ErrorCode)error.Code)
{
// unterminated character or string literal:
case ErrorCode.ERR_NewlineInConst:
// unterminated verbatim string literal:
case ErrorCode.ERR_UnterminatedStringLit:
// unexpected token following a global statement:
case ErrorCode.ERR_GlobalDefinitionOrStatementExpected:
case ErrorCode.ERR_EOFExpected:
return false;
}
}
return true;
}
private static bool HasUnterminatedMultiLineComment(SyntaxTriviaList triviaList)
{
foreach (var trivia in triviaList)
{
if (trivia.ContainsDiagnostics && trivia.Kind() == SyntaxKind.MultiLineCommentTrivia)
{
return true;
}
}
return false;
}
/// <summary>Creates a new CaseSwitchLabelSyntax instance.</summary>
public static CaseSwitchLabelSyntax CaseSwitchLabel(ExpressionSyntax value)
{
return SyntaxFactory.CaseSwitchLabel(SyntaxFactory.Token(SyntaxKind.CaseKeyword), value, SyntaxFactory.Token(SyntaxKind.ColonToken));
}
/// <summary>Creates a new DefaultSwitchLabelSyntax instance.</summary>
public static DefaultSwitchLabelSyntax DefaultSwitchLabel()
{
return SyntaxFactory.DefaultSwitchLabel(SyntaxFactory.Token(SyntaxKind.DefaultKeyword), SyntaxFactory.Token(SyntaxKind.ColonToken));
}
/// <summary>Creates a new BlockSyntax instance.</summary>
public static BlockSyntax Block(params StatementSyntax[] statements)
{
return Block(List(statements));
}
/// <summary>Creates a new BlockSyntax instance.</summary>
public static BlockSyntax Block(IEnumerable<StatementSyntax> statements)
{
return Block(List(statements));
}
public static PropertyDeclarationSyntax PropertyDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
TypeSyntax type,
ExplicitInterfaceSpecifierSyntax? explicitInterfaceSpecifier,
SyntaxToken identifier,
AccessorListSyntax accessorList)
{
return SyntaxFactory.PropertyDeclaration(
attributeLists,
modifiers,
type,
explicitInterfaceSpecifier,
identifier,
accessorList,
expressionBody: null,
initializer: null);
}
public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
SyntaxToken implicitOrExplicitKeyword,
SyntaxToken operatorKeyword,
TypeSyntax type,
ParameterListSyntax parameterList,
BlockSyntax? body,
SyntaxToken semicolonToken)
{
return SyntaxFactory.ConversionOperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
implicitOrExplicitKeyword: implicitOrExplicitKeyword,
operatorKeyword: operatorKeyword,
type: type,
parameterList: parameterList,
body: body,
expressionBody: null,
semicolonToken: semicolonToken);
}
public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers,
SyntaxToken implicitOrExplicitKeyword,
SyntaxToken operatorKeyword,
TypeSyntax type,
ParameterListSyntax parameterList,
BlockSyntax? body,
ArrowExpressionClauseSyntax? expressionBody,
SyntaxToken semicolonToken)
{
return SyntaxFactory.ConversionOperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
implicitOrExplicitKeyword: implicitOrExplicitKeyword,
explicitInterfaceSpecifier: null,
operatorKeyword: operatorKeyword,
type: type,
parameterList: parameterList,
body: body,
expressionBody: expressionBody,
semicolonToken: semicolonToken);
}
public static ConversionOperatorDeclarationSyntax ConversionOperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
SyntaxToken implicitOrExplicitKeyword,
TypeSyntax type,
ParameterListSyntax parameterList,
BlockSyntax? body,
ArrowExpressionClauseSyntax? expressionBody)
{
return SyntaxFactory.ConversionOperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
implicitOrExplicitKeyword: implicitOrExplicitKeyword,
explicitInterfaceSpecifier: null,
type: type,
parameterList: parameterList,
body: body,
expressionBody: expressionBody);
}
/// <summary>Creates a new OperatorDeclarationSyntax instance.</summary>
public static OperatorDeclarationSyntax OperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
TypeSyntax returnType,
SyntaxToken operatorKeyword,
SyntaxToken operatorToken,
ParameterListSyntax parameterList,
BlockSyntax? body,
SyntaxToken semicolonToken)
{
return SyntaxFactory.OperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
returnType: returnType,
operatorKeyword: operatorKeyword,
operatorToken: operatorToken,
parameterList: parameterList,
body: body,
expressionBody: null,
semicolonToken: semicolonToken);
}
/// <summary>Creates a new OperatorDeclarationSyntax instance.</summary>
public static OperatorDeclarationSyntax OperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
TypeSyntax returnType,
SyntaxToken operatorKeyword,
SyntaxToken operatorToken,
ParameterListSyntax parameterList,
BlockSyntax? body,
ArrowExpressionClauseSyntax? expressionBody,
SyntaxToken semicolonToken)
{
return SyntaxFactory.OperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
returnType: returnType,
explicitInterfaceSpecifier: null,
operatorKeyword: operatorKeyword,
operatorToken: operatorToken,
parameterList: parameterList,
body: body,
expressionBody: expressionBody,
semicolonToken: semicolonToken);
}
/// <summary>Creates a new OperatorDeclarationSyntax instance.</summary>
public static OperatorDeclarationSyntax OperatorDeclaration(
SyntaxList<AttributeListSyntax> attributeLists,
SyntaxTokenList modifiers,
TypeSyntax returnType,
SyntaxToken operatorToken,
ParameterListSyntax parameterList,
BlockSyntax? body,
ArrowExpressionClauseSyntax? expressionBody)
{
return SyntaxFactory.OperatorDeclaration(
attributeLists: attributeLists,
modifiers: modifiers,
returnType: returnType,
explicitInterfaceSpecifier: null,
operatorToken: operatorToken,
parameterList: parameterList,
body: body,
expressionBody: expressionBody);
}
/// <summary>Creates a new UsingDirectiveSyntax instance.</summary>
public static UsingDirectiveSyntax UsingDirective(NameEqualsSyntax alias, NameSyntax name)
{
return UsingDirective(
usingKeyword: Token(SyntaxKind.UsingKeyword),
staticKeyword: default(SyntaxToken),
alias: alias,
name: name,
semicolonToken: Token(SyntaxKind.SemicolonToken));
}
public static UsingDirectiveSyntax UsingDirective(SyntaxToken usingKeyword, SyntaxToken staticKeyword, NameEqualsSyntax? alias, NameSyntax name, SyntaxToken semicolonToken)
{
return UsingDirective(globalKeyword: default(SyntaxToken), usingKeyword, staticKeyword, alias, name, semicolonToken);
}
/// <summary>Creates a new ClassOrStructConstraintSyntax instance.</summary>
public static ClassOrStructConstraintSyntax ClassOrStructConstraint(SyntaxKind kind, SyntaxToken classOrStructKeyword)
{
return ClassOrStructConstraint(kind, classOrStructKeyword, questionToken: default(SyntaxToken));
}
// backwards compatibility for extended API
public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, BlockSyntax body)
=> SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, body, expressionBody: null);
public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, BlockSyntax body, SyntaxToken semicolonToken)
=> SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, keyword, body, expressionBody: null, semicolonToken);
public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, ArrowExpressionClauseSyntax expressionBody)
=> SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, body: null, expressionBody);
public static AccessorDeclarationSyntax AccessorDeclaration(SyntaxKind kind, SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken keyword, ArrowExpressionClauseSyntax expressionBody, SyntaxToken semicolonToken)
=> SyntaxFactory.AccessorDeclaration(kind, attributeLists, modifiers, keyword, body: null, expressionBody, semicolonToken);
public static EnumMemberDeclarationSyntax EnumMemberDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxToken identifier, EqualsValueClauseSyntax? equalsValue)
=> EnumMemberDeclaration(attributeLists, modifiers: default,
identifier, equalsValue);
public static NamespaceDeclarationSyntax NamespaceDeclaration(NameSyntax name, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members)
=> NamespaceDeclaration(attributeLists: default, modifiers: default,
name, externs, usings, members);
public static NamespaceDeclarationSyntax NamespaceDeclaration(SyntaxToken namespaceKeyword, NameSyntax name, SyntaxToken openBraceToken, SyntaxList<ExternAliasDirectiveSyntax> externs, SyntaxList<UsingDirectiveSyntax> usings, SyntaxList<MemberDeclarationSyntax> members, SyntaxToken closeBraceToken, SyntaxToken semicolonToken)
=> NamespaceDeclaration(attributeLists: default, modifiers: default,
namespaceKeyword, name, openBraceToken, externs, usings, members, closeBraceToken, semicolonToken);
/// <summary>Creates a new EventDeclarationSyntax instance.</summary>
public static EventDeclarationSyntax EventDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, AccessorListSyntax accessorList)
{
return EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList, semicolonToken: default);
}
/// <summary>Creates a new EventDeclarationSyntax instance.</summary>
public static EventDeclarationSyntax EventDeclaration(SyntaxList<AttributeListSyntax> attributeLists, SyntaxTokenList modifiers, SyntaxToken eventKeyword, TypeSyntax type, ExplicitInterfaceSpecifierSyntax explicitInterfaceSpecifier, SyntaxToken identifier, SyntaxToken semicolonToken)
{
return EventDeclaration(attributeLists, modifiers, eventKeyword, type, explicitInterfaceSpecifier, identifier, accessorList: null, semicolonToken);
}
/// <summary>Creates a new SwitchStatementSyntax instance.</summary>
public static SwitchStatementSyntax SwitchStatement(ExpressionSyntax expression, SyntaxList<SwitchSectionSyntax> sections)
{
bool needsParens = !(expression is TupleExpressionSyntax);
var openParen = needsParens ? SyntaxFactory.Token(SyntaxKind.OpenParenToken) : default;
var closeParen = needsParens ? SyntaxFactory.Token(SyntaxKind.CloseParenToken) : default;
return SyntaxFactory.SwitchStatement(
attributeLists: default,
SyntaxFactory.Token(SyntaxKind.SwitchKeyword),
openParen,
expression,
closeParen,
SyntaxFactory.Token(SyntaxKind.OpenBraceToken),
sections,
SyntaxFactory.Token(SyntaxKind.CloseBraceToken));
}
/// <summary>Creates a new SwitchStatementSyntax instance.</summary>
public static SwitchStatementSyntax SwitchStatement(ExpressionSyntax expression)
{
return SyntaxFactory.SwitchStatement(expression, default(SyntaxList<SwitchSectionSyntax>));
}
public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(ParameterSyntax parameter, CSharpSyntaxNode body)
=> body is BlockSyntax block
? SimpleLambdaExpression(parameter, block, null)
: SimpleLambdaExpression(parameter, null, (ExpressionSyntax)body);
public static SimpleLambdaExpressionSyntax SimpleLambdaExpression(SyntaxToken asyncKeyword, ParameterSyntax parameter, SyntaxToken arrowToken, CSharpSyntaxNode body)
=> body is BlockSyntax block
? SimpleLambdaExpression(asyncKeyword, parameter, arrowToken, block, null)
: SimpleLambdaExpression(asyncKeyword, parameter, arrowToken, null, (ExpressionSyntax)body);
public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(CSharpSyntaxNode body)
=> ParenthesizedLambdaExpression(ParameterList(), body);
public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(ParameterListSyntax parameterList, CSharpSyntaxNode body)
=> body is BlockSyntax block
? ParenthesizedLambdaExpression(parameterList, block, null)
: ParenthesizedLambdaExpression(parameterList, null, (ExpressionSyntax)body);
public static ParenthesizedLambdaExpressionSyntax ParenthesizedLambdaExpression(SyntaxToken asyncKeyword, ParameterListSyntax parameterList, SyntaxToken arrowToken, CSharpSyntaxNode body)
=> body is BlockSyntax block
? ParenthesizedLambdaExpression(asyncKeyword, parameterList, arrowToken, block, null)
: ParenthesizedLambdaExpression(asyncKeyword, parameterList, arrowToken, null, (ExpressionSyntax)body);
public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(CSharpSyntaxNode body)
=> AnonymousMethodExpression(parameterList: null, body);
public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(ParameterListSyntax? parameterList, CSharpSyntaxNode body)
=> body is BlockSyntax block
? AnonymousMethodExpression(default(SyntaxTokenList), SyntaxFactory.Token(SyntaxKind.DelegateKeyword), parameterList, block, null)
: throw new ArgumentException(nameof(body));
public static AnonymousMethodExpressionSyntax AnonymousMethodExpression(SyntaxToken asyncKeyword, SyntaxToken delegateKeyword, ParameterListSyntax parameterList, CSharpSyntaxNode body)
=> body is BlockSyntax block
? AnonymousMethodExpression(asyncKeyword, delegateKeyword, parameterList, block, null)
: throw new ArgumentException(nameof(body));
// BACK COMPAT OVERLOAD DO NOT MODIFY
[Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static SyntaxTree ParseSyntaxTree(
string text,
ParseOptions? options,
string path,
Encoding? encoding,
ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions,
CancellationToken cancellationToken)
{
return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken);
}
// BACK COMPAT OVERLOAD DO NOT MODIFY
[Obsolete("The diagnosticOptions parameter is obsolete due to performance problems, if you are passing non-null use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
[EditorBrowsable(EditorBrowsableState.Never)]
public static SyntaxTree ParseSyntaxTree(
SourceText text,
ParseOptions? options,
string path,
ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions,
CancellationToken cancellationToken)
{
return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, diagnosticOptions, isGeneratedCode: null, cancellationToken);
}
// BACK COMPAT OVERLOAD DO NOT MODIFY
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
public static SyntaxTree ParseSyntaxTree(
string text,
ParseOptions? options,
string path,
Encoding? encoding,
ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions,
bool? isGeneratedCode,
CancellationToken cancellationToken)
{
return ParseSyntaxTree(SourceText.From(text, encoding), options, path, diagnosticOptions, isGeneratedCode, cancellationToken);
}
// BACK COMPAT OVERLOAD DO NOT MODIFY
[EditorBrowsable(EditorBrowsableState.Never)]
[Obsolete("The diagnosticOptions and isGeneratedCode parameters are obsolete due to performance problems, if you are using them use CompilationOptions.SyntaxTreeOptionsProvider instead", error: false)]
public static SyntaxTree ParseSyntaxTree(
SourceText text,
ParseOptions? options,
string path,
ImmutableDictionary<string, ReportDiagnostic>? diagnosticOptions,
bool? isGeneratedCode,
CancellationToken cancellationToken)
{
return CSharpSyntaxTree.ParseText(text, (CSharpParseOptions?)options, path, diagnosticOptions, isGeneratedCode, cancellationToken);
}
}
}
| 49.931472 | 335 | 0.633072 | [
"MIT"
] | Evangelink/roslyn | src/Compilers/CSharp/Portable/Syntax/SyntaxFactory.cs | 137,713 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
[RequireComponent(typeof(TMPro.TextMeshProUGUI))]
public class DebugLabel : MonoBehaviour
{
[Header("Debug Label Settings")]
[SerializeField]
protected string label;
private TMPro.TextMeshProUGUI text;
private static List<DebugLabel> labels = new List<DebugLabel>();
public static DebugLabel GetLabel(string name)
{
foreach (var i in labels)
{
if (i.label == name) return i;
}
throw new System.Exception("Cannot find debug label with designation \"" + name + "\".\n" + UnityEngine.StackTraceUtility.ExtractStackTrace());
}
/// <summary>
/// Shorthand for GetLabel(name).SetText(text);
/// </summary>
/// <param name="name">The title of the debug label.</param>
/// <param name="text">The text you want to set.</param>
public static void SetLabelText(string name, string text)
{
GetLabel(name).SetText(text);
}
/// <summary>
/// Shorthand for GetLabel(name).AppendText(text);
/// </summary>
/// <param name="name">The title of the debug label.</param>
/// <param name="text">The text you want to set.</param>
public static void AppendLabelText(string name, string text)
{
GetLabel(name).AppendText(text);
}
public void SetText(string newText)
{
text.text = newText;
}
public void AppendText(string newText)
{
text.text += newText;
}
public TMPro.TextMeshProUGUI GetTMProComponent()
{
return text;
}
void Awake()
{
if (label == "") Debug.LogWarning("Debug text has no label.", this);
text = GetComponent<TMPro.TextMeshProUGUI>();
text.text = "";
labels.Add(this);
}
void Update()
{
}
}
| 25.875 | 151 | 0.611916 | [
"MIT"
] | Liam-Harrison/Battle-RPG-Demonstration | Assets/Scripts/Utilities/DebugLabel.cs | 1,865 | C# |
// This is free and unencumbered software released into the public domain.
//
// Anyone is free to copy, modify, publish, use, compile, sell, or
// distribute this software, either in source code form or as a compiled
// binary, for any purpose, commercial or non-commercial, and by any
// means.
//
// In jurisdictions that recognize copyright laws, the author or authors
// of this software dedicate any and all copyright interest in the
// software to the public domain. We make this dedication for the benefit
// of the public at large and to the detriment of our heirs and
// successors. We intend this dedication to be an overt act of
// relinquishment in perpetuity of all present and future rights to this
// software under copyright law.
//
// 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 NON-INFRINGEMENT.
// IN NO EVENT SHALL THE AUTHORS 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.
//
// For more information, please refer to <http://unlicense.org/>
using System;
namespace Ubiety.Scram.Core.Attributes
{
/// <summary>
/// Client proof attribute.
/// </summary>
public class ClientProofAttribute : ScramAttribute<byte[]>
{
/// <summary>
/// Initializes a new instance of the <see cref="ClientProofAttribute"/> class.
/// </summary>
/// <param name="value">String value of the client proof.</param>
public ClientProofAttribute(string value)
: base(ClientProofName, Convert.FromBase64String(value))
{
}
/// <summary>
/// Initializes a new instance of the <see cref="ClientProofAttribute"/> class.
/// </summary>
/// <param name="value">Byte array value of the client proof.</param>
public ClientProofAttribute(byte[] value)
: base(ClientProofName, value)
{
}
/// <inheritdoc/>
public override string ToString()
{
return $"{Name}={Convert.ToBase64String(Value)}";
}
}
}
| 38.633333 | 91 | 0.672994 | [
"Unlicense"
] | ubiety/Ubiety.Scram.Core | src/Ubiety.Scram.Core/Attributes/ClientProofAttribute.cs | 2,320 | 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.Globalization;
namespace BuildXL.ViewModel
{
/// <nodoc />
public class BuildSummaryPipDiagnostic
{
/// <nodoc />
public string SemiStablePipId { get; set; }
/// <nodoc />
public string PipDescription { get; set; }
/// <nodoc />
public string SpecPath { get; set; }
/// <nodoc />
public string ToolName { get; set; }
/// <nodoc />
public int ExitCode { get; set; }
/// <nodoc />
public string Output { get; set; }
/// <nodoc />
internal void RenderMarkDown(MarkDownWriter writer)
{
writer.WriteRaw("### <span style=\"font - family:consolas; monospace\">");
writer.WriteText(PipDescription);
writer.WriteRaw("</span> failed with exit code ");
writer.WriteLineRaw(ExitCode.ToString(CultureInfo.InvariantCulture));
writer.StartDetails("Pip Details");
writer.StartTable();
WriteKeyValuePair(writer, "PipHash:", SemiStablePipId, true);
WriteKeyValuePair(writer, "Pip:", PipDescription, true);
WriteKeyValuePair(writer, "Spec:", SpecPath, true);
WriteKeyValuePair(writer, "Tool:", ToolName, true);
WriteKeyValuePair(writer, "Exit Code:", ExitCode.ToString(CultureInfo.InvariantCulture), true);
writer.EndTable();
writer.EndDetails();
if (!string.IsNullOrEmpty(Output))
{
writer.WritePre(Output);
}
}
private void WriteKeyValuePair(MarkDownWriter writer, string key, string value, bool fixedFont)
{
writer.StartElement("tr");
writer.StartElement("td", "text-align:left;vertical-align: text-top;min-width:5em");
writer.WriteText(key);
writer.EndElement("td");
writer.StartElement("td");
if (fixedFont)
{
writer.StartElement("span", "font-family:consolas;monospace");
}
writer.WriteText(value);
if (fixedFont)
{
writer.EndElement("span");
}
writer.EndElement("td");
writer.EndElement("tr");
}
}
}
| 32.714286 | 108 | 0.542279 | [
"MIT"
] | breidikl/BuildXL | Public/Src/Engine/ViewModel/BuildSummaryPipDiagnostic.cs | 2,521 | C# |
// Copyright (c) Microsoft. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for full license information.
namespace Microsoft.DocAsCode.MarkdownLite
{
using System.Collections.Generic;
using System.Collections.Immutable;
using System.Linq;
public static class MarkdownTokenTreeValidatorFactory
{
public static readonly IMarkdownTokenTreeValidator Null = new NullTokenTreeValidator();
public static IMarkdownTokenTreeValidator Combine(
params IMarkdownTokenTreeValidator[] validators)
{
return Combine((IEnumerable<IMarkdownTokenTreeValidator>)validators);
}
public static IMarkdownTokenTreeValidator Combine(
IEnumerable<IMarkdownTokenTreeValidator> validators)
{
if (validators == null)
{
return Null;
}
var array = (from v in validators
where v != null && v != Null
select v).ToArray();
if (array.Length == 0)
{
return Null;
}
return new CompositeTokenTreeValidator(array);
}
private sealed class NullTokenTreeValidator : IMarkdownTokenTreeValidator
{
public void Validate(ImmutableArray<IMarkdownToken> tokens)
{
}
}
private sealed class CompositeTokenTreeValidator
: IMarkdownTokenTreeValidator
{
private IMarkdownTokenTreeValidator[] _validators;
public CompositeTokenTreeValidator(IMarkdownTokenTreeValidator[] validators)
{
_validators = validators;
}
public void Validate(ImmutableArray<IMarkdownToken> tokens)
{
foreach (var v in _validators)
{
v.Validate(tokens);
}
}
}
}
}
| 32.171875 | 102 | 0.565323 | [
"MIT"
] | Algorithman/docfx | src/Microsoft.DocAsCode.MarkdownLite/Validators/MarkdownTokenTreeValidatorFactory.cs | 1,998 | C# |
//Missão referente ao terceiro dia de jogo -> player ir até a cidade do leste, na casa do capitão e interagrir com ela
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
public class Porta_Leste : MonoBehaviour {
Vector3 Dist;
public bool final3 = false;
float posiX,posiY;
public bool podeInteragir=false;
GUIStyle guiStyle = new GUIStyle();
bool conversa=false;
private CharacterBase cb;
private GameObject c;//Completou Missao
// Use this for initialization
void Start () {
Dist = GameObject.Find ("Player").transform.position;
Dist = Dist - transform.position;
guiStyle.alignment = TextAnchor.MiddleCenter;
cb = GameObject.Find ("Player").GetComponent<PlayerBehaviour> ();
c = GameObject.Find("Congratulations");
StartCoroutine (Wait());
}
IEnumerator Wait(){
yield return new WaitForSecondsRealtime (3);
//c.SetActive (false);
}
void Update(){
Dist = GameObject.Find ("Player").transform.position;
Dist = Dist - transform.position;
}
// Update is called once per frame
void OnGUI(){
posiX = 0;
posiY = Screen.height / 2 + Screen.height / 5;
if (Dist.magnitude < 2)
podeInteragir = true;
else
podeInteragir = false;
if (conversa == false && podeInteragir == true) {
//Menssagem de interagir ao chegar na casa no terceiro dia
guiStyle.fontSize = 20;
GUI.Box (new Rect (0, posiY + 20, 1000, 100), "Interagir- ENTER", guiStyle);
//se o usuario apertar enter a conversa vai começar
if (Input.GetKeyDown (KeyCode.Return)) {
conversa = true;
}
}
if (conversa) {//Texto apresentado no fim da missão ao se encontrar e coletar o machado
conversa = false;
cb.Aumentarxp (250);
c.SetActive(true);
c.transform.GetChild(0).GetChild(1).GetComponent<Text>().text = ("A casa parece fechada a dias. \n Suspeito que Petr tenha sido enviado a alguma missão. \n Acho que devo ir a Verus conversar com os soldados.");
c.transform.GetChild(0).GetChild(3).GetComponent<Text>().text = ("250 Pontos de Experiência");
c.GetComponent<Animation>().enabled=true;
if (Input.GetKey (KeyCode.Return) || Input.GetKey (KeyCode.KeypadEnter)) {
c.GetComponent<Animation>().enabled=false;
c.SetActive(false);
enabled = false;
}
final3 = true;
}
}
}
| 33.231884 | 213 | 0.70519 | [
"MIT"
] | heitor57/One-Week | Assets/Porta_Leste.cs | 2,302 | C# |
/*----------------------------------------------------------------------------------
// Copyright 2019 Huawei Technologies Co.,Ltd.
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use
// this file except in compliance with the License. You may obtain a copy of the
// License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
//----------------------------------------------------------------------------------*/
using System.Collections.Generic;
namespace OBS.Model
{
/// <summary>
/// Bucket CORS configuration
/// </summary>
public class CorsConfiguration
{
private IList<CorsRule> rules;
/// <summary>
/// Bucket CORS rule list
/// </summary>
/// <remarks>
/// <para>
/// Mandatory parameter
/// </para>
/// </remarks>
public IList<CorsRule> Rules
{
get {
return this.rules ?? (this.rules = new List<CorsRule>()); }
set { this.rules = value; }
}
}
}
| 31.26087 | 87 | 0.51669 | [
"ECL-2.0",
"Apache-2.0"
] | he1a2s0/huaweicloud-sdk-dotnet-obs | Model/CorsConfiguration.cs | 1,438 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Text.Json;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.Network.Models;
namespace Azure.ResourceManager.Network
{
internal partial class LoadBalancerBackendAddressPoolsRestOperations
{
private Uri endpoint;
private string apiVersion;
private ClientDiagnostics _clientDiagnostics;
private HttpPipeline _pipeline;
private readonly string _userAgent;
/// <summary> Initializes a new instance of LoadBalancerBackendAddressPoolsRestOperations. </summary>
/// <param name="clientDiagnostics"> The handler for diagnostic messaging in the client. </param>
/// <param name="pipeline"> The HTTP pipeline for sending and receiving REST requests and responses. </param>
/// <param name="applicationId"> The application id to use for user agent. </param>
/// <param name="endpoint"> server parameter. </param>
/// <param name="apiVersion"> Api Version. </param>
/// <exception cref="ArgumentNullException"> <paramref name="apiVersion"/> is null. </exception>
public LoadBalancerBackendAddressPoolsRestOperations(ClientDiagnostics clientDiagnostics, HttpPipeline pipeline, string applicationId, Uri endpoint = null, string apiVersion = default)
{
this.endpoint = endpoint ?? new Uri("https://management.azure.com");
this.apiVersion = apiVersion ?? "2021-02-01";
_clientDiagnostics = clientDiagnostics;
_pipeline = pipeline;
_userAgent = Core.HttpMessageUtilities.GetUserAgentName(this, applicationId);
}
internal HttpMessage CreateListRequest(string subscriptionId, string resourceGroupName, string loadBalancerName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/loadBalancers/", false);
uri.AppendPath(loadBalancerName, true);
uri.AppendPath("/backendAddressPools", false);
uri.AppendQuery("api-version", apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("UserAgentOverride", _userAgent);
return message;
}
/// <summary> Gets all the load balancer backed address pools. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="loadBalancerName"/> is null. </exception>
public async Task<Response<LoadBalancerBackendAddressPoolListResult>> ListAsync(string subscriptionId, string resourceGroupName, string loadBalancerName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (loadBalancerName == null)
{
throw new ArgumentNullException(nameof(loadBalancerName));
}
using var message = CreateListRequest(subscriptionId, resourceGroupName, loadBalancerName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
LoadBalancerBackendAddressPoolListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = LoadBalancerBackendAddressPoolListResult.DeserializeLoadBalancerBackendAddressPoolListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets all the load balancer backed address pools. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="loadBalancerName"/> is null. </exception>
public Response<LoadBalancerBackendAddressPoolListResult> List(string subscriptionId, string resourceGroupName, string loadBalancerName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (loadBalancerName == null)
{
throw new ArgumentNullException(nameof(loadBalancerName));
}
using var message = CreateListRequest(subscriptionId, resourceGroupName, loadBalancerName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
LoadBalancerBackendAddressPoolListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = LoadBalancerBackendAddressPoolListResult.DeserializeLoadBalancerBackendAddressPoolListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateGetRequest(string subscriptionId, string resourceGroupName, string loadBalancerName, string backendAddressPoolName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/loadBalancers/", false);
uri.AppendPath(loadBalancerName, true);
uri.AppendPath("/backendAddressPools/", false);
uri.AppendPath(backendAddressPoolName, true);
uri.AppendQuery("api-version", apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("UserAgentOverride", _userAgent);
return message;
}
/// <summary> Gets load balancer backend address pool. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="backendAddressPoolName"> The name of the backend address pool. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="loadBalancerName"/>, or <paramref name="backendAddressPoolName"/> is null. </exception>
public async Task<Response<BackendAddressPoolData>> GetAsync(string subscriptionId, string resourceGroupName, string loadBalancerName, string backendAddressPoolName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (loadBalancerName == null)
{
throw new ArgumentNullException(nameof(loadBalancerName));
}
if (backendAddressPoolName == null)
{
throw new ArgumentNullException(nameof(backendAddressPoolName));
}
using var message = CreateGetRequest(subscriptionId, resourceGroupName, loadBalancerName, backendAddressPoolName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
BackendAddressPoolData value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = BackendAddressPoolData.DeserializeBackendAddressPoolData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((BackendAddressPoolData)null, message.Response);
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets load balancer backend address pool. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="backendAddressPoolName"> The name of the backend address pool. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="loadBalancerName"/>, or <paramref name="backendAddressPoolName"/> is null. </exception>
public Response<BackendAddressPoolData> Get(string subscriptionId, string resourceGroupName, string loadBalancerName, string backendAddressPoolName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (loadBalancerName == null)
{
throw new ArgumentNullException(nameof(loadBalancerName));
}
if (backendAddressPoolName == null)
{
throw new ArgumentNullException(nameof(backendAddressPoolName));
}
using var message = CreateGetRequest(subscriptionId, resourceGroupName, loadBalancerName, backendAddressPoolName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
BackendAddressPoolData value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = BackendAddressPoolData.DeserializeBackendAddressPoolData(document.RootElement);
return Response.FromValue(value, message.Response);
}
case 404:
return Response.FromValue((BackendAddressPoolData)null, message.Response);
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateCreateOrUpdateRequest(string subscriptionId, string resourceGroupName, string loadBalancerName, string backendAddressPoolName, BackendAddressPoolData parameters)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Put;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/loadBalancers/", false);
uri.AppendPath(loadBalancerName, true);
uri.AppendPath("/backendAddressPools/", false);
uri.AppendPath(backendAddressPoolName, true);
uri.AppendQuery("api-version", apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
request.Headers.Add("Content-Type", "application/json");
var content = new Utf8JsonRequestContent();
content.JsonWriter.WriteObjectValue(parameters);
request.Content = content;
message.SetProperty("UserAgentOverride", _userAgent);
return message;
}
/// <summary> Creates or updates a load balancer backend address pool. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="backendAddressPoolName"> The name of the backend address pool. </param>
/// <param name="parameters"> Parameters supplied to the create or update load balancer backend address pool operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="loadBalancerName"/>, <paramref name="backendAddressPoolName"/>, or <paramref name="parameters"/> is null. </exception>
public async Task<Response> CreateOrUpdateAsync(string subscriptionId, string resourceGroupName, string loadBalancerName, string backendAddressPoolName, BackendAddressPoolData parameters, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (loadBalancerName == null)
{
throw new ArgumentNullException(nameof(loadBalancerName));
}
if (backendAddressPoolName == null)
{
throw new ArgumentNullException(nameof(backendAddressPoolName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, loadBalancerName, backendAddressPoolName, parameters);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 201:
return message.Response;
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Creates or updates a load balancer backend address pool. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="backendAddressPoolName"> The name of the backend address pool. </param>
/// <param name="parameters"> Parameters supplied to the create or update load balancer backend address pool operation. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="loadBalancerName"/>, <paramref name="backendAddressPoolName"/>, or <paramref name="parameters"/> is null. </exception>
public Response CreateOrUpdate(string subscriptionId, string resourceGroupName, string loadBalancerName, string backendAddressPoolName, BackendAddressPoolData parameters, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (loadBalancerName == null)
{
throw new ArgumentNullException(nameof(loadBalancerName));
}
if (backendAddressPoolName == null)
{
throw new ArgumentNullException(nameof(backendAddressPoolName));
}
if (parameters == null)
{
throw new ArgumentNullException(nameof(parameters));
}
using var message = CreateCreateOrUpdateRequest(subscriptionId, resourceGroupName, loadBalancerName, backendAddressPoolName, parameters);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 201:
return message.Response;
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateDeleteRequest(string subscriptionId, string resourceGroupName, string loadBalancerName, string backendAddressPoolName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Delete;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendPath("/subscriptions/", false);
uri.AppendPath(subscriptionId, true);
uri.AppendPath("/resourceGroups/", false);
uri.AppendPath(resourceGroupName, true);
uri.AppendPath("/providers/Microsoft.Network/loadBalancers/", false);
uri.AppendPath(loadBalancerName, true);
uri.AppendPath("/backendAddressPools/", false);
uri.AppendPath(backendAddressPoolName, true);
uri.AppendQuery("api-version", apiVersion, true);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("UserAgentOverride", _userAgent);
return message;
}
/// <summary> Deletes the specified load balancer backend address pool. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="backendAddressPoolName"> The name of the backend address pool. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="loadBalancerName"/>, or <paramref name="backendAddressPoolName"/> is null. </exception>
public async Task<Response> DeleteAsync(string subscriptionId, string resourceGroupName, string loadBalancerName, string backendAddressPoolName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (loadBalancerName == null)
{
throw new ArgumentNullException(nameof(loadBalancerName));
}
if (backendAddressPoolName == null)
{
throw new ArgumentNullException(nameof(backendAddressPoolName));
}
using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, loadBalancerName, backendAddressPoolName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
case 202:
case 204:
return message.Response;
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Deletes the specified load balancer backend address pool. </summary>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="backendAddressPoolName"> The name of the backend address pool. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, <paramref name="loadBalancerName"/>, or <paramref name="backendAddressPoolName"/> is null. </exception>
public Response Delete(string subscriptionId, string resourceGroupName, string loadBalancerName, string backendAddressPoolName, CancellationToken cancellationToken = default)
{
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (loadBalancerName == null)
{
throw new ArgumentNullException(nameof(loadBalancerName));
}
if (backendAddressPoolName == null)
{
throw new ArgumentNullException(nameof(backendAddressPoolName));
}
using var message = CreateDeleteRequest(subscriptionId, resourceGroupName, loadBalancerName, backendAddressPoolName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
case 202:
case 204:
return message.Response;
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
internal HttpMessage CreateListNextPageRequest(string nextLink, string subscriptionId, string resourceGroupName, string loadBalancerName)
{
var message = _pipeline.CreateMessage();
var request = message.Request;
request.Method = RequestMethod.Get;
var uri = new RawRequestUriBuilder();
uri.Reset(endpoint);
uri.AppendRawNextLink(nextLink, false);
request.Uri = uri;
request.Headers.Add("Accept", "application/json");
message.SetProperty("UserAgentOverride", _userAgent);
return message;
}
/// <summary> Gets all the load balancer backed address pools. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="loadBalancerName"/> is null. </exception>
public async Task<Response<LoadBalancerBackendAddressPoolListResult>> ListNextPageAsync(string nextLink, string subscriptionId, string resourceGroupName, string loadBalancerName, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (loadBalancerName == null)
{
throw new ArgumentNullException(nameof(loadBalancerName));
}
using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName, loadBalancerName);
await _pipeline.SendAsync(message, cancellationToken).ConfigureAwait(false);
switch (message.Response.Status)
{
case 200:
{
LoadBalancerBackendAddressPoolListResult value = default;
using var document = await JsonDocument.ParseAsync(message.Response.ContentStream, default, cancellationToken).ConfigureAwait(false);
value = LoadBalancerBackendAddressPoolListResult.DeserializeLoadBalancerBackendAddressPoolListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw await _clientDiagnostics.CreateRequestFailedExceptionAsync(message.Response).ConfigureAwait(false);
}
}
/// <summary> Gets all the load balancer backed address pools. </summary>
/// <param name="nextLink"> The URL to the next page of results. </param>
/// <param name="subscriptionId"> The subscription credentials which uniquely identify the Microsoft Azure subscription. The subscription ID forms part of the URI for every service call. </param>
/// <param name="resourceGroupName"> The name of the resource group. </param>
/// <param name="loadBalancerName"> The name of the load balancer. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <exception cref="ArgumentNullException"> <paramref name="nextLink"/>, <paramref name="subscriptionId"/>, <paramref name="resourceGroupName"/>, or <paramref name="loadBalancerName"/> is null. </exception>
public Response<LoadBalancerBackendAddressPoolListResult> ListNextPage(string nextLink, string subscriptionId, string resourceGroupName, string loadBalancerName, CancellationToken cancellationToken = default)
{
if (nextLink == null)
{
throw new ArgumentNullException(nameof(nextLink));
}
if (subscriptionId == null)
{
throw new ArgumentNullException(nameof(subscriptionId));
}
if (resourceGroupName == null)
{
throw new ArgumentNullException(nameof(resourceGroupName));
}
if (loadBalancerName == null)
{
throw new ArgumentNullException(nameof(loadBalancerName));
}
using var message = CreateListNextPageRequest(nextLink, subscriptionId, resourceGroupName, loadBalancerName);
_pipeline.Send(message, cancellationToken);
switch (message.Response.Status)
{
case 200:
{
LoadBalancerBackendAddressPoolListResult value = default;
using var document = JsonDocument.Parse(message.Response.ContentStream);
value = LoadBalancerBackendAddressPoolListResult.DeserializeLoadBalancerBackendAddressPoolListResult(document.RootElement);
return Response.FromValue(value, message.Response);
}
default:
throw _clientDiagnostics.CreateRequestFailedException(message.Response);
}
}
}
}
| 56.532143 | 260 | 0.636869 | [
"MIT"
] | lubaozhen/azure-sdk-for-net | sdk/network/Azure.ResourceManager.Network/src/Generated/RestOperations/LoadBalancerBackendAddressPoolsRestOperations.cs | 31,658 | C# |
using DevExtreme.AspNet.Data.Aggregation;
using DevExtreme.AspNet.Data.Helpers;
using DevExtreme.AspNet.Data.Types;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
namespace DevExtreme.AspNet.Data {
partial class DataSourceLoadContext {
readonly DataSourceLoadOptionsBase _options;
readonly QueryProviderInfo _providerInfo;
readonly Type _itemType;
public DataSourceLoadContext(DataSourceLoadOptionsBase options, QueryProviderInfo providerInfo, Type itemType) {
_options = options;
_providerInfo = providerInfo;
_itemType = itemType;
}
public bool GuardNulls {
get {
#if DEBUG
if(_options.GuardNulls.HasValue)
return _options.GuardNulls.Value;
#endif
return _providerInfo.IsLinqToObjects;
}
}
public bool RequireQueryableChainBreak {
get {
if(_providerInfo.IsXPO) {
// 1. XPQuery is stateful
// 2. CreateQuery(expr) and Execute(expr) don't spawn intermediate query instances for Queryable calls within expr.
// This can put XPQuery into an invalid state. Example: Distinct().Count()
// 3. XPQuery is IQueryProvider itself
return true;
}
return false;
}
}
public AnonTypeNewTweaks CreateAnonTypeNewTweaks() => new AnonTypeNewTweaks {
AllowEmpty = !_providerInfo.IsL2S && !_providerInfo.IsMongoDB,
AllowUnusedMembers = !_providerInfo.IsL2S
};
static bool IsEmpty<T>(IReadOnlyCollection<T> collection) {
return collection == null || collection.Count < 1;
}
static bool IsEmptyList(IList list) {
return list == null || list.Count < 1;
}
}
// Total count
partial class DataSourceLoadContext {
public bool RequireTotalCount => _options.RequireTotalCount;
public bool IsCountQuery => _options.IsCountQuery;
}
// Paging
partial class DataSourceLoadContext {
public int Skip => _options.Skip;
public int Take => _options.Take;
public bool HasPaging => Skip > 0 || Take > 0;
public bool PaginateViaPrimaryKey => _options.PaginateViaPrimaryKey.GetValueOrDefault(false);
}
// Filter
partial class DataSourceLoadContext {
public IList Filter => _options.Filter;
public bool HasFilter => !IsEmptyList(_options.Filter);
public bool UseStringToLower => _options.StringToLower ?? DataSourceLoadOptionsBase.StringToLowerDefault ?? _providerInfo.IsLinqToObjects;
}
// Grouping
partial class DataSourceLoadContext {
bool?
_shouldEmptyGroups,
_useRemoteGrouping;
public bool RequireGroupCount => _options.RequireGroupCount;
public IReadOnlyList<GroupingInfo> Group => _options.Group;
public bool HasGroups => !IsEmpty(Group);
public bool ShouldEmptyGroups {
get {
if(!_shouldEmptyGroups.HasValue)
_shouldEmptyGroups = HasGroups && !Group.Last().GetIsExpanded();
return _shouldEmptyGroups.Value;
}
}
public bool UseRemoteGrouping {
get {
bool HasAvg(IEnumerable<SummaryInfo> summary) {
return summary != null && summary.Any(i => i.SummaryType == "avg");
}
bool ShouldUseRemoteGrouping() {
if(_providerInfo.IsLinqToObjects)
return false;
if(_providerInfo.IsEFCore) {
// https://github.com/aspnet/EntityFrameworkCore/issues/2341
// https://github.com/aspnet/EntityFrameworkCore/issues/11993
// https://github.com/aspnet/EntityFrameworkCore/issues/11999
if(_providerInfo.Version < new Version(2, 2, 0))
return false;
#warning Remove with https://github.com/aspnet/EntityFrameworkCore/issues/11711 fix
if(HasAvg(TotalSummary) || HasAvg(GroupSummary))
return false;
}
return true;
}
if(!_useRemoteGrouping.HasValue)
_useRemoteGrouping = _options.RemoteGrouping ?? ShouldUseRemoteGrouping();
return _useRemoteGrouping.Value;
}
}
}
// Sorting & Primary Key
partial class DataSourceLoadContext {
bool _primaryKeyAndDefaultSortEnsured;
string[] _primaryKey;
string _defaultSort;
public bool HasAnySort => HasGroups || HasSort || ShouldSortByPrimaryKey || HasDefaultSort;
bool HasSort => !IsEmpty(_options.Sort);
public IReadOnlyList<string> PrimaryKey {
get {
EnsurePrimaryKeyAndDefaultSort();
return _primaryKey;
}
}
string DefaultSort {
get {
EnsurePrimaryKeyAndDefaultSort();
return _defaultSort;
}
}
public bool HasPrimaryKey => !IsEmpty(PrimaryKey);
bool HasDefaultSort => !String.IsNullOrEmpty(DefaultSort);
bool ShouldSortByPrimaryKey => HasPrimaryKey && _options.SortByPrimaryKey.GetValueOrDefault(true);
public IEnumerable<SortingInfo> GetFullSort() {
var memo = new HashSet<string>();
var result = new List<SortingInfo>();
if(HasGroups) {
foreach(var g in Group) {
if(memo.Contains(g.Selector))
continue;
memo.Add(g.Selector);
result.Add(g);
}
}
if(HasSort) {
foreach(var s in _options.Sort) {
if(memo.Contains(s.Selector))
continue;
memo.Add(s.Selector);
result.Add(s);
}
}
IEnumerable<string> requiredSort = new string[0];
if(HasDefaultSort)
requiredSort = requiredSort.Concat(new[] { DefaultSort });
if(ShouldSortByPrimaryKey)
requiredSort = requiredSort.Concat(PrimaryKey);
return Utils.AddRequiredSort(result, requiredSort);
}
void EnsurePrimaryKeyAndDefaultSort() {
if(_primaryKeyAndDefaultSortEnsured)
return;
var primaryKey = _options.PrimaryKey;
var defaultSort = _options.DefaultSort;
if(IsEmpty(primaryKey))
primaryKey = Utils.GetPrimaryKey(_itemType);
if(HasPaging && String.IsNullOrEmpty(defaultSort) && IsEmpty(primaryKey)) {
if(_providerInfo.IsEFClassic || _providerInfo.IsEFCore)
defaultSort = EFSorting.FindSortableMember(_itemType);
else if(_providerInfo.IsXPO)
defaultSort = "this";
}
_primaryKey = primaryKey;
_defaultSort = defaultSort;
_primaryKeyAndDefaultSortEnsured = true;
}
}
// Summary
partial class DataSourceLoadContext {
bool? _summaryIsTotalCountOnly;
public IReadOnlyList<SummaryInfo> TotalSummary => _options.TotalSummary;
public IReadOnlyList<SummaryInfo> GroupSummary => _options.GroupSummary;
public bool HasSummary => HasTotalSummary || HasGroupSummary;
public bool HasTotalSummary => !IsEmpty(TotalSummary);
public bool HasGroupSummary => HasGroups && !IsEmpty(GroupSummary);
public bool SummaryIsTotalCountOnly {
get {
if(!_summaryIsTotalCountOnly.HasValue)
_summaryIsTotalCountOnly = !HasGroupSummary && HasTotalSummary && TotalSummary.All(i => i.SummaryType == AggregateName.COUNT);
return _summaryIsTotalCountOnly.Value;
}
}
public bool ExpandLinqSumType {
get {
if(_options.ExpandLinqSumType.HasValue)
return _options.ExpandLinqSumType.Value;
// NH 5.2.6: https://github.com/nhibernate/nhibernate-core/issues/2029
// EFCore 2: https://github.com/aspnet/EntityFrameworkCore/issues/14851
return _providerInfo.IsEFClassic
|| _providerInfo.IsEFCore && _providerInfo.Version.Major > 2
|| _providerInfo.IsXPO;
}
}
}
// Select
partial class DataSourceLoadContext {
string[] _fullSelect;
bool? _useRemoteSelect;
public bool HasAnySelect => FullSelect.Count > 0;
public bool UseRemoteSelect {
get {
if(!_useRemoteSelect.HasValue)
_useRemoteSelect = _options.RemoteSelect ?? (!_providerInfo.IsLinqToObjects && FullSelect.Count <= AnonType.MAX_SIZE);
return _useRemoteSelect.Value;
}
}
public IReadOnlyList<string> FullSelect {
get {
string[] Init() {
var hasSelect = !IsEmpty(_options.Select);
var hasPreSelect = !IsEmpty(_options.PreSelect);
if(hasPreSelect && hasSelect)
return Enumerable.Intersect(_options.PreSelect, _options.Select, StringComparer.OrdinalIgnoreCase).ToArray();
if(hasPreSelect)
return _options.PreSelect;
if(hasSelect)
return _options.Select;
return new string[0];
}
if(_fullSelect == null)
_fullSelect = Init();
return _fullSelect;
}
}
}
}
| 33.47351 | 146 | 0.568602 | [
"MIT"
] | AmitN-Learner/DevExtreme.AspNet.Data | net/DevExtreme.AspNet.Data/DataSourceLoadContext.cs | 10,111 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
/// <summary>
/// Descrição resumida de Locais
/// </summary>
///
namespace falconDex.Models
{
public class Local
{
public int Id { get; set; }
public String Nome { get; set; }
public String Bloco { get; set; }
public Status status { get; set; }
public Local()
{
//
// TODO: Adicionar lógica do construtor aqui
//
}
}
} | 18.357143 | 56 | 0.544747 | [
"MIT"
] | brunoaugustosilva/falconDex | App_Code/Models/Local.cs | 519 | C# |
#region License
// Copyright (c) 2009 Sander van Rossen
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
#endregion
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Drawing;
using System.ComponentModel;
using Graph.Items;
namespace Graph
{
public sealed class NodeEventArgs : EventArgs
{
public NodeEventArgs(Node node) { Node = node; }
public Node Node { get; private set; }
}
public sealed class ElementEventArgs : EventArgs
{
public ElementEventArgs(IElement element) { Element = element; }
public IElement Element { get; private set; }
}
public sealed class AcceptNodeEventArgs : CancelEventArgs
{
public AcceptNodeEventArgs(Node node) { Node = node; }
public AcceptNodeEventArgs(Node node, bool cancel) : base(cancel) { Node = node; }
public Node Node { get; private set; }
}
public sealed class AcceptElementLocationEventArgs : CancelEventArgs
{
public AcceptElementLocationEventArgs(IElement element, Point position) { Element = element; Position = position; }
public AcceptElementLocationEventArgs(IElement element, Point position, bool cancel) : base(cancel) { Element = element; Position = position; }
public IElement Element { get; private set; }
public Point Position { get; private set; }
}
public class Node : IElement
{
public string Title { get { return titleItem.Title; } set { titleItem.Title = value; } }
#region Collapsed
internal bool internalCollapsed;
public bool Collapsed
{
get
{
return (internalCollapsed &&
((state & RenderState.DraggedOver) == 0)) ||
nodeItems.Count == 0;
}
set
{
var oldValue = Collapsed;
internalCollapsed = value;
if (Collapsed != oldValue)
titleItem.ForceResize();
}
}
#endregion
public bool HasNoItems { get { return nodeItems.Count == 0; } }
public PointF Location { get; set; }
public object Tag { get; set; }
public IEnumerable<NodeConnection> Connections { get { return connections; } }
public IEnumerable<NodeItem> Items { get { return nodeItems; } }
internal RectangleF bounds;
internal RectangleF inputBounds;
internal RectangleF outputBounds;
internal RectangleF itemsBounds;
internal RenderState state = RenderState.None;
internal RenderState inputState = RenderState.None;
internal RenderState outputState = RenderState.None;
internal readonly List<NodeConnector> inputConnectors = new List<NodeConnector>();
internal readonly List<NodeConnector> outputConnectors = new List<NodeConnector>();
internal readonly List<NodeConnection> connections = new List<NodeConnection>();
internal readonly NodeTitleItem titleItem = new NodeTitleItem();
readonly List<NodeItem> nodeItems = new List<NodeItem>();
public Node(string title)
{
this.Title = title;
titleItem.Node = this;
}
public void AddItem(NodeItem item)
{
if (nodeItems.Contains(item))
return;
if (item.Node != null)
item.Node.RemoveItem(item);
nodeItems.Add(item);
item.Node = this;
}
public void RemoveItem(NodeItem item)
{
if (!nodeItems.Contains(item))
return;
item.Node = null;
nodeItems.Remove(item);
}
// Returns true if there are some connections that aren't connected
public bool AnyConnectorsDisconnected
{
get
{
foreach (var item in nodeItems)
{
if (item.Input.Enabled && !item.Input.HasConnection)
return true;
if (item.Output.Enabled && !item.Output.HasConnection)
return true;
}
return false;
}
}
// Returns true if there are some output connections that aren't connected
public bool AnyOutputConnectorsDisconnected
{
get
{
foreach (var item in nodeItems)
if (item.Output.Enabled && !item.Output.HasConnection)
return true;
return false;
}
}
// Returns true if there are some input connections that aren't connected
public bool AnyInputConnectorsDisconnected
{
get
{
foreach (var item in nodeItems)
if (item.Input.Enabled && !item.Input.HasConnection)
return true;
return false;
}
}
public ElementType ElementType { get { return ElementType.Node; } }
}
}
| 30.393064 | 145 | 0.711868 | [
"MIT"
] | Eresea/QuestCreator | Graph/Node.cs | 5,260 | 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("QSimPlanner")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("QSimPlanner")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("182ca73b-6911-4d37-ba34-c86232fe37f1")]
// 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("0.4.8.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 37.638889 | 84 | 0.741697 | [
"MIT"
] | JetStream96/QSimPlanner | src/QSP/Properties/AssemblyInfo.cs | 1,358 | C# |
using System;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Runtime.CompilerServices;
// 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.Route53RecoveryReadiness")]
#if BCL35
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS Route53 Recovery Readiness. Amazon Route 53 Application Recovery Controller's readiness check capability continually monitors resource quotas, capacity, and network routing policies to ensure that the recovery environment is scaled and configured to take over when needed.")]
#elif BCL45
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (4.5) - AWS Route53 Recovery Readiness. Amazon Route 53 Application Recovery Controller's readiness check capability continually monitors resource quotas, capacity, and network routing policies to ensure that the recovery environment is scaled and configured to take over when needed.")]
#elif NETSTANDARD20
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (NetStandard 2.0) - AWS Route53 Recovery Readiness. Amazon Route 53 Application Recovery Controller's readiness check capability continually monitors resource quotas, capacity, and network routing policies to ensure that the recovery environment is scaled and configured to take over when needed.")]
#elif NETCOREAPP3_1
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (.NET Core 3.1) - AWS Route53 Recovery Readiness. Amazon Route 53 Application Recovery Controller's readiness check capability continually monitors resource quotas, capacity, and network routing policies to ensure that the recovery environment is scaled and configured to take over when needed.")]
#else
#error Unknown platform constant - unable to set correct AssemblyDescription
#endif
[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.7.0.79")]
[assembly: System.CLSCompliant(true)]
#if BCL
[assembly: System.Security.AllowPartiallyTrustedCallers]
#endif | 59.705882 | 368 | 0.789163 | [
"Apache-2.0"
] | andyhopp/aws-sdk-net | sdk/src/Services/Route53RecoveryReadiness/Properties/AssemblyInfo.cs | 3,045 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class lose : MonoBehaviour {
private Rigidbody m_Rigidbody;
private Transform m_Transform;
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
//if()
//lose the game)
m_Transform.Rotate (Vector3.up, -90);
}
}
| 19.25 | 41 | 0.672727 | [
"MIT"
] | zhaoyiran924/Crazy_Football | congtre/lose.cs | 387 | 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.IoTJobsDataPlane")]
[assembly: AssemblyDescription("The Amazon Web Services SDK for .NET (3.5) - AWS IoT Jobs Data Plane. This release adds support for new the service called Iot Jobs. This client is built for the device SDK to use Iot Jobs Device specific APIs.")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyProduct("Amazon Web Services SDK for .NET")]
[assembly: AssemblyCompany("Amazon.com, Inc")]
[assembly: AssemblyCopyright("Copyright 2009-2019 Amazon.com, Inc. or its affiliates. All Rights Reserved.")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("3.3")]
[assembly: AssemblyFileVersion("3.3.100.113")] | 47.75 | 245 | 0.750654 | [
"Apache-2.0"
] | gbent/aws-sdk-net | sdk/code-analysis/ServiceAnalysis/IoTJobsDataPlane/Properties/AssemblyInfo.cs | 1,528 | 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("12.Cnt_occurancies_larger_nrs_array")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("12.Cnt_occurancies_larger_nrs_array")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("ba108487-628f-43a9-af5d-2ab5c5f83333")]
// 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.864865 | 84 | 0.75452 | [
"MIT"
] | stanislaviv/Programming-Fundamentals-May-2017 | 06_Arrays/06. Arrays/12.Cnt_occurancies_larger_nrs_array/Properties/AssemblyInfo.cs | 1,441 | C# |
using System.Linq;
using System.Threading.Tasks;
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Query;
using Microsoft.EntityFrameworkCore.TestModels.Northwind;
using Microsoft.EntityFrameworkCore.TestUtilities;
using Pomelo.EntityFrameworkCore.MySql.Infrastructure;
using Pomelo.EntityFrameworkCore.MySql.Storage;
using Pomelo.EntityFrameworkCore.MySql.Tests.TestUtilities.Attributes;
using Xunit;
using Xunit.Abstractions;
namespace Pomelo.EntityFrameworkCore.MySql.FunctionalTests.Query
{
public class NorthwindIncludeQueryMySqlTest : NorthwindIncludeQueryRelationalTestBase<
NorthwindQueryMySqlFixture<NoopModelCustomizer>>
{
// ReSharper disable once UnusedParameter.Local
public NorthwindIncludeQueryMySqlTest(
NorthwindQueryMySqlFixture<NoopModelCustomizer> fixture,
ITestOutputHelper testOutputHelper)
: base(fixture)
{
ClearLog();
//Fixture.TestSqlLoggerFactory.SetTestOutputHelper(testOutputHelper);
}
protected override bool CanExecuteQueryString
=> true;
[ConditionalTheory]
public override Task Include_duplicate_collection(bool async)
{
return base.Include_duplicate_collection(async);
}
[SupportedServerVersionCondition(nameof(ServerVersionSupport.WindowFunctions))]
public override Task Include_in_let_followed_by_FirstOrDefault(bool async)
{
return base.Include_in_let_followed_by_FirstOrDefault(async);
}
[SupportedServerVersionCondition(nameof(ServerVersionSupport.CrossApply))]
public override Task Include_collection_with_cross_apply_with_filter(bool async)
{
return base.Include_collection_with_cross_apply_with_filter(async);
}
[SupportedServerVersionCondition(nameof(ServerVersionSupport.OuterApply))]
public override Task Include_collection_with_outer_apply_with_filter(bool async)
{
return base.Include_collection_with_outer_apply_with_filter(async);
}
[SupportedServerVersionCondition(nameof(ServerVersionSupport.OuterApply))]
public override Task Include_collection_with_outer_apply_with_filter_non_equality(bool async)
{
return base.Include_collection_with_outer_apply_with_filter_non_equality(async);
}
[SupportedServerVersionCondition(nameof(ServerVersionSupport.OuterApply))]
public override Task Filtered_include_with_multiple_ordering(bool async)
{
return base.Filtered_include_with_multiple_ordering(async);
}
public override Task Include_collection_with_multiple_conditional_order_by(bool async)
{
// The order of `Orders` can be different, becaues it is not explicitly sorted.
// This is the case on MariaDB.
return AssertQuery(
async,
ss => ss.Set<Order>()
.Include(c => c.OrderDetails)
.OrderBy(o => o.OrderID > 0)
.ThenBy(o => o.Customer != null ? o.Customer.City : string.Empty)
.ThenBy(o => o.OrderID)
.Take(5),
elementAsserter: (e, a) => AssertInclude(e, a, new ExpectedInclude<Order>(o => o.OrderDetails)),
entryCount: 14);
}
public override Task Include_duplicate_collection_result_operator(bool async)
{
// The order of `Orders` can be different, becaues it is not explicitly sorted.
// This is the case on MariaDB.
return AssertQuery(
async,
ss => (from c1 in ss.Set<Customer>().Include(c => c.Orders).OrderBy(c => c.CustomerID).ThenBy(c => c.Orders.FirstOrDefault() != null ? c.Orders.FirstOrDefault().CustomerID : null).Take(2)
from c2 in ss.Set<Customer>().Include(c => c.Orders).OrderBy(c => c.CustomerID).ThenBy(c => c.Orders.FirstOrDefault() != null ? c.Orders.FirstOrDefault().CustomerID : null).Skip(2).Take(2)
select new { c1, c2 }).OrderBy(t => t.c1.CustomerID).ThenBy(t => t.c2.CustomerID).Take(1),
elementSorter: e => (e.c1.CustomerID, e.c2.CustomerID),
elementAsserter: (e, a) =>
{
AssertInclude(e.c1, a.c1, new ExpectedInclude<Customer>(c => c.Orders));
AssertInclude(e.c2, a.c2, new ExpectedInclude<Customer>(c => c.Orders));
},
entryCount: 15);
}
public override Task Include_duplicate_collection_result_operator2(bool async)
{
// The order of `Orders` can be different, becaues it is not explicitly sorted.
// This is the case on MariaDB.
return AssertQuery(
async,
ss => (from c1 in ss.Set<Customer>().Include(c => c.Orders).OrderBy(c => c.CustomerID).ThenBy(c => c.Orders.FirstOrDefault() != null ? c.Orders.FirstOrDefault().CustomerID : null).Take(2)
from c2 in ss.Set<Customer>().OrderBy(c => c.CustomerID).Skip(2).Take(2)
select new { c1, c2 }).OrderBy(t => t.c1.CustomerID).ThenBy(t => t.c2.CustomerID).Take(1),
elementSorter: e => (e.c1.CustomerID, e.c2.CustomerID),
elementAsserter: (e, a) =>
{
AssertInclude(e.c1, a.c1, new ExpectedInclude<Customer>(c => c.Orders));
AssertEqual(e.c2, a.c2);
},
entryCount: 8);
}
private void AssertSql(params string[] expected)
=> Fixture.TestSqlLoggerFactory.AssertBaseline(expected);
protected override void ClearLog()
=> Fixture.TestSqlLoggerFactory.Clear();
}
}
| 46.634921 | 208 | 0.638359 | [
"MIT"
] | Artrilogic/Pomelo.EntityFrameworkCore.MySql | test/EFCore.MySql.FunctionalTests/Query/NorthwindIncludeQueryMySqlTest.cs | 5,876 | C# |
using System.Text.RegularExpressions;
using SmartFormat;
using WDE.Common.Database;
namespace WDE.Conditions.Exporter
{
public static class ConditionsSerializer
{
private static readonly Regex ConditionLineRegex = new(
@"\(\s*(-?\d+),\s*(-?\d+),\s*(-?\d+),\s*(-?\d+),\s*(-?\d+),\s*(-?\d+),\s*(-?\d+),\s*(-?\d+),\s*(-?\d+),\s*(-?\d+),\s*(-?\d+),\s*"".*?""\s*\)");
private static readonly string ConditionSql =
@"({sourceType}, {sourceGroup}, {sourceEntry}, {sourceId}, {elseGroup}, {conditionType}, {conditionTarget}, {conditionValue1}, {conditionValue2}, {conditionValue3}, {negativeCondition}, ""{comment}"")";
public static string ToSqlString(this IConditionLine line)
{
object l = new
{
sourceType = line.SourceType,
sourceGroup = line.SourceGroup,
sourceEntry = line.SourceEntry,
sourceId = line.SourceId,
elseGroup = line.ElseGroup,
conditionType = line.ConditionType,
conditionTarget = line.ConditionTarget,
conditionValue1 = line.ConditionValue1,
conditionValue2 = line.ConditionValue2,
conditionValue3 = line.ConditionValue3,
negativeCondition = line.NegativeCondition,
comment = line.Comment,
};
return Smart.Format(ConditionSql, l);
}
public static bool TryToConditionLine(this string str, out IConditionLine line)
{
line = new AbstractConditionLine();
Match m = ConditionLineRegex.Match(str);
if (!m.Success)
return false;
line.SourceType = int.Parse(m.Groups[1].ToString());
line.SourceGroup = int.Parse(m.Groups[2].ToString());
line.SourceEntry = int.Parse(m.Groups[3].ToString());
line.SourceId = int.Parse(m.Groups[4].ToString());
line.ElseGroup = int.Parse(m.Groups[5].ToString());
line.ConditionType = int.Parse(m.Groups[6].ToString());
line.ConditionTarget = byte.Parse(m.Groups[7].ToString());
line.ConditionValue1 = int.Parse(m.Groups[8].ToString());
line.ConditionValue2 = int.Parse(m.Groups[9].ToString());
line.ConditionValue3 = int.Parse(m.Groups[10].ToString());
line.NegativeCondition = int.Parse(m.Groups[11].ToString());
line.Comment = m.Groups[11].ToString();
return true;
}
}
} | 43.066667 | 214 | 0.565789 | [
"Unlicense"
] | Crypticaz/WoWDatabaseEditor | WDE.Conditions/Exporter/ConditionsSerializer.cs | 2,586 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.Logging;
namespace StoreApi
{
public class Program
{
public static void Main(string[] args)
{
BuildWebHost(args).Run();
}
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.Build();
}
}
| 23 | 61 | 0.660535 | [
"MIT"
] | cob3x85/NetCoreDev | WebApiStore/StoreApi/Program.cs | 600 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using AutoMapper;
using Sombra.Core;
using Sombra.Core.Enums;
using Sombra.Infrastructure.DAL;
using Sombra.Messaging.Infrastructure;
using Sombra.Messaging.Requests.Search;
using Sombra.Messaging.Responses.Search;
using Sombra.Messaging.Shared;
using Sombra.SearchService.DAL;
namespace Sombra.SearchService
{
public class GetRandomCharitiesRequestHandler : IAsyncRequestHandler<GetRandomCharitiesRequest, GetRandomCharitiesResponse>
{
private readonly SearchContext _context;
private readonly IMapper _mapper;
public GetRandomCharitiesRequestHandler(SearchContext context, IMapper mapper)
{
_context = context;
_mapper = mapper;
}
public async Task<GetRandomCharitiesResponse> Handle(GetRandomCharitiesRequest message)
{
return new GetRandomCharitiesResponse
{
Results = await _context.Content.Where(c => c.Type == SearchContentType.Charity)
.OrderBy(c => Guid.NewGuid()).Take(message.Amount)
.ProjectToListAsync<SearchResult>(_mapper)
};
}
}
} | 32.567568 | 127 | 0.697095 | [
"MIT"
] | markslingerland/Sombra | Sombra.SearchService/GetRandomCharitiesRequestHandler.cs | 1,207 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Core.Utilities.Results
{
public class SuccessResult:Result
{
public SuccessResult(string message) : base(true,message)
{
}
public SuccessResult() : base(true)
{
}
}
}
| 15.45 | 65 | 0.608414 | [
"MIT"
] | sdnrcvk/FinalProject | Core/Utilities/Results/SuccessResult.cs | 311 | C# |
namespace Be.Vlaanderen.Basisregisters.Api.Exceptions
{
using System;
using System.Collections.Generic;
using System.Linq;
using System.Runtime.Serialization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Versioning;
using Microsoft.Extensions.DependencyInjection;
using Newtonsoft.Json;
using StatusCodeProblemDetails = BasicApiProblem.StatusCodeProblemDetails;
// https://github.com/Microsoft/aspnet-api-versioning/wiki/Error-Responses
/// <summary>
/// Represents the ProblemDetails implementation for creating HTTP error responses related to API versioning.
/// </summary>
public class ProblemDetailsResponseProvider : IErrorResponseProvider
{
/// <summary>
/// Creates and returns a new error response given the provided context.
/// </summary>
/// <param name="context">The <see cref="ErrorResponseContext">error context</see> used to generate the response.</param>
/// <returns>The generated <see cref="IActionResult">response</see>.</returns>
public virtual IActionResult CreateResponse(ErrorResponseContext context)
=> new ObjectResult(CreateErrorContent(context)) { StatusCode = context.StatusCode };
/// <summary>
/// Creates the default error content using the given context.
/// </summary>
/// <param name="context">The <see cref="ErrorResponseContext">error context</see> used to create the error content.</param>
/// <returns>An <see cref="object"/> representing the error content.</returns>
protected virtual object CreateErrorContent(ErrorResponseContext context)
=> new ApiVersionProblemDetails(context);
}
public class ApiVersionProblemDetails : StatusCodeProblemDetails
{
private readonly Dictionary<string, string> _errorCodeTitles = new Dictionary<string, string>
{
{"ApiVersionUnspecified", "API version unspecified."},
{"UnsupportedApiVersion", "Unsupported API version."},
{"InvalidApiVersion", "Invalid API version."},
{"AmbiguousApiVersion", "An API version was specified multiple times with different values."},
}.ToDictionary(x => x.Key.ToLowerInvariant(), x => x.Value);
private const string DefaultErrorCodeTitle = "There was a problem determining the API version.";
/// <summary>Validatie fouten.</summary>
[JsonProperty("apiVersionError", DefaultValueHandling = DefaultValueHandling.Ignore)]
[DataMember(Name = "apiVersionError", Order = 600, EmitDefaultValue = false)]
public object InnerError { get; set; }
public ApiVersionProblemDetails(ErrorResponseContext context) : base(context.StatusCode)
{
var errorCode = context.ErrorCode.ToLowerInvariant();
ProblemTypeUri = $"urn:apiversion:{errorCode}";
Detail = NullIfEmpty(context.Message);
InnerError = NewInnerError(context, c => new { Message = c.MessageDetail });
Title = _errorCodeTitles.ContainsKey(errorCode)
? _errorCodeTitles[errorCode]
: DefaultErrorCodeTitle;
var httpContext = context.Request.HttpContext;
ProblemInstanceUri = httpContext
.RequestServices
.GetRequiredService<ProblemDetailsHelper>()
.GetInstanceUri(httpContext);
}
private static string NullIfEmpty(string value) => string.IsNullOrEmpty(value) ? null : value;
private static TError NewInnerError<TError>(ErrorResponseContext context, Func<ErrorResponseContext, TError> create)
{
if (string.IsNullOrEmpty(context.MessageDetail))
return default;
var environment = (IHostingEnvironment)context.Request.HttpContext.RequestServices.GetService(typeof(IHostingEnvironment));
return environment?.IsDevelopment() == true
? create(context)
: default;
}
}
}
| 45.977528 | 135 | 0.674242 | [
"MIT"
] | CumpsD/api | src/Be.Vlaanderen.Basisregisters.Api/Exceptions/ProblemDetailsResponseProvider.cs | 4,092 | C# |
namespace CarRentalSystem.Dealers.Data.Configurations
{
using Microsoft.EntityFrameworkCore;
using Microsoft.EntityFrameworkCore.Metadata.Builders;
using Models;
using static DataConstants.Dealers;
using static CarRentalSystem.Data.DataConstants.Common;
internal class DealerConfiguration : IEntityTypeConfiguration<Dealer>
{
public void Configure(EntityTypeBuilder<Dealer> builder)
{
builder
.HasKey(d => d.Id);
builder
.Property(d => d.Name)
.IsRequired()
.HasMaxLength(MaxNameLength);
builder
.Property(d => d.PhoneNumber)
.IsRequired()
.HasMaxLength(MaxPhoneNumberLength);
builder
.Property(d => d.UserId)
.IsRequired();
builder
.HasMany(d => d.CarAds)
.WithOne(c => c.Dealer)
.HasForeignKey(c => c.DealerId)
.IsRequired()
.OnDelete(DeleteBehavior.Restrict);
}
}
}
| 27.9 | 73 | 0.545699 | [
"MIT"
] | Digid-GMAO/MyTested.AspNet.TV | src/Eventual Consistency Done Right/CarRentalSystem.Dealers/Data/Configurations/DealerConfiguration.cs | 1,118 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace Command.Receiver
{
public sealed class CodeGroup : Group
{
public override void ExcuteOpeation()
{
Console.WriteLine("This is Code Group.");
}
public override void Rollback()
{
Console.WriteLine("This is Code Group.");
}
}
}
| 19.45 | 53 | 0.59126 | [
"Apache-2.0"
] | HadesKing/DesignPatterns | src/Behavioral Patterns/Command/Receiver/CodeGroup.cs | 391 | C# |
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information.
using System;
using System.IO;
using System.Linq;
using Microsoft.CodeAnalysis.CSharp.Symbols;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Microsoft.CodeAnalysis.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public partial class QueryTests : CompilingTestBase
{
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void DegenerateQueryExpression()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from i in c select i;
if (ReferenceEquals(c, r)) throw new Exception();
// List1<int> r = c.Select(i => i);
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1, 2, 3, 4, 5, 6, 7]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void FromClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c select i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from i in c select i')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i')
ReturnedValue:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void QueryContinuation()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from i in c select i into q select q;
if (ReferenceEquals(c, r)) throw new Exception();
// List1<int> r = c.Select(i => i);
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1, 2, 3, 4, 5, 6, 7]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void QueryContinuation_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c select i into q select q/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from i in c ... q select q')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select q')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'select i')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i')
ReturnedValue:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'q')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'q')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'q')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'q')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'q')
ReturnedValue:
IParameterReferenceOperation: q (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'q')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void Select()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from i in c select i+1;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[2, 3, 4, 5, 6, 7, 8]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void SelectClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c select i+1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from i in c select i+1')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i+1')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i+1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i+1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i+1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i+1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i+1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i+1')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void GroupBy01()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
var r = from i in c group i by i % 2;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[1, 3, 5, 7], 0:[2, 4, 6]]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void GroupByClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c group i by i % 2/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Linq.IGrouping<System.Int32, System.Int32>>) (Syntax: 'from i in c ... i by i % 2')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Linq.IGrouping<System.Int32, System.Int32>> System.Linq.Enumerable.GroupBy<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> keySelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Linq.IGrouping<System.Int32, System.Int32>>, IsImplicit) (Syntax: 'group i by i % 2')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i % 2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i % 2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i % 2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i % 2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i % 2')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Remainder) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i % 2')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 2) (Syntax: '2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void GroupBy02()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(1, 2, 3, 4, 5, 6, 7);
var r = from i in c group 10+i by i % 2;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[11, 13, 15, 17], 0:[12, 14, 16]]");
}
[Fact]
public void Cast()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<object> c = new List1<object>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from int i in c select i;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1, 2, 3, 4, 5, 6, 7]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void CastInFromClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<object> c = new List<object>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from int i in c select i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int i in c select i')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select i')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int i in c')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int i in c')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Object>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i')
ReturnedValue:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void Where()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<object> c = new List1<object>(1, 2, 3, 4, 5, 6, 7);
List1<int> r = from int i in c where i < 5 select i;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1, 2, 3, 4]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void WhereClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<object> c = new List<object>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from int i in c where i < 5 select i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int i ... 5 select i')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Where<System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Boolean> predicate)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'where i < 5')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int i in c')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int i in c')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Object>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i < 5')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Boolean>, IsImplicit) (Syntax: 'i < 5')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i < 5')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i < 5')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i < 5')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'i < 5')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 5) (Syntax: '5')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void FromJoinSelect()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3, 4, 5, 7);
List1<int> c2 = new List1<int>(10, 30, 40, 50, 60, 70);
List1<int> r = from x1 in c1
join x2 in c2 on x1 equals x2/10
select x1+x2;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[11, 33, 44, 55, 77]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void FromJoinSelect_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c1 = new List<int>() {1, 2, 3, 4, 5, 6, 7};
List<int> c2 = new List<int>() {10, 30, 40, 50, 60, 70};
var r = /*<bind>*/from x1 in c1
join x2 in c2 on x1 equals x2/10
select x1+x2/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from x1 in ... elect x1+x2')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Join<System.Int32, System.Int32, System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> outer, System.Collections.Generic.IEnumerable<System.Int32> inner, System.Func<System.Int32, System.Int32> outerKeySelector, System.Func<System.Int32, System.Int32> innerKeySelector, System.Func<System.Int32, System.Int32, System.Int32> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'join x2 in ... quals x2/10')
Instance Receiver:
null
Arguments(5):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outer) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x1 in c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from x1 in c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'x1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x1')
ReturnedValue:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x2/10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'x2/10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x2/10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x2/10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x2/10')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x2/10')
Left:
IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x1+x2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, System.Int32>, IsImplicit) (Syntax: 'x1+x2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x1+x2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x1+x2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x1+x2')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x1+x2')
Left:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x1')
Right:
IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void OrderBy()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(28, 51, 27, 84, 27, 27, 72, 64, 55, 46, 39);
var r =
from i in c
orderby i/10 descending, i%10
select i;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[84, 72, 64, 51, 55, 46, 39, 27, 27, 27, 28]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void OrderByClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c = new List<int>() {1, 2, 3, 4, 5, 6, 7};
var r = /*<bind>*/from i in c
orderby i/10 descending, i%10
select i/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Linq.IOrderedEnumerable<System.Int32>) (Syntax: 'from i in c ... select i')
Expression:
IInvocationOperation (System.Linq.IOrderedEnumerable<System.Int32> System.Linq.Enumerable.ThenBy<System.Int32, System.Int32>(this System.Linq.IOrderedEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> keySelector)) (OperationKind.Invocation, Type: System.Linq.IOrderedEnumerable<System.Int32>, IsImplicit) (Syntax: 'i%10')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i/10 descending')
IInvocationOperation (System.Linq.IOrderedEnumerable<System.Int32> System.Linq.Enumerable.OrderByDescending<System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Int32> keySelector)) (OperationKind.Invocation, Type: System.Linq.IOrderedEnumerable<System.Int32>, IsImplicit) (Syntax: 'i/10 descending')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from i in c')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from i in c')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i/10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i/10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i/10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i/10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i/10')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i/10')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: keySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'i%10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'i%10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i%10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i%10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i%10')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Remainder) (OperationKind.Binary, Type: System.Int32) (Syntax: 'i%10')
Left:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'i')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void GroupJoin()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3, 4, 5, 7);
List1<int> c2 = new List1<int>(12, 34, 42, 51, 52, 66, 75);
List1<string> r =
from x1 in c1
join x2 in c2 on x1 equals x2 / 10 into g
select x1 + "":"" + g.ToString();
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[12], 2:[], 3:[34], 4:[42], 5:[51, 52], 7:[75]]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void GroupJoinClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{12, 34, 42, 51, 52, 66, 75};
var r =
/*<bind>*/from x1 in c1
join x2 in c2 on x1 equals x2 / 10 into g
select x1 + "":"" + g.ToString()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.String>) (Syntax: 'from x1 in ... .ToString()')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.String> System.Linq.Enumerable.GroupJoin<System.Int32, System.Int32, System.Int32, System.String>(this System.Collections.Generic.IEnumerable<System.Int32> outer, System.Collections.Generic.IEnumerable<System.Int32> inner, System.Func<System.Int32, System.Int32> outerKeySelector, System.Func<System.Int32, System.Int32> innerKeySelector, System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>, System.String> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.String>, IsImplicit) (Syntax: 'join x2 in ... / 10 into g')
Instance Receiver:
null
Arguments(5):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outer) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x1 in c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from x1 in c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x1')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'x1')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x1')
ReturnedValue:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x2 / 10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'x2 / 10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x2 / 10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x2 / 10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x2 / 10')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x2 / 10')
Left:
IParameterReferenceOperation: x2 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x2')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>, System.String>, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x1 + "":"" + g.ToString()')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'x1 + "":"" + g.ToString()')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.String) (Syntax: 'x1 + "":""')
Left:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Object, IsImplicit) (Syntax: 'x1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Operand:
IParameterReferenceOperation: x1 (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x1')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.String, Constant: "":"") (Syntax: '"":""')
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'g.ToString()')
Instance Receiver:
IParameterReferenceOperation: g (OperationKind.ParameterReference, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'g')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void SelectMany01()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3);
List1<int> c2 = new List1<int>(10, 20, 30);
List1<int> r = from x in c1 from y in c2 select x + y;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[11, 21, 31, 12, 22, 32, 13, 23, 33]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void SelectMany_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
List<int> c2 = new List<int>{12, 34, 42, 51, 52, 66, 75};
var r = /*<bind>*/from x in c1 from y in c2 select x + y/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from x in c ... elect x + y')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.SelectMany<System.Int32, System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<System.Int32, System.Int32, System.Int32> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from y in c2')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from x in c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from x in c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c2')
ReturnedValue:
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + y')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, System.Int32>, IsImplicit) (Syntax: 'x + y')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'y')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void SelectMany02()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3);
List1<int> c2 = new List1<int>(10, 20, 30);
List1<int> r = from x in c1 from int y in c2 select x + y;
Console.WriteLine(r);
}
}";
CompileAndVerify(csSource, expectedOutput: "[11, 21, 31, 12, 22, 32, 13, 23, 33]");
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void Let01()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3);
List1<int> r1 =
from int x in c1
let g = x * 10
let z = g + x*100
select x + z;
System.Console.WriteLine(r1);
}
}";
CompileAndVerify(csSource, expectedOutput: "[111, 222, 333]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void LetClause_IOperation()
{
string source = @"
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
List<int> c1 = new List<int>{1, 2, 3, 4, 5, 7};
var r = /*<bind>*/from int x in c1
let g = x * 10
let z = g + x*100
select x + z/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int x ... elect x + z')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, System.Int32>(this System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>> source, System.Func<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select x + z')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let z = g + x*100')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>> System.Linq.Enumerable.Select<<anonymous type: System.Int32 x, System.Int32 g>, <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 g>> source, System.Func<<anonymous type: System.Int32 x, System.Int32 g>, <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>>, IsImplicit) (Syntax: 'let z = g + x*100')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let g = x * 10')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 g>> System.Linq.Enumerable.Select<System.Int32, <anonymous type: System.Int32 x, System.Int32 g>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, <anonymous type: System.Int32 x, System.Int32 g>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 g>>, IsImplicit) (Syntax: 'let g = x * 10')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int x in c1')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int x in c1')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x * 10')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, <anonymous type: System.Int32 x, System.Int32 g>>, IsImplicit) (Syntax: 'x * 10')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x * 10')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x * 10')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x * 10')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let g = x * 10')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let g = x * ... elect x + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'let g = x * 10')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let g = x * 10')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'let g = x * 10')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let g = x * 10')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.g { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x * 10')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let g = x * 10')
Right:
IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x * 10')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'g + x*100')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 g>, <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>>, IsImplicit) (Syntax: 'g + x*100')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'g + x*100')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'g + x*100')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'g + x*100')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let z = g + x*100')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let g = x * ... elect x + z')
Left:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 g> <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let z = g + x*100')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let z = g + x*100')
Right:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'let z = g + x*100')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let z = g + x*100')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'g + x*100')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let z = g + x*100')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'g + x*100')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.g { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'g')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'g')
Right:
IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x*100')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100) (Syntax: '100')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + z')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, System.Int32>, IsImplicit) (Syntax: 'x + z')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + z')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + z')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + z')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 g>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 g> <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 g>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 g> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void TransparentIdentifiers_FromLet()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
C c3 = new C(100, 200, 300);
C r1 =
from int x in c1
from int y in c2
from int z in c3
let g = x + y + z
where (x + y / 10 + z / 100) < 6
select g;
Console.WriteLine(r1);
}
}";
CompileAndVerify(csSource, expectedOutput: "[111, 211, 311, 121, 221, 131, 112, 212, 122, 113]");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void TransparentIdentifiers_FromLet_IOperation()
{
string source = @"
using C = System.Collections.Generic.List<int>;
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
C c1 = new C{1, 2, 3};
C c2 = new C{10, 20, 30};
C c3 = new C{100, 200, 300};
var r1 =
/*<bind>*/from int x in c1
from int y in c2
from int z in c3
let g = x + y + z
where (x + y / 10 + z / 100) < 6
select g/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int x ... select g')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Int32>(this System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> source, System.Func<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Int32> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'select g')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'where (x + ... / 100) < 6')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> System.Linq.Enumerable.Where<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>(this System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> source, System.Func<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Boolean> predicate)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>, IsImplicit) (Syntax: 'where (x + ... / 100) < 6')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'let g = x + y + z')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> System.Linq.Enumerable.Select<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>(this System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>> source, System.Func<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>> selector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>, IsImplicit) (Syntax: 'let g = x + y + z')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int z in c3')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>> System.Linq.Enumerable.SelectMany<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> source, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>>, IsImplicit) (Syntax: 'from int z in c3')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> System.Linq.Enumerable.SelectMany<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int x in c1')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int x in c1')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c2')
ReturnedValue:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'from int y in c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'from int y in c2')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c3')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c3')
ReturnedValue:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c3')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c3')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c3')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c3 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int z in c3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>>, IsImplicit) (Syntax: 'from int z in c3')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'from int z in c3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'from int z in c3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'from int z in c3')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'from int z in c3')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int z in c3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'from int z in c3')
Right:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int z in c3')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int z in c3')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'from int z in c3')
Right:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int z in c3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + y + z')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>>, IsImplicit) (Syntax: 'x + y + z')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + y + z')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + y + z')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y + z')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'let g = x + y + z')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'from int y ... select g')
Left:
IPropertyReferenceOperation: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.<>h__TransparentIdentifier1 { get; } (OperationKind.PropertyReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let g = x + y + z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'let g = x + y + z')
Right:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'let g = x + y + z')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'let g = x + y + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.g { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'x + y + z')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'let g = x + y + z')
Right:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y + z')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'y')
Right:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier1 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: predicate) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Boolean>, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '(x + y / 10 ... / 100) < 6')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.LessThan) (OperationKind.Binary, Type: System.Boolean) (Syntax: '(x + y / 10 ... / 100) < 6')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y / 10 + z / 100')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y / 10')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.<>h__TransparentIdentifier1 { get; } (OperationKind.PropertyReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier2 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'x')
Right:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'y / 10')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: System.Int32 x, System.Int32 y> <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.<>h__TransparentIdentifier0 { get; } (OperationKind.PropertyReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'y')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.<>h__TransparentIdentifier1 { get; } (OperationKind.PropertyReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier2 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'y')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 10) (Syntax: '10')
Right:
IBinaryOperation (BinaryOperatorKind.Divide) (OperationKind.Binary, Type: System.Int32) (Syntax: 'z / 100')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>.z { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'z')
Instance Receiver:
IPropertyReferenceOperation: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.<>h__TransparentIdentifier1 { get; } (OperationKind.PropertyReference, Type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z>, IsImplicit) (Syntax: 'z')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier2 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'z')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 100) (Syntax: '100')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 6) (Syntax: '6')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: selector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'g')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, System.Int32>, IsImplicit) (Syntax: 'g')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'g')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'g')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'g')
ReturnedValue:
IPropertyReferenceOperation: System.Int32 <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>.g { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'g')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier2 (OperationKind.ParameterReference, Type: <anonymous type: <anonymous type: <anonymous type: System.Int32 x, System.Int32 y> <>h__TransparentIdentifier0, System.Int32 z> <>h__TransparentIdentifier1, System.Int32 g>, IsImplicit) (Syntax: 'g')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void TransparentIdentifiers_Join01()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
C r1 =
from int x in c1
join y in c2 on x equals y/10
let z = x+y
select z;
Console.WriteLine(r1);
}
}";
CompileAndVerify(csSource, expectedOutput: "[11, 22, 33]");
}
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void TransparentIdentifiers_Join02()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3, 4, 5, 7);
List1<int> c2 = new List1<int>(12, 34, 42, 51, 52, 66, 75);
List1<string> r1 = from x1 in c1
join x2 in c2 on x1 equals x2 / 10 into g
where x1 < 7
select x1 + "":"" + g.ToString();
Console.WriteLine(r1);
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[12], 2:[], 3:[34], 4:[42], 5:[51, 52]]");
}
[Fact]
public void CodegenBug()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c1 = new List1<int>(1, 2, 3, 4, 5, 7);
List1<int> c2 = new List1<int>(12, 34, 42, 51, 52, 66, 75);
List1<Tuple<int, List1<int>>> r1 =
c1
.GroupJoin(c2, x1 => x1, x2 => x2 / 10, (x1, g) => new Tuple<int, List1<int>>(x1, g))
;
Func1<Tuple<int, List1<int>>, bool> condition = (Tuple<int, List1<int>> TR1) => TR1.Item1 < 7;
List1<Tuple<int, List1<int>>> r2 =
r1
.Where(condition)
;
Func1<Tuple<int, List1<int>>, string> map = (Tuple<int, List1<int>> TR1) => TR1.Item1.ToString() + "":"" + TR1.Item2.ToString();
List1<string> r3 =
r2
.Select(map)
;
string r4 = r3.ToString();
Console.WriteLine(r4);
return;
}
}";
CompileAndVerify(csSource, expectedOutput: "[1:[12], 2:[], 3:[34], 4:[42], 5:[51, 52]]");
}
[Fact]
public void RangeVariables01()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
C c3 = new C(100, 200, 300);
C r1 =
from int x in c1
from int y in c2
from int z in c3
select x + y + z;
Console.WriteLine(r1);
}
}";
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
dynamic methodM = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = methodM.Body.Statements[3].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
var x = model.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
Assert.Equal("Cast", info0.CastInfo.Symbol.Name);
Assert.NotEqual(MethodKind.ReducedExtension, ((IMethodSymbol)info0.CastInfo.Symbol).MethodKind);
Assert.Null(info0.OperationInfo.Symbol);
var info1 = model.GetQueryClauseInfo(q.Body.Clauses[0]);
var y = model.GetDeclaredSymbol(q.Body.Clauses[0]);
Assert.Equal(SymbolKind.RangeVariable, y.Kind);
Assert.Equal("y", y.Name);
Assert.Equal("Cast", info1.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info1.OperationInfo.Symbol.Name);
Assert.NotEqual(MethodKind.ReducedExtension, ((IMethodSymbol)info1.OperationInfo.Symbol).MethodKind);
var info2 = model.GetQueryClauseInfo(q.Body.Clauses[1]);
var z = model.GetDeclaredSymbol(q.Body.Clauses[1]);
Assert.Equal(SymbolKind.RangeVariable, z.Kind);
Assert.Equal("z", z.Name);
Assert.Equal("Cast", info2.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info2.OperationInfo.Symbol.Name);
var info3 = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
Assert.NotNull(info3);
// what about info3's contents ???
var xPyPz = (q.Body.SelectOrGroup as SelectClauseSyntax).Expression as BinaryExpressionSyntax;
var xPy = xPyPz.Left as BinaryExpressionSyntax;
Assert.Equal(x, model.GetSemanticInfoSummary(xPy.Left).Symbol);
Assert.Equal(y, model.GetSemanticInfoSummary(xPy.Right).Symbol);
Assert.Equal(z, model.GetSemanticInfoSummary(xPyPz.Right).Symbol);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void RangeVariables_IOperation()
{
string source = @"
using C = System.Collections.Generic.List<int>;
using System.Collections.Generic;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
C c1 = new C{1, 2, 3};
C c2 = new C{10, 20, 30};
C c3 = new C{100, 200, 300};
var r1 =
/*<bind>*/from int x in c1
from int y in c2
from int z in c3
select x + y + z/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from int x ... t x + y + z')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.SelectMany<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> source, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, System.Int32> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int z in c3')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IInvocationOperation (System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>> System.Linq.Enumerable.SelectMany<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>(this System.Collections.Generic.IEnumerable<System.Int32> source, System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>> collectionSelector, System.Func<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<<anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
null
Arguments(3):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int x in c1')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int x in c1')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c1')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c1')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c1 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c2')
ReturnedValue:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c2')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c2')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c2')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c2 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, <anonymous type: System.Int32 x, System.Int32 y>>, IsImplicit) (Syntax: 'from int y in c2')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'from int y in c2')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'from int y in c2')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... t x + y + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsImplicit) (Syntax: 'from int y ... t x + y + z')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'from int y in c2')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from int y in c2')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: collectionSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c3')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Collections.Generic.IEnumerable<System.Int32>>, IsImplicit) (Syntax: 'c3')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'c3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'c3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'c3')
ReturnedValue:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'c3')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'c3')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'c3')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
ILocalReferenceOperation: c3 (OperationKind.LocalReference, Type: System.Collections.Generic.List<System.Int32>) (Syntax: 'c3')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x + y + z')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, System.Int32 y>, System.Int32, System.Int32>, IsImplicit) (Syntax: 'x + y + z')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + y + z')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + y + z')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + y + z')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y + z')
Left:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: System.Int32) (Syntax: 'x + y')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'x')
Right:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, System.Int32 y>.y { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, System.Int32 y>, IsImplicit) (Syntax: 'y')
Right:
IParameterReferenceOperation: z (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'z')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
public void RangeVariables02()
{
var csSource = @"
using System;
using System.Linq;
class Query
{
public static void Main(string[] args)
{
var c1 = new int[] {1, 2, 3};
var c2 = new int[] {10, 20, 30};
var c3 = new int[] {100, 200, 300};
var r1 =
from int x in c1
from int y in c2
from int z in c3
select x + y + z;
Console.WriteLine(r1);
}
}";
var compilation = CreateCompilation(csSource);
foreach (var dd in compilation.GetDiagnostics()) Console.WriteLine(dd);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
dynamic methodM = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = methodM.Body.Statements[3].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
var x = model.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
Assert.Equal("Cast", info0.CastInfo.Symbol.Name);
Assert.Equal(MethodKind.ReducedExtension, ((IMethodSymbol)info0.CastInfo.Symbol).MethodKind);
Assert.Null(info0.OperationInfo.Symbol);
var info1 = model.GetQueryClauseInfo(q.Body.Clauses[0]);
var y = model.GetDeclaredSymbol(q.Body.Clauses[0]);
Assert.Equal(SymbolKind.RangeVariable, y.Kind);
Assert.Equal("y", y.Name);
Assert.Equal("Cast", info1.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info1.OperationInfo.Symbol.Name);
Assert.Equal(MethodKind.ReducedExtension, ((IMethodSymbol)info1.OperationInfo.Symbol).MethodKind);
var info2 = model.GetQueryClauseInfo(q.Body.Clauses[1]);
var z = model.GetDeclaredSymbol(q.Body.Clauses[1]);
Assert.Equal(SymbolKind.RangeVariable, z.Kind);
Assert.Equal("z", z.Name);
Assert.Equal("Cast", info2.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info2.OperationInfo.Symbol.Name);
var info3 = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
Assert.NotNull(info3);
// what about info3's contents ???
var xPyPz = (q.Body.SelectOrGroup as SelectClauseSyntax).Expression as BinaryExpressionSyntax;
var xPy = xPyPz.Left as BinaryExpressionSyntax;
Assert.Equal(x, model.GetSemanticInfoSummary(xPy.Left).Symbol);
Assert.Equal(y, model.GetSemanticInfoSummary(xPy.Right).Symbol);
Assert.Equal(z, model.GetSemanticInfoSummary(xPyPz.Right).Symbol);
}
[Fact]
public void TestGetSemanticInfo01()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
C r1 =
from int x in c1
from int y in c2
select x + y;
Console.WriteLine(r1);
}
}";
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
dynamic methodM = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = methodM.Body.Statements[2].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
Assert.Equal("Cast", info0.CastInfo.Symbol.Name);
Assert.Null(info0.OperationInfo.Symbol);
Assert.Equal("x", model.GetDeclaredSymbol(q.FromClause).Name);
var info1 = model.GetQueryClauseInfo(q.Body.Clauses[0]);
Assert.Equal("Cast", info1.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info1.OperationInfo.Symbol.Name);
Assert.Equal("y", model.GetDeclaredSymbol(q.Body.Clauses[0]).Name);
var info2 = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
// what about info2's contents?
}
[Fact]
public void TestGetSemanticInfo02()
{
var csSource = LINQ + @"
class Query
{
public static void Main(string[] args)
{
List1<int> c = new List1<int>(28, 51, 27, 84, 27, 27, 72, 64, 55, 46, 39);
var r =
from i in c
orderby i/10 descending, i%10
select i;
Console.WriteLine(r);
}
}";
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
dynamic methodM = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = methodM.Body.Statements[1].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
Assert.Null(info0.CastInfo.Symbol);
Assert.Null(info0.OperationInfo.Symbol);
Assert.Equal("i", model.GetDeclaredSymbol(q.FromClause).Name);
var i = model.GetDeclaredSymbol(q.FromClause);
var info1 = model.GetQueryClauseInfo(q.Body.Clauses[0]);
Assert.Null(info1.CastInfo.Symbol);
Assert.Null(info1.OperationInfo.Symbol);
Assert.Null(model.GetDeclaredSymbol(q.Body.Clauses[0]));
var order = q.Body.Clauses[0] as OrderByClauseSyntax;
var oinfo0 = model.GetSemanticInfoSummary(order.Orderings[0]);
Assert.Equal("OrderByDescending", oinfo0.Symbol.Name);
var oinfo1 = model.GetSemanticInfoSummary(order.Orderings[1]);
Assert.Equal("ThenBy", oinfo1.Symbol.Name);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(541774, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541774")]
[Fact]
public void MultipleFromClauseIdentifierInExprNotInContext()
{
string source = @"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q2 = /*<bind>*/from n1 in nums
from n2 in nums
select n1/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from n1 in ... select n1')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'from n2 in nums')
Children(3):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'nums')
Children(0)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'nums')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'nums')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'nums')
ReturnedValue:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'nums')
Children(0)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'n1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'n1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'n1')
ReturnedValue:
IParameterReferenceOperation: n1 (OperationKind.ParameterReference, Type: ?) (Syntax: 'n1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0103: The name 'nums' does not exist in the current context
// var q2 = /*<bind>*/from n1 in nums
Diagnostic(ErrorCode.ERR_NameNotInContext, "nums").WithArguments("nums").WithLocation(8, 39),
// CS0103: The name 'nums' does not exist in the current context
// from n2 in nums
Diagnostic(ErrorCode.ERR_NameNotInContext, "nums").WithArguments("nums").WithLocation(9, 29)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(541906, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541906")]
[Fact]
public void NullLiteralFollowingJoinInQuery()
{
string source = @"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var query = /*<bind>*/from int i in new int[] { 1 } join null on true equals true select i/*</bind>*/; //CS1031
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from int i ... ue select i')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'join null o ... equals true')
Children(5):
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Cast<System.Int32>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'from int i ... int[] { 1 }')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'new int[] { 1 }')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsImplicit) (Syntax: 'new int[] { 1 }')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IArrayCreationOperation (OperationKind.ArrayCreation, Type: System.Int32[]) (Syntax: 'new int[] { 1 }')
Dimension Sizes(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1, IsImplicit) (Syntax: 'new int[] { 1 }')
Initializer:
IArrayInitializerOperation (1 elements) (OperationKind.ArrayInitializer, Type: null) (Syntax: '{ 1 }')
Element Values(1):
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'join null o ... equals true')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'null')
Children(1):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null, IsInvalid) (Syntax: 'null')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'true')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'true')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'true')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'true')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'true')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'true')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Boolean, Constant: True) (Syntax: 'true')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'i')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'i')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'i')
ReturnedValue:
IParameterReferenceOperation: i (OperationKind.ParameterReference, Type: ?) (Syntax: 'i')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1031: Type expected
// var query = /*<bind>*/from int i in new int[] { 1 } join null on true equals true select i/*</bind>*/; //CS1031
Diagnostic(ErrorCode.ERR_TypeExpected, "null").WithLocation(8, 66),
// CS1001: Identifier expected
// var query = /*<bind>*/from int i in new int[] { 1 } join null on true equals true select i/*</bind>*/; //CS1031
Diagnostic(ErrorCode.ERR_IdentifierExpected, "null").WithLocation(8, 66),
// CS1003: Syntax error, 'in' expected
// var query = /*<bind>*/from int i in new int[] { 1 } join null on true equals true select i/*</bind>*/; //CS1031
Diagnostic(ErrorCode.ERR_SyntaxError, "null").WithArguments("in", "null").WithLocation(8, 66)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(541779, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541779")]
[Fact]
public void MultipleFromClauseQueryExpr()
{
var csSource = @"
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var nums = new int[] { 3, 4 };
var q2 = from int n1 in nums
from int n2 in nums
select n1;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}";
CompileAndVerify(csSource, expectedOutput: "3 3 4 4");
}
[WorkItem(541782, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541782")]
[Fact]
public void FromSelectQueryExprOnArraysWithTypeImplicit()
{
var csSource = @"
using System;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var nums = new int[] { 3, 4 };
var q2 = from n1 in nums select n1;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}";
CompileAndVerify(csSource, expectedOutput: "3 4");
}
[WorkItem(541788, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541788")]
[Fact]
public void JoinClauseTest()
{
var csSource = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var q2 =
from a in Enumerable.Range(1, 13)
join b in Enumerable.Range(1, 13) on 4 * a equals b
select a;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}";
CompileAndVerify(csSource, expectedOutput: "1 2 3");
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(17838, "https://github.com/dotnet/roslyn/issues/17838")]
public void JoinClause_IOperation()
{
string source = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var q2 =
/*<bind>*/from a in Enumerable.Range(1, 13)
join b in Enumerable.Range(1, 13) on 4 * a equals b
select a/*</bind>*/;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'from a in E ... select a')
Expression:
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Join<System.Int32, System.Int32, System.Int32, System.Int32>(this System.Collections.Generic.IEnumerable<System.Int32> outer, System.Collections.Generic.IEnumerable<System.Int32> inner, System.Func<System.Int32, System.Int32> outerKeySelector, System.Func<System.Int32, System.Int32> innerKeySelector, System.Func<System.Int32, System.Int32, System.Int32> resultSelector)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>, IsImplicit) (Syntax: 'join b in E ... a equals b')
Instance Receiver:
null
Arguments(5):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outer) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Enumerable.Range(1, 13)')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Range(System.Int32 start, System.Int32 count)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'Enumerable.Range(1, 13)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: start) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: count) (OperationKind.Argument, Type: null) (Syntax: '13')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 13) (Syntax: '13')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: inner) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'Enumerable.Range(1, 13)')
IInvocationOperation (System.Collections.Generic.IEnumerable<System.Int32> System.Linq.Enumerable.Range(System.Int32 start, System.Int32 count)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.Int32>) (Syntax: 'Enumerable.Range(1, 13)')
Instance Receiver:
null
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: start) (OperationKind.Argument, Type: null) (Syntax: '1')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: count) (OperationKind.Argument, Type: null) (Syntax: '13')
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 13) (Syntax: '13')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: outerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: '4 * a')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: '4 * a')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '4 * a')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '4 * a')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '4 * a')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Multiply) (OperationKind.Binary, Type: System.Int32) (Syntax: '4 * a')
Left:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 4) (Syntax: '4')
Right:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: innerKeySelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'b')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32>, IsImplicit) (Syntax: 'b')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'b')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'b')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'b')
ReturnedValue:
IParameterReferenceOperation: b (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'b')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: resultSelector) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'a')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, System.Int32, System.Int32>, IsImplicit) (Syntax: 'a')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'a')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'a')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'a')
ReturnedValue:
IParameterReferenceOperation: a (OperationKind.ParameterReference, Type: System.Int32) (Syntax: 'a')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
";
var expectedDiagnostics = DiagnosticDescription.None;
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(541789, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541789")]
[WorkItem(9229, "DevDiv_Projects/Roslyn")]
[Fact]
public void WhereClauseTest()
{
var csSource = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
where (x > 2)
select x;
string serializer = String.Empty;
foreach (var q in q2)
{
serializer = serializer + q + "" "";
}
System.Console.Write(serializer.Trim());
}
}";
CompileAndVerify(csSource, expectedOutput: "3 4");
}
[WorkItem(541942, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541942")]
[Fact]
public void WhereDefinedInType()
{
var csSource = @"
using System;
class Y
{
public int Where(Func<int, bool> predicate)
{
return 45;
}
}
class P
{
static void Main()
{
var src = new Y();
var query = from x in src
where x > 0
select x;
Console.Write(query);
}
}";
CompileAndVerify(csSource, expectedOutput: "45");
}
[Fact]
public void GetInfoForSelectExpression01()
{
string sourceCode = @"
using System;
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select x;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
SelectClauseSyntax selectClause = (SelectClauseSyntax)tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf("select", StringComparison.Ordinal)).Parent;
var info = semanticModel.GetSemanticInfoSummary(selectClause.Expression);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
Assert.Equal(SymbolKind.RangeVariable, info.Symbol.Kind);
var info2 = semanticModel.GetSemanticInfoSummary(selectClause);
var m = (MethodSymbol)info2.Symbol;
Assert.Equal("Select", m.ReducedFrom.Name);
}
[Fact]
public void GetInfoForSelectExpression02()
{
string sourceCode = @"
using System;
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select x into w
select w;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
SelectClauseSyntax selectClause = (SelectClauseSyntax)tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf("select w", StringComparison.Ordinal)).Parent;
var info = semanticModel.GetSemanticInfoSummary(selectClause.Expression);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
Assert.Equal(SymbolKind.RangeVariable, info.Symbol.Kind);
}
[Fact]
public void GetInfoForSelectExpression03()
{
string sourceCode = @"
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select x+1 into w
select w+1;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
compilation.VerifyDiagnostics();
var semanticModel = compilation.GetSemanticModel(tree);
var e = (IdentifierNameSyntax)tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf("x+1", StringComparison.Ordinal)).Parent;
var info = semanticModel.GetSemanticInfoSummary(e);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
Assert.Equal(SymbolKind.RangeVariable, info.Symbol.Kind);
Assert.Equal("x", info.Symbol.Name);
e = (IdentifierNameSyntax)tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf("w+1", StringComparison.Ordinal)).Parent;
info = semanticModel.GetSemanticInfoSummary(e);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
Assert.Equal(SymbolKind.RangeVariable, info.Symbol.Kind);
Assert.Equal("w", info.Symbol.Name);
var e2 = e.Parent as ExpressionSyntax; // w+1
var info2 = semanticModel.GetSemanticInfoSummary(e2);
Assert.Equal(SpecialType.System_Int32, info2.Type.SpecialType);
Assert.Equal("System.Int32 System.Int32.op_Addition(System.Int32 left, System.Int32 right)", info2.Symbol.ToTestDisplayString());
}
[WorkItem(541806, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541806")]
[Fact]
public void GetDeclaredSymbolForQueryContinuation()
{
string sourceCode = @"
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select x into w
select w;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var queryContinuation = tree.GetRoot().FindToken(sourceCode.IndexOf("into w", StringComparison.Ordinal)).Parent;
var symbol = semanticModel.GetDeclaredSymbol(queryContinuation);
Assert.NotNull(symbol);
Assert.Equal("w", symbol.Name);
Assert.Equal(SymbolKind.RangeVariable, symbol.Kind);
}
[WorkItem(541899, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541899")]
[Fact]
public void ComputeQueryVariableType()
{
string sourceCode = @"
using System.Linq;
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
var q2 = from x in nums
select 5;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var selectExpression = tree.GetCompilationUnitRoot().FindToken(sourceCode.IndexOf('5'));
var info = semanticModel.GetSpeculativeTypeInfo(selectExpression.SpanStart, SyntaxFactory.ParseExpression("x"), SpeculativeBindingOption.BindAsExpression);
Assert.Equal(SpecialType.System_Int32, info.Type.SpecialType);
}
[WorkItem(541893, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541893")]
[Fact]
public void GetDeclaredSymbolForJoinIntoClause()
{
string sourceCode = @"
using System;
using System.Linq;
static class Test
{
static void Main()
{
var qie = from x3 in new int[] { 0 }
join x7 in (new int[] { 0 }) on 5 equals 5 into x8
select x8;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var joinInto = tree.GetRoot().FindToken(sourceCode.IndexOf("into x8", StringComparison.Ordinal)).Parent;
var symbol = semanticModel.GetDeclaredSymbol(joinInto);
Assert.NotNull(symbol);
Assert.Equal("x8", symbol.Name);
Assert.Equal(SymbolKind.RangeVariable, symbol.Kind);
Assert.Equal("? x8", symbol.ToTestDisplayString());
}
[WorkItem(541982, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541982")]
[WorkItem(543494, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543494")]
[Fact()]
public void GetDeclaredSymbolAddAccessorDeclIncompleteQuery()
{
string sourceCode = @"
using System;
using System.Linq;
public class QueryExpressionTest
{
public static void Main()
{
var expr1 = new[] { 1, 2, 3, 4, 5 };
var query1 = from event in expr1 select event;
var query2 = from int
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var unknownAccessorDecls = tree.GetCompilationUnitRoot().DescendantNodes().OfType<AccessorDeclarationSyntax>();
var symbols = unknownAccessorDecls.Select(decl => semanticModel.GetDeclaredSymbol(decl));
Assert.True(symbols.All(s => ReferenceEquals(s, null)));
}
[WorkItem(542235, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542235")]
[Fact]
public void TwoFromClauseFollowedBySelectClause()
{
string sourceCode = @"
using System.Linq;
class Test
{
public static void Main()
{
var q2 = from num1 in new int[] { 4, 5 }
from num2 in new int[] { 4, 5 }
select num1;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var selectClause = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SelectClause)).Single() as SelectClauseSyntax;
var fromClause1 = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => (n.IsKind(SyntaxKind.FromClause)) && (n.ToString().Contains("num1"))).Single() as FromClauseSyntax;
var fromClause2 = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => (n.IsKind(SyntaxKind.FromClause)) && (n.ToString().Contains("num2"))).Single() as FromClauseSyntax;
var symbolInfoForSelect = semanticModel.GetSemanticInfoSummary(selectClause);
var queryInfoForFrom1 = semanticModel.GetQueryClauseInfo(fromClause1);
var queryInfoForFrom2 = semanticModel.GetQueryClauseInfo(fromClause2);
Assert.Null(queryInfoForFrom1.CastInfo.Symbol);
Assert.Null(queryInfoForFrom1.OperationInfo.Symbol);
Assert.Null(queryInfoForFrom2.CastInfo.Symbol);
Assert.Equal("SelectMany", queryInfoForFrom2.OperationInfo.Symbol.Name);
Assert.Null(symbolInfoForSelect.Symbol);
Assert.Empty(symbolInfoForSelect.CandidateSymbols);
Assert.Equal(CandidateReason.None, symbolInfoForSelect.CandidateReason);
}
[WorkItem(528747, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528747")]
[Fact]
public void SemanticInfoForOrderingClauses()
{
string sourceCode = @"
using System;
using System.Linq;
public class QueryExpressionTest
{
public static void Main()
{
var q1 =
from x in new int[] { 4, 5 }
orderby
x descending,
x.ToString() ascending,
x descending
select x;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
int count = 0;
string[] names = { "OrderByDescending", "ThenBy", "ThenByDescending" };
foreach (var ordering in tree.GetCompilationUnitRoot().DescendantNodes().OfType<OrderingSyntax>())
{
var symbolInfo = model.GetSemanticInfoSummary(ordering);
Assert.Equal(names[count++], symbolInfo.Symbol.Name);
}
Assert.Equal(3, count);
}
[WorkItem(542266, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542266")]
[Fact]
public void FromOrderBySelectQueryTranslation()
{
string sourceCode = @"
using System;
using System.Collections;
using System.Collections.Generic;
public interface IOrderedEnumerable<TElement> : IEnumerable<TElement>,
IEnumerable
{
}
public static class Extensions
{
public static IOrderedEnumerable<TSource> OrderBy<TSource, TKey>(
this IEnumerable<TSource> source,
Func<TSource, TKey> keySelector)
{
return null;
}
public static IEnumerable<TResult> Select<TSource, TResult>(
this IEnumerable<TSource> source,
Func<TSource, TResult> selector)
{
return null;
}
}
class Program
{
static void Main(string[] args)
{
var q1 = from num in new int[] { 4, 5 }
orderby num
select num;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var selectClause = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SelectClause)).Single() as SelectClauseSyntax;
var symbolInfoForSelect = semanticModel.GetSemanticInfoSummary(selectClause);
Assert.Null(symbolInfoForSelect.Symbol);
}
[WorkItem(528756, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528756")]
[Fact]
public void FromWhereSelectTranslation()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
public static class Extensions
{
public static IEnumerable<TSource> Where<TSource>(
this IEnumerable<TSource> source,
Func<TSource, bool> predicate)
{
return null;
}
}
class Program
{
static void Main(string[] args)
{
var q1 = from num in System.Linq.Enumerable.Range(4, 5).Where(n => n > 10)
select num;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
semanticModel.GetDiagnostics().Verify(
// (21,30): error CS1935: Could not find an implementation of the query pattern for source type 'System.Collections.Generic.IEnumerable<int>'. 'Select' not found. Are you missing a reference to 'System.Core.dll' or a using directive for 'System.Linq'?
// var q1 = from num in System.Linq.Enumerable.Range(4, 5).Where(n => n > 10)
Diagnostic(ErrorCode.ERR_QueryNoProviderStandard, "System.Linq.Enumerable.Range(4, 5).Where(n => n > 10)").WithArguments("System.Collections.Generic.IEnumerable<int>", "Select"));
}
[WorkItem(528760, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528760")]
[Fact]
public void FromJoinSelectTranslation()
{
string sourceCode = @"
using System.Linq;
class Program
{
static void Main(string[] args)
{
var q1 = from num in new int[] { 4, 5 }
join x1 in new int[] { 4, 5 } on num equals x1
select x1 + 5;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var selectClause = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.SelectClause)).Single() as SelectClauseSyntax;
var symbolInfoForSelect = semanticModel.GetSemanticInfoSummary(selectClause);
Assert.Null(symbolInfoForSelect.Symbol);
}
[WorkItem(528761, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528761")]
[WorkItem(544585, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544585")]
[Fact]
public void OrderingSyntaxWithOverloadResolutionFailure()
{
string sourceCode = @"
using System.Linq;
class Program
{
static void Main(string[] args)
{
int[] numbers = new int[] { 4, 5 };
var q1 = from num in numbers.Single()
orderby (x1) => x1.ToString()
select num;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (10,30): error CS1936: Could not find an implementation of the query pattern for source type 'int'. 'OrderBy' not found.
// var q1 = from num in numbers.Single()
Diagnostic(ErrorCode.ERR_QueryNoProvider, "numbers.Single()").WithArguments("int", "OrderBy")
);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var orderingClause = tree.GetCompilationUnitRoot().DescendantNodes().Where(n => n.IsKind(SyntaxKind.AscendingOrdering)).Single() as OrderingSyntax;
var symbolInfoForOrdering = semanticModel.GetSemanticInfoSummary(orderingClause);
Assert.Null(symbolInfoForOrdering.Symbol);
}
[WorkItem(542292, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542292")]
[Fact]
public void EmitIncompleteQueryWithSyntaxErrors()
{
string sourceCode = @"
using System.Linq;
class Program
{
static int Main()
{
int [] goo = new int [] {1};
var q = from x in goo
select x + 1 into z
select z.T
";
using (var output = new MemoryStream())
{
Assert.False(CreateCompilationWithMscorlib40AndSystemCore(sourceCode).Emit(output).Success);
}
}
[WorkItem(542294, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542294")]
[Fact]
public void EmitQueryWithBindErrors()
{
string sourceCode = @"
using System.Linq;
class Program
{
static void Main()
{
int[] nums = { 0, 1, 2, 3, 4, 5 };
var query = from num in nums
let num = 3 // CS1930
select num;
}
}";
using (var output = new MemoryStream())
{
Assert.False(CreateCompilationWithMscorlib40AndSystemCore(sourceCode).Emit(output).Success);
}
}
[WorkItem(542372, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542372")]
[Fact]
public void BindToIncompleteSelectManyDecl()
{
string sourceCode = @"
class P
{
static C<X> M2<X>(X x)
{
return new C<X>(x);
}
static void Main()
{
C<int> e1 = new C<int>(1);
var q = from x1 in M2<int>(x1)
from x2 in e1
select x1;
}
}
class C<T>
{
public C<V> SelectMany";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var diags = semanticModel.GetDiagnostics();
Assert.NotEmpty(diags);
}
[WorkItem(542419, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542419")]
[Fact]
public void BindIdentifierInWhereErrorTolerance()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
using System.Linq;
class Program
{
static void Main(string[] args)
{
var r = args.Where(b => b < > );
var q = from a in args
where a <>
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var diags = semanticModel.GetDiagnostics();
Assert.NotEmpty(diags);
}
[WorkItem(542460, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542460")]
[Fact]
public void QueryWithMultipleParseErrorsAndScriptParseOption()
{
string sourceCode = @"
using System;
using System.Linq;
public class QueryExpressionTest
{
public static void Main()
{
var expr1 = new int[] { 1, 2, 3, 4, 5 };
var query2 = from int namespace in expr1 select namespace;
var query25 = from i in expr1 let namespace = expr1 select i;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode, parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var queryExpr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<QueryExpressionSyntax>().Where(x => x.ToFullString() == "from i in expr1 let ").Single();
var symbolInfo = semanticModel.GetSemanticInfoSummary(queryExpr);
Assert.Null(symbolInfo.Symbol);
}
[WorkItem(542496, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542496")]
[Fact]
public void QueryExpressionInFieldInitReferencingAnotherFieldWithScriptParseOption()
{
string sourceCode = @"
using System.Linq;
using System.Collections;
class P
{
double one = 1;
public IEnumerable e =
from x in new int[] { 1, 2, 3 }
select x + one;
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode, parseOptions: TestOptions.Script);
var tree = compilation.SyntaxTrees[0];
var semanticModel = compilation.GetSemanticModel(tree);
var queryExpr = tree.GetCompilationUnitRoot().DescendantNodes().OfType<QueryExpressionSyntax>().Single();
var symbolInfo = semanticModel.GetSemanticInfoSummary(queryExpr);
Assert.Null(symbolInfo.Symbol);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(542559, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542559")]
[ConditionalFact(typeof(DesktopOnly))]
public void StaticTypeInFromClause()
{
string source = @"
using System;
using System.Linq;
class C
{
static void Main()
{
var q2 = string.Empty.Cast<GC>().Select(x => x);
var q1 = /*<bind>*/from GC x in string.Empty select x/*</bind>*/;
}
}
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0718: 'GC': static types cannot be used as type arguments
// var q2 = string.Empty.Cast<GC>().Select(x => x);
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "string.Empty.Cast<GC>").WithArguments("System.GC").WithLocation(9, 18),
// CS0718: 'GC': static types cannot be used as type arguments
// var q1 = /*<bind>*/from GC x in string.Empty select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "from GC x in string.Empty").WithArguments("System.GC").WithLocation(10, 28)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from GC x i ... ty select x')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select x')
Children(2):
IInvocationOperation (System.Collections.Generic.IEnumerable<System.GC> System.Linq.Enumerable.Cast<System.GC>(this System.Collections.IEnumerable source)) (OperationKind.Invocation, Type: System.Collections.Generic.IEnumerable<System.GC>, IsInvalid, IsImplicit) (Syntax: 'from GC x i ... tring.Empty')
Instance Receiver:
null
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: source) (OperationKind.Argument, Type: null, IsInvalid, IsImplicit) (Syntax: 'string.Empty')
IConversionOperation (TryCast: False, Unchecked) (OperationKind.Conversion, Type: System.Collections.IEnumerable, IsInvalid, IsImplicit) (Syntax: 'string.Empty')
Conversion: CommonConversion (Exists: True, IsIdentity: False, IsNumeric: False, IsReference: True, IsUserDefined: False) (MethodSymbol: null)
Operand:
IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty')
Instance Receiver:
null
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x')
ReturnedValue:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.GC) (Syntax: 'x')
", new DiagnosticDescription[] {
// CS0718: 'GC': static types cannot be used as type arguments
// var q2 = string.Empty.Cast<GC>().Select(x => x);
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "string.Empty.Cast<GC>").WithArguments("System.GC").WithLocation(9, 18),
// CS0718: 'GC': static types cannot be used as type arguments
// var q1 = /*<bind>*/from GC x in string.Empty select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_GenericArgIsStaticClass, "from GC x in string.Empty").WithArguments("System.GC").WithLocation(10, 28)
}, parseOptions: TestOptions.WithoutImprovedOverloadCandidates);
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from GC x i ... ty select x')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select x')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'from GC x i ... tring.Empty')
Children(1):
IFieldReferenceOperation: System.String System.String.Empty (Static) (OperationKind.FieldReference, Type: System.String, IsInvalid) (Syntax: 'string.Empty')
Instance Receiver:
null
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x')
ReturnedValue:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ?) (Syntax: 'x')
", new DiagnosticDescription[] {
// file.cs(9,18): error CS1929: 'string' does not contain a definition for 'Cast' and the best extension method overload 'Queryable.Cast<GC>(IQueryable)' requires a receiver of type 'IQueryable'
// var q2 = string.Empty.Cast<GC>().Select(x => x);
Diagnostic(ErrorCode.ERR_BadInstanceArgType, "string.Empty").WithArguments("string", "Cast", "System.Linq.Queryable.Cast<System.GC>(System.Linq.IQueryable)", "System.Linq.IQueryable").WithLocation(9, 18),
// file.cs(10,41): error CS1929: 'string' does not contain a definition for 'Cast' and the best extension method overload 'Queryable.Cast<GC>(IQueryable)' requires a receiver of type 'IQueryable'
// var q1 = /*<bind>*/from GC x in string.Empty select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadInstanceArgType, "string.Empty").WithArguments("string", "Cast", "System.Linq.Queryable.Cast<System.GC>(System.Linq.IQueryable)", "System.Linq.IQueryable").WithLocation(10, 41)
});
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(542560, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542560")]
[Fact]
public void MethodGroupInFromClause()
{
string source = @"
using System;
using System.Linq;
class Program
{
static void Main()
{
var q1 = /*<bind>*/from y in Main select y/*</bind>*/;
var q2 = Main.Select(y => y);
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from y in Main select y')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select y')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'from y in Main')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'Main')
Children(1):
IInstanceReferenceOperation (ReferenceKind: ContainingTypeInstance) (OperationKind.InstanceReference, Type: Program, IsInvalid, IsImplicit) (Syntax: 'Main')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y')
ReturnedValue:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: ?) (Syntax: 'y')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0119: 'Program.Main()' is a method, which is not valid in the given context
// var q1 = /*<bind>*/from y in Main select y/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("Program.Main()", "method").WithLocation(9, 38),
// CS0119: 'Program.Main()' is a method, which is not valid in the given context
// var q2 = Main.Select(y => y);
Diagnostic(ErrorCode.ERR_BadSKunknown, "Main").WithArguments("Program.Main()", "method").WithLocation(10, 18)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(542558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542558")]
[Fact]
public void SelectFromType01()
{
string sourceCode = @"using System;
using System.Collections.Generic;
class C
{
static void Main()
{
var q = from x in C select x;
}
static IEnumerable<T> Select<T>(Func<int, T> f) { return null; }
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "C").Single();
dynamic main = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = main.Body.Statements[0].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
var x = model.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
Assert.Equal(null, info0.CastInfo.Symbol);
Assert.Null(info0.OperationInfo.Symbol);
var infoSelect = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
Assert.Equal("Select", infoSelect.Symbol.Name);
}
[WorkItem(542558, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542558")]
[Fact]
public void SelectFromType02()
{
string sourceCode = @"using System;
using System.Collections.Generic;
class C
{
static void Main()
{
var q = from x in C select x;
}
static Func<Func<int, object>, IEnumerable<object>> Select = null;
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "C").Single();
dynamic main = (MethodDeclarationSyntax)classC.Members[0];
QueryExpressionSyntax q = main.Body.Statements[0].Declaration.Variables[0].Initializer.Value;
var info0 = model.GetQueryClauseInfo(q.FromClause);
var x = model.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
Assert.Equal(null, info0.CastInfo.Symbol);
Assert.Null(info0.OperationInfo.Symbol);
var infoSelect = model.GetSemanticInfoSummary(q.Body.SelectOrGroup);
Assert.Equal("Select", infoSelect.Symbol.Name);
}
[WorkItem(542624, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542624")]
[Fact]
public void QueryColorColor()
{
string sourceCode = @"
using System;
using System.Collections.Generic;
class Color
{
public static IEnumerable<T> Select<T>(Func<int, T> f) { return null; }
}
class Flavor
{
public IEnumerable<T> Select<T>(Func<int, T> f) { return null; }
}
class Program
{
Color Color;
static Flavor Flavor;
static void Main()
{
var q1 = from x in Color select x;
var q2 = from x in Flavor select x;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (17,11): warning CS0169: The field 'Program.Color' is never used
// Color Color;
Diagnostic(ErrorCode.WRN_UnreferencedField, "Color").WithArguments("Program.Color"),
// (18,19): warning CS0649: Field 'Program.Flavor' is never assigned to, and will always have its default value null
// static Flavor Flavor;
Diagnostic(ErrorCode.WRN_UnassignedInternalField, "Flavor").WithArguments("Program.Flavor", "null")
);
}
[WorkItem(542704, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542704")]
[Fact]
public void QueryOnSourceWithGroupByMethod()
{
string source = @"
delegate T Func<A, T>(A a);
class Y<U>
{
public U u;
public Y(U u)
{
this.u = u;
}
public string GroupBy(Func<U, string> keySelector)
{
return null;
}
}
class Test
{
static int Main()
{
Y<int> src = new Y<int>(2);
string q1 = src.GroupBy(x => x.GetType().Name); // ok
string q2 = from x in src group x by x.GetType().Name; // Roslyn CS1501
return 0;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics();
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void RangeTypeAlreadySpecified()
{
string source = @"
using System.Linq;
using System.Collections;
static class Test
{
public static void Main2()
{
var list = new CastableToArrayList();
var q = /*<bind>*/from int x in list
select x + 1/*</bind>*/;
}
}
class CastableToArrayList
{
public ArrayList Cast<T>() { return null; }
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from int x ... elect x + 1')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select x + 1')
Children(2):
IInvocationOperation ( System.Collections.ArrayList CastableToArrayList.Cast<System.Int32>()) (OperationKind.Invocation, Type: System.Collections.ArrayList, IsInvalid, IsImplicit) (Syntax: 'from int x in list')
Instance Receiver:
ILocalReferenceOperation: list (OperationKind.LocalReference, Type: CastableToArrayList, IsInvalid) (Syntax: 'list')
Arguments(0)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x + 1')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x + 1')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x + 1')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Add) (OperationKind.Binary, Type: ?) (Syntax: 'x + 1')
Left:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ?) (Syntax: 'x')
Right:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 1) (Syntax: '1')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1936: Could not find an implementation of the query pattern for source type 'ArrayList'. 'Select' not found.
// var q = /*<bind>*/from int x in list
Diagnostic(ErrorCode.ERR_QueryNoProvider, "list").WithArguments("System.Collections.ArrayList", "Select").WithLocation(10, 41)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(11414, "DevDiv_Projects/Roslyn")]
[Fact]
public void InvalidQueryWithAnonTypesAndKeywords()
{
string source = @"
public class QueryExpressionTest
{
public static void Main()
{
var query7 = from i in expr1 join const in expr2 on i equals const select new { i, const };
var query8 = from int i in expr1 select new { i, const };
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
Assert.NotEmpty(compilation.GetDiagnostics());
}
[WorkItem(543787, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543787")]
[ClrOnlyFact]
public void GetSymbolInfoOfSelectNodeWhenTypeOfRangeVariableIsErrorType()
{
string source = @"
using System.Linq;
class Test
{
static void V()
{
}
public static int Main()
{
var e1 = from i in V() select i;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees.First();
var index = source.IndexOf("select i", StringComparison.Ordinal);
var selectNode = tree.GetCompilationUnitRoot().FindToken(index).Parent as SelectClauseSyntax;
var model = compilation.GetSemanticModel(tree);
var symbolInfo = model.GetSymbolInfo(selectNode);
Assert.NotNull(symbolInfo);
Assert.Null(symbolInfo.Symbol); // there is no select method to call because the receiver is bad
var typeInfo = model.GetTypeInfo(selectNode);
Assert.Equal(SymbolKind.ErrorType, typeInfo.Type.Kind);
}
[WorkItem(543790, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543790")]
[Fact]
public void GetQueryClauseInfoForQueryWithSyntaxErrors()
{
string source = @"
using System.Linq;
class Test
{
public static void Main ()
{
var query8 = from int i in expr1 join int delegate in expr2 on i equals delegate select new { i, delegate };
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
var tree = compilation.SyntaxTrees.First();
var index = source.IndexOf("join int delegate in expr2 on i equals delegate", StringComparison.Ordinal);
var joinNode = tree.GetCompilationUnitRoot().FindToken(index).Parent as JoinClauseSyntax;
var model = compilation.GetSemanticModel(tree);
var queryInfo = model.GetQueryClauseInfo(joinNode);
Assert.NotNull(queryInfo);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(545797, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545797")]
[Fact]
public void QueryOnNull()
{
string source = @"
using System;
static class C
{
static void Main()
{
var q = /*<bind>*/from x in null select x/*</bind>*/;
}
static object Select(this object x, Func<int, int> y)
{
return null;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Object, IsInvalid) (Syntax: 'from x in null select x')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'select x')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'from x in null')
Children(1):
ILiteralOperation (OperationKind.Literal, Type: null, Constant: null) (Syntax: 'null')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
ReturnedValue:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ?, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0186: Use of null is not valid in this context
// var q = /*<bind>*/from x in null select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_NullNotValid, "select x").WithLocation(7, 42)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[WorkItem(545797, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545797")]
[Fact]
public void QueryOnLambda()
{
string source = @"
using System;
static class C
{
static void Main()
{
var q = /*<bind>*/from x in y => y select x/*</bind>*/;
}
static object Select(this object x, Func<int, int> y)
{
return null;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: System.Object, IsInvalid) (Syntax: 'from x in y ... y select x')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: System.Object, IsInvalid, IsImplicit) (Syntax: 'select x')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'from x in y => y')
Children(1):
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null) (Syntax: 'y => y')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'y')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'y')
ReturnedValue:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: ?) (Syntax: 'y')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'x')
ReturnedValue:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: ?, IsInvalid) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS1936: Could not find an implementation of the query pattern for source type 'anonymous method'. 'Select' not found.
// var q = /*<bind>*/from x in y => y select x/*</bind>*/;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "select x").WithArguments("anonymous method", "Select").WithLocation(7, 44)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[WorkItem(545444, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545444")]
[Fact]
public void RefOmittedOnComCall()
{
string source = @"using System;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
[ComImport]
[Guid(""A88A175D-2448-447A-B786-64682CBEF156"")]
public interface IRef1
{
int M(ref int x, int y);
}
public class Ref1Impl : IRef1
{
public int M(ref int x, int y) { return x + y; }
}
class Test
{
public static void Main()
{
IRef1 ref1 = new Ref1Impl();
Expression<Func<int, int, int>> F = (x, y) => ref1.M(x, y);
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (22,54): error CS2037: An expression tree lambda may not contain a COM call with ref omitted on arguments
// Expression<Func<int, int, int>> F = (x, y) => ref1.M(x, y);
Diagnostic(ErrorCode.ERR_ComRefCallInExpressionTree, "ref1.M(x, y)")
);
}
[Fact, WorkItem(5728, "https://github.com/dotnet/roslyn/issues/5728")]
public void RefOmittedOnComCallErr()
{
string source = @"
using System;
using System.Linq.Expressions;
using System.Runtime.InteropServices;
[ComImport]
[Guid(""A88A175D-2448-447A-B786-64682CBEF156"")]
public interface IRef1
{
long M(uint y, ref int x, int z);
long M(uint y, ref int x, int z, int q);
}
public class Ref1Impl : IRef1
{
public long M(uint y, ref int x, int z) { return x + y; }
public long M(uint y, ref int x, int z, int q) { return x + y; }
}
class Test1
{
static void Test(Expression<Action<IRef1>> e)
{
}
static void Test<U>(Expression<Func<IRef1, U>> e)
{
}
public static void Main()
{
Test(ref1 => ref1.M(1, ));
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (34,32): error CS1525: Invalid expression term ')'
// Test(ref1 => ref1.M(1, ));
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(34, 32)
);
}
[WorkItem(529350, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529350")]
[Fact]
public void BindLambdaBodyWhenError()
{
string source =
@"using System.Linq;
class A
{
static void Main()
{
}
static void M(System.Reflection.Assembly[] a)
{
var q2 = a.SelectMany(assem2 => assem2.UNDEFINED, (assem2, t) => t);
var q1 = from assem1 in a
from t in assem1.UNDEFINED
select t;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(source);
compilation.VerifyDiagnostics(
// (10,48): error CS1061: 'System.Reflection.Assembly' does not contain a definition for 'UNDEFINED' and no extension method 'UNDEFINED' accepting a first argument of type 'System.Reflection.Assembly' could be found (are you missing a using directive or an assembly reference?)
// var q2 = a.SelectMany(assem2 => assem2.UNDEFINED, (assem2, t) => t);
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "UNDEFINED").WithArguments("System.Reflection.Assembly", "UNDEFINED"),
// (13,35): error CS1061: 'System.Reflection.Assembly' does not contain a definition for 'UNDEFINED' and no extension method 'UNDEFINED' accepting a first argument of type 'System.Reflection.Assembly' could be found (are you missing a using directive or an assembly reference?)
// from t in assem1.UNDEFINED
Diagnostic(ErrorCode.ERR_NoSuchMemberOrExtension, "UNDEFINED").WithArguments("System.Reflection.Assembly", "UNDEFINED")
);
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var assem2 =
tree.GetCompilationUnitRoot().DescendantNodes(n => n.ToString().Contains("assem2"))
.Where(e => e.ToString() == "assem2")
.OfType<ExpressionSyntax>()
.Single();
var typeInfo2 = model.GetTypeInfo(assem2);
Assert.NotEqual(TypeKind.Error, typeInfo2.Type.TypeKind);
Assert.Equal("Assembly", typeInfo2.Type.Name);
var assem1 =
tree.GetCompilationUnitRoot().DescendantNodes(n => n.ToString().Contains("assem1"))
.Where(e => e.ToString() == "assem1")
.OfType<ExpressionSyntax>()
.Single();
var typeInfo1 = model.GetTypeInfo(assem1);
Assert.NotEqual(TypeKind.Error, typeInfo1.Type.TypeKind);
Assert.Equal("Assembly", typeInfo1.Type.Name);
}
[Fact]
public void TestSpeculativeSemanticModel_GetQueryClauseInfo()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
}
}";
var speculatedSource = @"
C r1 =
from int x in c1
from int y in c2
select x + y;
";
var queryStatement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.Statements[1].Span.End, queryStatement, out speculativeModel);
Assert.True(success);
var q = (QueryExpressionSyntax)queryStatement.Declaration.Variables[0].Initializer.Value;
var info0 = speculativeModel.GetQueryClauseInfo(q.FromClause);
Assert.Equal("Cast", info0.CastInfo.Symbol.Name);
Assert.Null(info0.OperationInfo.Symbol);
Assert.Equal("x", speculativeModel.GetDeclaredSymbol(q.FromClause).Name);
var info1 = speculativeModel.GetQueryClauseInfo(q.Body.Clauses[0]);
Assert.Equal("Cast", info1.CastInfo.Symbol.Name);
Assert.Equal("SelectMany", info1.OperationInfo.Symbol.Name);
Assert.Equal("y", speculativeModel.GetDeclaredSymbol(q.Body.Clauses[0]).Name);
}
[Fact]
public void TestSpeculativeSemanticModel_GetSemanticInfoForSelectClause()
{
var csSource = @"
using C = List1<int>;" + LINQ + @"
class Query
{
public static void Main(string[] args)
{
C c1 = new C(1, 2, 3);
C c2 = new C(10, 20, 30);
}
}";
var speculatedSource = @"
C r1 =
from int x in c1
select x;
";
var queryStatement = (LocalDeclarationStatementSyntax)SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilation(csSource);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Query").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.Statements[1].Span.End, queryStatement, out speculativeModel);
Assert.True(success);
var q = (QueryExpressionSyntax)queryStatement.Declaration.Variables[0].Initializer.Value;
var x = speculativeModel.GetDeclaredSymbol(q.FromClause);
Assert.Equal(SymbolKind.RangeVariable, x.Kind);
Assert.Equal("x", x.Name);
var selectExpression = (q.Body.SelectOrGroup as SelectClauseSyntax).Expression;
Assert.Equal(x, speculativeModel.GetSemanticInfoSummary(selectExpression).Symbol);
var selectClauseSymbolInfo = speculativeModel.GetSymbolInfo(q.Body.SelectOrGroup);
Assert.NotNull(selectClauseSymbolInfo.Symbol);
Assert.Equal("Select", selectClauseSymbolInfo.Symbol.Name);
var selectClauseTypeInfo = speculativeModel.GetTypeInfo(q.Body.SelectOrGroup);
Assert.NotNull(selectClauseTypeInfo.Type);
Assert.Equal("List1", selectClauseTypeInfo.Type.Name);
}
[Fact]
public void TestSpeculativeSemanticModel_GetDeclaredSymbolForJoinIntoClause()
{
string sourceCode = @"
public class Test
{
public static void Main()
{
}
}";
var speculatedSource = @"
var qie = from x3 in new int[] { 0 }
join x7 in (new int[] { 1 }) on 5 equals 5 into x8
select x8;
";
var queryStatement = SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Test").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.SpanStart, queryStatement, out speculativeModel);
var queryExpression = (QueryExpressionSyntax)((LocalDeclarationStatementSyntax)queryStatement).Declaration.Variables[0].Initializer.Value;
JoinIntoClauseSyntax joinInto = ((JoinClauseSyntax)queryExpression.Body.Clauses[0]).Into;
var symbol = speculativeModel.GetDeclaredSymbol(joinInto);
Assert.NotNull(symbol);
Assert.Equal("x8", symbol.Name);
Assert.Equal(SymbolKind.RangeVariable, symbol.Kind);
Assert.Equal("? x8", symbol.ToTestDisplayString());
}
[Fact]
public void TestSpeculativeSemanticModel_GetDeclaredSymbolForQueryContinuation()
{
string sourceCode = @"
public class Test2
{
public static void Main()
{
var nums = new int[] { 1, 2, 3, 4 };
}
}";
var speculatedSource = @"
var q2 = from x in nums
select x into w
select w;
";
var queryStatement = SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics();
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "Test2").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.Statements[0].Span.End, queryStatement, out speculativeModel);
Assert.True(success);
var queryExpression = (QueryExpressionSyntax)((LocalDeclarationStatementSyntax)queryStatement).Declaration.Variables[0].Initializer.Value;
var queryContinuation = queryExpression.Body.Continuation;
var symbol = speculativeModel.GetDeclaredSymbol(queryContinuation);
Assert.NotNull(symbol);
Assert.Equal("w", symbol.Name);
Assert.Equal(SymbolKind.RangeVariable, symbol.Kind);
}
[Fact]
public void TestSpeculativeSemanticModel_GetSymbolInfoForOrderingClauses()
{
string sourceCode = @"
using System.Linq; // Needed for speculative code.
public class QueryExpressionTest
{
public static void Main()
{
}
}";
var speculatedSource = @"
var q1 =
from x in new int[] { 4, 5 }
orderby
x descending,
x.ToString() ascending,
x descending
select x;
";
var queryStatement = SyntaxFactory.ParseStatement(speculatedSource);
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (2,1): info CS8019: Unnecessary using directive.
// using System.Linq; // Needed for speculative code.
Diagnostic(ErrorCode.HDN_UnusedUsingDirective, "using System.Linq;"));
var tree = compilation.SyntaxTrees[0];
var model = compilation.GetSemanticModel(tree);
var classC = tree.GetCompilationUnitRoot().ChildNodes().OfType<TypeDeclarationSyntax>().Where(t => t.Identifier.ValueText == "QueryExpressionTest").Single();
var methodM = (MethodDeclarationSyntax)classC.Members[0];
SemanticModel speculativeModel;
bool success = model.TryGetSpeculativeSemanticModel(methodM.Body.SpanStart, queryStatement, out speculativeModel);
Assert.True(success);
int count = 0;
string[] names = { "OrderByDescending", "ThenBy", "ThenByDescending" };
foreach (var ordering in queryStatement.DescendantNodes().OfType<OrderingSyntax>())
{
var symbolInfo = speculativeModel.GetSemanticInfoSummary(ordering);
Assert.Equal(names[count++], symbolInfo.Symbol.Name);
}
Assert.Equal(3, count);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact]
public void BrokenQueryPattern()
{
string source = @"
using System;
class Q<T>
{
public Q<V> SelectMany<U, V>(Func<T, U> f1, Func<T, U, V> f2) { return null; }
public Q<U> Select<U>(Func<T, U> f1) { return null; }
//public Q<T> Where(Func<T, bool> f1) { return null; }
public X Where(Func<T, bool> f1) { return null; }
}
class X
{
public X Select<U>(Func<int, U> f1) { return null; }
}
class Program
{
static void Main(string[] args)
{
Q<int> q = null;
var r =
/*<bind>*/from x in q
from y in q
where x.ToString() == y.ToString()
select x.ToString()/*</bind>*/;
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: X, IsInvalid) (Syntax: 'from x in q ... .ToString()')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: X, IsInvalid, IsImplicit) (Syntax: 'select x.ToString()')
Children(2):
IInvocationOperation ( X Q<<anonymous type: System.Int32 x, Q<System.Int32> y>>.Where(System.Func<<anonymous type: System.Int32 x, Q<System.Int32> y>, System.Boolean> f1)) (OperationKind.Invocation, Type: X, IsImplicit) (Syntax: 'where x.ToS ... .ToString()')
Instance Receiver:
IInvocationOperation ( Q<<anonymous type: System.Int32 x, Q<System.Int32> y>> Q<System.Int32>.SelectMany<Q<System.Int32>, <anonymous type: System.Int32 x, Q<System.Int32> y>>(System.Func<System.Int32, Q<System.Int32>> f1, System.Func<System.Int32, Q<System.Int32>, <anonymous type: System.Int32 x, Q<System.Int32> y>> f2)) (OperationKind.Invocation, Type: Q<<anonymous type: System.Int32 x, Q<System.Int32> y>>, IsImplicit) (Syntax: 'from y in q')
Instance Receiver:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: Q<System.Int32>) (Syntax: 'q')
Arguments(2):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f1) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'q')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, Q<System.Int32>>, IsImplicit) (Syntax: 'q')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'q')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'q')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'q')
ReturnedValue:
ILocalReferenceOperation: q (OperationKind.LocalReference, Type: Q<System.Int32>) (Syntax: 'q')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f2) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'from y in q')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<System.Int32, Q<System.Int32>, <anonymous type: System.Int32 x, Q<System.Int32> y>>, IsImplicit) (Syntax: 'from y in q')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'from y in q')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'from y in q')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'from y in q')
ReturnedValue:
IAnonymousObjectCreationOperation (OperationKind.AnonymousObjectCreation, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'from y in q')
Initializers(2):
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'from y in q ... .ToString()')
Left:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, Q<System.Int32> y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32, IsImplicit) (Syntax: 'from y in q')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'from y in q')
Right:
IParameterReferenceOperation: x (OperationKind.ParameterReference, Type: System.Int32, IsImplicit) (Syntax: 'from y in q')
ISimpleAssignmentOperation (OperationKind.SimpleAssignment, Type: Q<System.Int32>, IsInvalid, IsImplicit) (Syntax: 'from y in q ... .ToString()')
Left:
IPropertyReferenceOperation: Q<System.Int32> <anonymous type: System.Int32 x, Q<System.Int32> y>.y { get; } (OperationKind.PropertyReference, Type: Q<System.Int32>, IsImplicit) (Syntax: 'from y in q')
Instance Receiver:
IInstanceReferenceOperation (ReferenceKind: ImplicitReceiver) (OperationKind.InstanceReference, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'from y in q')
Right:
IParameterReferenceOperation: y (OperationKind.ParameterReference, Type: Q<System.Int32>, IsImplicit) (Syntax: 'from y in q')
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
Arguments(1):
IArgumentOperation (ArgumentKind.Explicit, Matching Parameter: f1) (OperationKind.Argument, Type: null, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
IDelegateCreationOperation (OperationKind.DelegateCreation, Type: System.Func<<anonymous type: System.Int32 x, Q<System.Int32> y>, System.Boolean>, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
Target:
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: 'x.ToString( ... .ToString()')
ReturnedValue:
IBinaryOperation (BinaryOperatorKind.Equals) (OperationKind.Binary, Type: System.Boolean) (Syntax: 'x.ToString( ... .ToString()')
Left:
IInvocationOperation (virtual System.String System.Int32.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'x.ToString()')
Instance Receiver:
IPropertyReferenceOperation: System.Int32 <anonymous type: System.Int32 x, Q<System.Int32> y>.x { get; } (OperationKind.PropertyReference, Type: System.Int32) (Syntax: 'x')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'x')
Arguments(0)
Right:
IInvocationOperation (virtual System.String System.Object.ToString()) (OperationKind.Invocation, Type: System.String) (Syntax: 'y.ToString()')
Instance Receiver:
IPropertyReferenceOperation: Q<System.Int32> <anonymous type: System.Int32 x, Q<System.Int32> y>.y { get; } (OperationKind.PropertyReference, Type: Q<System.Int32>) (Syntax: 'y')
Instance Receiver:
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: <anonymous type: System.Int32 x, Q<System.Int32> y>, IsImplicit) (Syntax: 'y')
Arguments(0)
InConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
OutConversion: CommonConversion (Exists: True, IsIdentity: True, IsNumeric: False, IsReference: False, IsUserDefined: False) (MethodSymbol: null)
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsInvalid, IsImplicit) (Syntax: 'x.ToString()')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsInvalid, IsImplicit) (Syntax: 'x.ToString()')
IReturnOperation (OperationKind.Return, Type: null, IsInvalid, IsImplicit) (Syntax: 'x.ToString()')
ReturnedValue:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid) (Syntax: 'x.ToString()')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'x.ToString')
Children(1):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'x')
Children(1):
IParameterReferenceOperation: <>h__TransparentIdentifier0 (OperationKind.ParameterReference, Type: System.Int32, IsInvalid, IsImplicit) (Syntax: 'x')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS8016: Transparent identifier member access failed for field 'x' of 'int'. Does the data being queried implement the query pattern?
// select x.ToString()/*</bind>*/;
Diagnostic(ErrorCode.ERR_UnsupportedTransparentIdentifierAccess, "x").WithArguments("x", "int").WithLocation(27, 20)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[Fact]
[WorkItem(204561, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=204561&_a=edit")]
public void Bug204561_01()
{
string sourceCode =
@"
class C
{
public static void Main()
{
var x01 = from a in Test select a + 1;
}
}
public class Test
{
}
public static class TestExtensions
{
public static Test Select<T>(this Test x, System.Func<int, T> selector)
{
return null;
}
}
";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (6,34): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Select' not found.
// var x01 = from a in Test select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "select a + 1").WithArguments("Test", "Select").WithLocation(6, 34)
);
}
[Fact]
[WorkItem(204561, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=204561&_a=edit")]
public void Bug204561_02()
{
string sourceCode =
@"
class C
{
public static void Main()
{
var y02 = from a in Test select a + 1;
var x02 = from a in Test where a > 0 select a + 1;
}
}
class Test
{
public static Test Select<T>(System.Func<int, T> selector)
{
return null;
}
}
static class TestExtensions
{
public static Test Where(this Test x, System.Func<int, bool> filter)
{
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (7,34): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Where' not found.
// var x02 = from a in Test where a > 0 select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "where a > 0").WithArguments("Test", "Where").WithLocation(7, 34),
// (7,46): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Select' not found.
// var x02 = from a in Test where a > 0 select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "select a + 1").WithArguments("Test", "Select").WithLocation(7, 46)
);
}
[Fact]
[WorkItem(204561, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=204561&_a=edit")]
public void Bug204561_03()
{
string sourceCode =
@"
class C
{
public static void Main()
{
var y03 = from a in Test select a + 1;
var x03 = from a in Test where a > 0 select a + 1;
}
}
class Test
{
}
static class TestExtensions
{
public static Test Select<T>(this Test x, System.Func<int, T> selector)
{
return null;
}
public static Test Where(this Test x, System.Func<int, bool> filter)
{
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode);
compilation.VerifyDiagnostics(
// (6,34): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Select' not found.
// var y03 = from a in Test select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "select a + 1").WithArguments("Test", "Select").WithLocation(6, 34),
// (7,34): error CS1936: Could not find an implementation of the query pattern for source type 'Test'. 'Where' not found.
// var x03 = from a in Test where a > 0 select a + 1;
Diagnostic(ErrorCode.ERR_QueryNoProvider, "where a > 0").WithArguments("Test", "Where").WithLocation(7, 34)
);
}
[Fact]
[WorkItem(204561, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=204561&_a=edit")]
public void Bug204561_04()
{
string sourceCode =
@"
class C
{
public static void Main()
{
var x04 = from a in Test select a + 1;
}
}
class Test
{
public static Test Select<T>(System.Func<int, T> selector)
{
System.Console.WriteLine(""Select"");
return null;
}
}";
var compilation = CreateCompilationWithMscorlib40AndSystemCore(sourceCode, options: TestOptions.DebugExe);
CompileAndVerify(compilation, expectedOutput: "Select");
}
[WorkItem(15910, "https://github.com/dotnet/roslyn/issues/15910")]
[Fact]
public void ExpressionVariablesInQueryClause_01()
{
var csSource = @"
using System.Linq;
class Program
{
public static void Main(string[] args)
{
var a = new[] { 1, 2, 3, 4 };
var za = from x in M(a, out var q1) select x; // ok
var zc = from x in a from y in M(a, out var z) select x; // error 1
var zd = from x in a from int y in M(a, out var z) select x; // error 2
var ze = from x in a from y in M(a, out var z) where true select x; // error 3
var zf = from x in a from int y in M(a, out var z) where true select x; // error 4
var zg = from x in a let y = M(a, out var z) select x; // error 5
var zh = from x in a where M(x, out var z) == 1 select x; // error 6
var zi = from x in a join y in M(a, out var q2) on x equals y select x; // ok
var zj = from x in a join y in a on M(x, out var z) equals y select x; // error 7
var zk = from x in a join y in a on x equals M(y, out var z) select x; // error 8
var zl = from x in a orderby M(x, out var z) select x; // error 9
var zm = from x in a orderby x, M(x, out var z) select x; // error 10
var zn = from x in a group M(x, out var z) by x; // error 11
var zo = from x in a group x by M(x, out var z); // error 12
}
public static T M<T>(T x, out T z) => z = x;
}";
CreateCompilationWithMscorlib40AndSystemCore(csSource, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (10,53): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zc = from x in a from y in M(a, out var z) select x; // error 1
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(10, 53),
// (11,57): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zd = from x in a from int y in M(a, out var z) select x; // error 2
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(11, 57),
// (12,53): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var ze = from x in a from y in M(a, out var z) where true select x; // error 3
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(12, 53),
// (13,57): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zf = from x in a from int y in M(a, out var z) where true select x; // error 4
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(13, 57),
// (14,51): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zg = from x in a let y = M(a, out var z) select x; // error 5
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(14, 51),
// (15,49): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zh = from x in a where M(x, out var z) == 1 select x; // error 6
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(15, 49),
// (17,58): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zj = from x in a join y in a on M(x, out var z) equals y select x; // error 7
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(17, 58),
// (18,67): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zk = from x in a join y in a on x equals M(y, out var z) select x; // error 8
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(18, 67),
// (19,51): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zl = from x in a orderby M(x, out var z) select x; // error 9
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(19, 51),
// (20,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zm = from x in a orderby x, M(x, out var z) select x; // error 10
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(20, 54),
// (21,49): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zn = from x in a group M(x, out var z) by x; // error 11
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(21, 49),
// (22,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zo = from x in a group x by M(x, out var z); // error 12
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(22, 54)
);
CreateCompilationWithMscorlib40AndSystemCore(csSource).VerifyDiagnostics();
}
[WorkItem(15910, "https://github.com/dotnet/roslyn/issues/15910")]
[Fact]
public void ExpressionVariablesInQueryClause_02()
{
var csSource = @"
using System.Linq;
class Program
{
public static void Main(string[] args)
{
var a = new[] { 1, 2, 3, 4 };
var za = from x in M(a, a is var q1) select x; // ok
var zc = from x in a from y in M(a, a is var z) select x; // error 1
var zd = from x in a from int y in M(a, a is var z) select x; // error 2
var ze = from x in a from y in M(a, a is var z) where true select x; // error 3
var zf = from x in a from int y in M(a, a is var z) where true select x; // error 4
var zg = from x in a let y = M(a, a is var z) select x; // error 5
var zh = from x in a where M(x, x is var z) == 1 select x; // error 6
var zi = from x in a join y in M(a, a is var q2) on x equals y select x; // ok
var zj = from x in a join y in a on M(x, x is var z) equals y select x; // error 7
var zk = from x in a join y in a on x equals M(y, y is var z) select x; // error 8
var zl = from x in a orderby M(x, x is var z) select x; // error 9
var zm = from x in a orderby x, M(x, x is var z) select x; // error 10
var zn = from x in a group M(x, x is var z) by x; // error 11
var zo = from x in a group x by M(x, x is var z); // error 12
}
public static T M<T>(T x, bool b) => x;
}";
CreateCompilationWithMscorlib40AndSystemCore(csSource, parseOptions: TestOptions.Regular7_2).VerifyDiagnostics(
// (10,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zc = from x in a from y in M(a, a is var z) select x; // error 1
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(10, 54),
// (11,58): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zd = from x in a from int y in M(a, a is var z) select x; // error 2
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(11, 58),
// (12,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var ze = from x in a from y in M(a, a is var z) where true select x; // error 3
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(12, 54),
// (13,58): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zf = from x in a from int y in M(a, a is var z) where true select x; // error 4
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(13, 58),
// (14,52): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zg = from x in a let y = M(a, a is var z) select x; // error 5
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(14, 52),
// (15,50): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zh = from x in a where M(x, x is var z) == 1 select x; // error 6
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(15, 50),
// (17,59): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zj = from x in a join y in a on M(x, x is var z) equals y select x; // error 7
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(17, 59),
// (18,68): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zk = from x in a join y in a on x equals M(y, y is var z) select x; // error 8
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(18, 68),
// (19,52): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zl = from x in a orderby M(x, x is var z) select x; // error 9
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(19, 52),
// (20,55): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zm = from x in a orderby x, M(x, x is var z) select x; // error 10
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(20, 55),
// (21,50): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zn = from x in a group M(x, x is var z) by x; // error 11
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(21, 50),
// (22,55): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zo = from x in a group x by M(x, x is var z); // error 12
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(22, 55)
);
CreateCompilationWithMscorlib40AndSystemCore(csSource).VerifyDiagnostics();
}
[WorkItem(15910, "https://github.com/dotnet/roslyn/issues/15910")]
[Fact]
public void ExpressionVariablesInQueryClause_03()
{
var csSource = @"
using System.Linq;
class Program
{
public static void Main(string[] args)
{
var a = new[] { (1, 2), (3, 4) };
var za = from x in M(a, (int qa, int wa) = a[0]) select x; // scoping ok
var zc = from x in a from y in M(a, (int z, int w) = x) select x; // error 1
var zd = from x in a from int y in M(a, (int z, int w) = x) select x; // error 2
var ze = from x in a from y in M(a, (int z, int w) = x) where true select x; // error 3
var zf = from x in a from int y in M(a, (int z, int w) = x) where true select x; // error 4
var zg = from x in a let y = M(x, (int z, int w) = x) select x; // error 5
var zh = from x in a where M(x, (int z, int w) = x).Item1 == 1 select x; // error 6
var zi = from x in a join y in M(a, (int qi, int wi) = a[0]) on x equals y select x; // scoping ok
var zj = from x in a join y in a on M(x, (int z, int w) = x) equals y select x; // error 7
var zk = from x in a join y in a on x equals M(y, (int z, int w) = y) select x; // error 8
var zl = from x in a orderby M(x, (int z, int w) = x) select x; // error 9
var zm = from x in a orderby x, M(x, (int z, int w) = x) select x; // error 10
var zn = from x in a group M(x, (int z, int w) = x) by x; // error 11
var zo = from x in a group x by M(x, (int z, int w) = x); // error 12
}
public static T M<T>(T x, (int, int) z) => x;
}
namespace System
{
public struct ValueTuple<T1, T2>
{
public T1 Item1;
public T2 Item2;
public ValueTuple(T1 item1, T2 item2)
{
this.Item1 = item1;
this.Item2 = item2;
}
}
}
";
CreateCompilationWithMscorlib40AndSystemCore(csSource, parseOptions: TestOptions.Regular7_2)
.GetDiagnostics()
.Where(d => d.Code != (int)ErrorCode.ERR_DeclarationExpressionNotPermitted)
.Verify(
// (10,50): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zc = from x in a from y in M(a, (int z, int w) = x) select x; // error 1
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(10, 50),
// (11,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zd = from x in a from int y in M(a, (int z, int w) = x) select x; // error 2
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(11, 54),
// (12,50): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var ze = from x in a from y in M(a, (int z, int w) = x) where true select x; // error 3
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(12, 50),
// (13,54): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zf = from x in a from int y in M(a, (int z, int w) = x) where true select x; // error 4
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(13, 54),
// (14,48): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zg = from x in a let y = M(x, (int z, int w) = x) select x; // error 5
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(14, 48),
// (15,46): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zh = from x in a where M(x, (int z, int w) = x).Item1 == 1 select x; // error 6
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(15, 46),
// (17,55): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zj = from x in a join y in a on M(x, (int z, int w) = x) equals y select x; // error 7
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(17, 55),
// (18,64): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zk = from x in a join y in a on x equals M(y, (int z, int w) = y) select x; // error 8
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(18, 64),
// (19,48): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zl = from x in a orderby M(x, (int z, int w) = x) select x; // error 9
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(19, 48),
// (20,51): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zm = from x in a orderby x, M(x, (int z, int w) = x) select x; // error 10
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(20, 51),
// (21,46): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zn = from x in a group M(x, (int z, int w) = x) by x; // error 11
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(21, 46),
// (22,51): error CS8320: Feature 'declaration of expression variables in member initializers and queries' is not available in C# 7.2. Please use language version 7.3 or greater.
// var zo = from x in a group x by M(x, (int z, int w) = x); // error 12
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_2, "z").WithArguments("declaration of expression variables in member initializers and queries", "7.3").WithLocation(22, 51)
);
CreateCompilationWithMscorlib40AndSystemCore(csSource)
.GetDiagnostics()
.Where(d => d.Code != (int)ErrorCode.ERR_DeclarationExpressionNotPermitted)
.Verify();
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(14689, "https://github.com/dotnet/roslyn/issues/14689")]
public void SelectFromNamespaceShouldGiveAnError()
{
string source = @"
using System.Linq;
using NSAlias = ParentNamespace.ConsoleApp;
namespace ParentNamespace
{
namespace ConsoleApp
{
class Program
{
static void Main()
{
var x = from c in ConsoleApp select 3;
var y = from c in ParentNamespace.ConsoleApp select 3;
var z = /*<bind>*/from c in NSAlias select 3/*</bind>*/;
}
}
}
}
";
string expectedOperationTree = @"
ITranslatedQueryOperation (OperationKind.TranslatedQuery, Type: ?, IsInvalid) (Syntax: 'from c in N ... as select 3')
Expression:
IInvalidOperation (OperationKind.Invalid, Type: ?, IsImplicit) (Syntax: 'select 3')
Children(2):
IInvalidOperation (OperationKind.Invalid, Type: ?, IsInvalid, IsImplicit) (Syntax: 'from c in NSAlias')
Children(1):
IOperation: (OperationKind.None, Type: null, IsInvalid) (Syntax: 'NSAlias')
IAnonymousFunctionOperation (Symbol: lambda expression) (OperationKind.AnonymousFunction, Type: null, IsImplicit) (Syntax: '3')
IBlockOperation (1 statements) (OperationKind.Block, Type: null, IsImplicit) (Syntax: '3')
IReturnOperation (OperationKind.Return, Type: null, IsImplicit) (Syntax: '3')
ReturnedValue:
ILiteralOperation (OperationKind.Literal, Type: System.Int32, Constant: 3) (Syntax: '3')
";
var expectedDiagnostics = new DiagnosticDescription[] {
// CS0119: 'ConsoleApp' is a namespace, which is not valid in the given context
// var x = from c in ConsoleApp select 3;
Diagnostic(ErrorCode.ERR_BadSKunknown, "ConsoleApp").WithArguments("ConsoleApp", "namespace").WithLocation(13, 35),
// CS0119: 'ParentNamespace.ConsoleApp' is a namespace, which is not valid in the given context
// var y = from c in ParentNamespace.ConsoleApp select 3;
Diagnostic(ErrorCode.ERR_BadSKunknown, "ParentNamespace.ConsoleApp").WithArguments("ParentNamespace.ConsoleApp", "namespace").WithLocation(14, 35),
// CS0119: 'NSAlias' is a namespace, which is not valid in the given context
// var z = /*<bind>*/from c in NSAlias select 3/*</bind>*/;
Diagnostic(ErrorCode.ERR_BadSKunknown, "NSAlias").WithArguments("NSAlias", "namespace").WithLocation(15, 45)
};
VerifyOperationTreeAndDiagnosticsForTest<QueryExpressionSyntax>(source, expectedOperationTree, expectedDiagnostics);
}
[CompilerTrait(CompilerFeature.IOperation)]
[Fact, WorkItem(12052, "https://github.com/dotnet/roslyn/issues/12052")]
public void LambdaParameterConflictsWithRangeVariable()
{
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);
}
[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.7812 | 1,332 | 0.631485 | [
"Apache-2.0"
] | Maxprofs/roslyn | src/Compilers/CSharp/Test/Semantic/Semantics/QueryTests.cs | 292,704 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Input;
namespace Telerik.UI.Xaml.Controls.Primitives
{
/// <summary>
/// Represents a strongly-typed class that provides basic infrastructure for <see cref="RadControl"/> commands.
/// </summary>
public abstract class CommandServiceBase<T> : ServiceBase<T> where T : RadControl
{
internal Dictionary<int, ICommand> defaultCommands;
internal CommandCollection<T> userCommands;
internal CommandServiceBase(T owner)
: base(owner)
{
this.defaultCommands = new Dictionary<int, ICommand>();
this.userCommands = new CommandCollection<T>(owner);
}
internal bool ExecuteCommandCore(int id, object parameter, bool searchUser)
{
if (this.Owner == null)
{
return false;
}
var command = this.GetCommandById(id, searchUser);
if (command != null && command.CanExecute(parameter))
{
command.Execute(parameter);
return true;
}
return false;
}
internal ICommand GetCommandById(int id, bool searchUser)
{
ICommand command;
if (searchUser)
{
command = this.FindUserCommandById(id);
if (command != null)
{
return command;
}
}
if (this.defaultCommands.TryGetValue(id, out command))
{
return command;
}
return null;
}
internal ICommand FindUserCommandById(int id)
{
foreach (var command in this.userCommands)
{
if (command.CommandId == id)
{
return command;
}
}
return null;
}
}
}
| 26.763158 | 115 | 0.52409 | [
"Apache-2.0"
] | ChristianGutman/UI-For-UWP | Controls/Primitives/Primitives.UWP/Common/Services/Commands/CommandServiceBase.cs | 2,036 | C# |
using System;
namespace Mes
{
class Program
{
static void Main(string[] args)
{
int mes = int.Parse(Console.ReadLine());
switch (mes) {
case 1:
Console.WriteLine("January");
break;
case 2:
Console.WriteLine("February");
break;
case 3:
Console.WriteLine("March");
break;
case 4:
Console.WriteLine("April");
break;
case 5:
Console.WriteLine("May");
break;
case 6:
Console.WriteLine("June");
break;
case 7:
Console.WriteLine("July");
break;
case 8:
Console.WriteLine("August");
break;
case 9:
Console.WriteLine("September");
break;
case 10:
Console.WriteLine("October");
break;
case 11:
Console.WriteLine("November");
break;
case 12:
Console.WriteLine("December");
break;
default:
Console.WriteLine("Digite um número válido de 1 a 12");
break;
}
Console.ReadLine();
}
}
}
| 24.982456 | 71 | 0.389747 | [
"MIT"
] | jardelMoraes/Desafios-Bootcamps-DIO-Jardel-Moraes | C#/GFT Start #4 .NET/Mes/Program.cs | 1,428 | C# |
// This file is part of Silk.NET.
//
// You may modify and distribute Silk.NET under the terms
// of the MIT license. See the LICENSE file for details.
using System;
using Silk.NET.Core.Attributes;
#pragma warning disable 1591
namespace Silk.NET.OpenGL
{
[NativeName("Name", "PointParameterNameARB")]
public enum PointParameterNameARB : int
{
[NativeName("Name", "GL_POINT_SIZE_MIN_EXT")]
PointSizeMinExt = 0x8126,
[NativeName("Name", "GL_POINT_SIZE_MAX_EXT")]
PointSizeMaxExt = 0x8127,
[NativeName("Name", "GL_POINT_FADE_THRESHOLD_SIZE")]
PointFadeThresholdSize = 0x8128,
[NativeName("Name", "GL_POINT_FADE_THRESHOLD_SIZE_EXT")]
PointFadeThresholdSizeExt = 0x8128,
}
}
| 27.962963 | 64 | 0.690066 | [
"MIT"
] | ThomasMiz/Silk.NET | src/OpenGL/Silk.NET.OpenGL/Enums/PointParameterNameARB.gen.cs | 755 | C# |
//------------------------------------------------------------------------------
// <auto-generated>
// This code was generated by a tool.
//
// Changes to this file may cause incorrect behavior and will be lost if
// the code is regenerated.
// </auto-generated>
//------------------------------------------------------------------------------
namespace HOSS {
public partial class Site1 {
/// <summary>
/// head control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder head;
/// <summary>
/// form1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.HtmlControls.HtmlForm form1;
/// <summary>
/// HyperLink1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink HyperLink1;
/// <summary>
/// HyperLink8 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink HyperLink8;
/// <summary>
/// HyperLink3 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink HyperLink3;
/// <summary>
/// LoginName1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LoginName LoginName1;
/// <summary>
/// HyperLink9 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.HyperLink HyperLink9;
/// <summary>
/// LoginStatus1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.LoginStatus LoginStatus1;
/// <summary>
/// ContentPlaceHolder1 control.
/// </summary>
/// <remarks>
/// Auto-generated field.
/// To modify move field declaration from designer file to code-behind file.
/// </remarks>
protected global::System.Web.UI.WebControls.ContentPlaceHolder ContentPlaceHolder1;
}
}
| 34.680412 | 91 | 0.534185 | [
"Apache-2.0"
] | BryceSuchy/Hospital-Online-Scheduling-System | WebApplication1/hoss/Site1.Master.designer.cs | 3,366 | C# |
using System;
using System.Collections.Concurrent;
using System.Collections.Generic;
using System.Runtime.InteropServices;
using System.Threading;
using System.Threading.Tasks;
namespace Launchpad
{
public class LaunchpadSRenderer : IRenderer
{
private readonly MidiDevice _device;
private readonly Light[] _lights;
private readonly byte[] _indexToMidi, _midiToIndex;
private readonly byte[] _normalMsg, _flashMsg, _bufferMsg;
private bool _lightsInvalidated;
private bool _flashState;
public LaunchpadSRenderer(MidiDevice device)
{
_device = device;
// Cache id lookups
var info = DeviceInfo.FromType(device.Type);
_indexToMidi = new byte[256];
_midiToIndex = new byte[256];
for (int i = 0; i < _indexToMidi.Length; i++)
_indexToMidi[i] = 255;
for (int i = 0; i < _midiToIndex.Length; i++)
_midiToIndex[i] = 255;
for (byte y = 0; y < info.Height; y++)
{
for (byte x = 0; x < info.Width; x++)
{
byte midi = info.MidiLayout[info.Height - y - 1, x];
byte index = info.IndexLayout[info.Height - y - 1, x];
if (midi != 255 && index != 255)
{
_indexToMidi[index] = midi;
_midiToIndex[midi] = index;
}
}
}
// Register events
var layoutMsg = Midi.CreateBuffer(MidiMessageType.ControlModeChange, 1);
layoutMsg[1] = 0x00;
layoutMsg[2] = 0x01; // X-Y layout
var clearMsg = Midi.CreateBuffer(MidiMessageType.ControlModeChange, 1);
clearMsg[1] = 0x00;
clearMsg[2] = 0x00; // Clear all lights
_device.Connected += () =>
{
SendMidi(layoutMsg);
SendMidi(clearMsg);
_lightsInvalidated = true;
};
_device.Disconnecting += () =>
{
SendMidi(clearMsg);
};
// Create buffers
_lights = new Light[info.LightCount];
_normalMsg = Midi.CreateBuffer(MidiMessageType.NoteOn, 3, _lights.Length);
_flashMsg = Midi.CreateBuffer(MidiMessageType.NoteOn, 3, _lights.Length);
_bufferMsg = Midi.CreateBuffer(MidiMessageType.ControlModeChange, 1);
_bufferMsg[2] = 32; // Simple
}
public void Clear()
{
for (int i = 0; i < _lights.Length; i++)
{
if (_lights[i].Mode != LightMode.Off)
_lightsInvalidated = true;
_lights[i] = new Light(LightMode.Off);
}
}
public void Set(byte midiId, Light light)
{
switch (light.Mode)
{
case LightMode.Off: SetOff(midiId); break;
case LightMode.Normal: Set(midiId, light.Color); break;
case LightMode.Pulse: SetPulse(midiId, light.Color); break;
case LightMode.Flash: SetFlash(midiId, light.Color, light.FlashColor); break;
}
}
public void Set(byte midiId, byte color)
{
byte index = _midiToIndex[midiId];
if (index == byte.MaxValue)
return;
if (_lights[index].Mode == LightMode.Normal &&
_lights[index].Color == color)
return;
_lights[index] = new Light(LightMode.Normal, color);
_lightsInvalidated = true;
}
public void SetOff(byte midiId)
{
byte index = _midiToIndex[midiId];
if (index == byte.MaxValue)
return;
if (_lights[index].Mode == LightMode.Off)
return;
_lights[index] = new Light(LightMode.Off);
_lightsInvalidated = true;
}
public void SetPulse(byte midiId, byte color)
{
byte index = _midiToIndex[midiId];
if (index == byte.MaxValue || color < 0 || color > 128)
return;
if (_lights[index].Mode == LightMode.Pulse &&
_lights[index].Color == color)
return;
_lights[index] = new Light(LightMode.Pulse, color);
_lightsInvalidated = true;
}
public void SetFlash(byte midiId, byte color1, byte color2)
{
byte index = _midiToIndex[midiId];
if (index == byte.MaxValue)
return;
if (_lights[index].Mode == LightMode.Flash &&
_lights[index].Color == color1 &&
_lights[index].FlashColor == color2)
return;
_lights[index] = new Light(LightMode.Flash, color1, color2);
_lightsInvalidated = true;
}
public void ClockTick()
{
_flashState = !_flashState;
}
public void Render()
{
if (!_lightsInvalidated)
return;
var flashState = _flashState; // Cache because value is updated async
for (int i = 0; i < _lights.Length; i++)
{
byte midi = _indexToMidi[i];
var light = _lights[i];
switch (light.Mode)
{
case LightMode.Off:
_normalMsg[i + 1] = 0;
_flashMsg[i + 1] = 0;
break;
case LightMode.Normal:
_normalMsg[i + 1] = light.Color;
_flashMsg[i + 1] = light.Color;
break;
case LightMode.Pulse: // Not supported, treat as flash
case LightMode.Flash:
_normalMsg[i + 1] = light.Color;
_flashMsg[i + 1] = 0; // light.FlashColor
break;
}
}
if (!flashState)
SendMidi(_normalMsg);
else
SendMidi(_flashMsg);
SendMidi(_bufferMsg); // Reset cursor position
}
private void SendMidi(byte[] buffer)
=> _device.Send(buffer, buffer.Length);
}
} | 35.349727 | 93 | 0.488638 | [
"MIT"
] | RogueException/Launchpad.Net | src/Launchpad.Net/Renderers/LaunchpadSRenderer.cs | 6,469 | C# |
namespace SqlPad.Oracle.ToolTips
{
public partial class ToolTipPartition
{
public ToolTipPartition(PartitionDetailsModelBase dataModel)
{
InitializeComponent();
DataContext = dataModel;
}
}
}
| 16.076923 | 62 | 0.755981 | [
"MIT"
] | Husqvik/SQLPad | SqlPad.Oracle/ToolTips/ToolTipPartition.xaml.cs | 211 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Security.Cryptography;
namespace SSH.IO
{
abstract class HashWriter : PacketWriter
{
private static Dictionary<string, Type> types;
protected HashAlgorithm algorithm;
protected string name;
static HashWriter()
{
types = AppDomain.CurrentDomain.GetAssemblies().SelectMany(a => a.GetTypes()).
Where(t => typeof(HashWriter).IsAssignableFrom(t) && t.IsDefined(typeof(HashWriterAttribute), false)).
SelectMany(t => t.GetCustomAttributes(typeof(HashWriterAttribute), false).
Cast<HashWriterAttribute>().
Select(a => new { a, t })).
ToDictionary(ta => ta.a.Name, ta => ta.t);
}
protected HashWriter(HashAlgorithm h)
: base(new CryptoStream(System.IO.Stream.Null, h, CryptoStreamMode.Write))
{
algorithm = h;
}
public virtual byte[] Hash
{
get
{
algorithm.TransformFinalBlock(new byte[0], 0, 0);
return algorithm.Hash;
}
}
public HashAlgorithm Algorithm
{
get { return algorithm; }
}
public string AlgorithmName
{
get { return name; }
}
public static HashWriter Create(string name)
{
var type = types[name];
return (HashWriter)Activator.CreateInstance(type);
}
public static Type GetType(string name)
{
return types[name];
}
public void Reset()
{
algorithm.Initialize();
}
}
[AttributeUsage(AttributeTargets.Class, AllowMultiple = true)]
internal class HashWriterAttribute : Attribute
{
public string Name { get; set; }
public HashWriterAttribute(string name)
{
this.Name = name;
}
}
}
| 26.923077 | 119 | 0.527619 | [
"MIT"
] | neoscrib/secureshell | SSH/IO/HashWriter.cs | 2,102 | C# |
using BlazorBoilerplate.Infrastructure.Extensions;
using BlazorBoilerplate.Infrastructure.Server.Models;
using BlazorBoilerplate.Infrastructure.Storage.DataModels;
using BlazorBoilerplate.Localization;
using BlazorBoilerplate.Storage;
using IdentityModel;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Identity;
using Microsoft.Extensions.Configuration;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Localization;
using Microsoft.Extensions.Logging;
using Microsoft.Net.Http.Headers;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Newtonsoft.Json.Serialization;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Linq;
using System.Text;
using System.Text.RegularExpressions;
using System.Threading.Tasks;
using static Microsoft.AspNetCore.Http.StatusCodes;
namespace BlazorBoilerplate.Server.Middleware
{
//Logging -> https://salslab.com/a/safely-logging-api-requests-and-responses-in-asp-net-core
//Response -> https://www.c-sharpcorner.com/article/asp-net-core-and-web-api-a-custom-wrapper-for-managing-exceptions-and-consiste/
public class APIResponseRequestLoggingMiddleware : BaseMiddleware
{
private IServiceScopeFactory _scopeFactory;
private readonly Func<object, Task> _clearCacheHeadersDelegate;
private readonly bool _enableAPILogging;
private List<string> _ignorePaths;
public APIResponseRequestLoggingMiddleware(RequestDelegate next,
IConfiguration configuration,
IStringLocalizer<Strings> l,
ILogger<APIResponseRequestLoggingMiddleware> logger) : base(next, l, logger)
{
_enableAPILogging = configuration.GetSection("BlazorBoilerplate:Api:Logging:Enabled").Get<bool>();
_clearCacheHeadersDelegate = ClearCacheHeaders;
_ignorePaths = configuration.GetSection("BlazorBoilerplate:Api:Logging:IgnorePaths").Get<List<string>>() ?? new List<string>();
}
public async Task Invoke(HttpContext httpContext, IServiceScopeFactory scopeFactory, UserManager<ApplicationUser> userManager)
{
_scopeFactory = scopeFactory;
try
{
var request = httpContext.Request;
if (IsSwagger(httpContext) || !request.Path.StartsWithSegments(new PathString("/api")))
{
await _next(httpContext);
}
else
{
Stopwatch stopWatch = Stopwatch.StartNew();
var requestTime = DateTime.UtcNow;
var formattedRequest = await FormatRequest(request);
var originalBodyStream = httpContext.Response.Body;
using (var responseBody = new MemoryStream())
{
try
{
string responseBodyContent = null;
var response = httpContext.Response;
if (new string[] { "/api/data", "/api/externalauth" }.Any(e => request.Path.StartsWithSegments(new PathString(e.ToLower()))))
await _next.Invoke(httpContext);
else
{
response.Body = responseBody;
await _next.Invoke(httpContext);
//wrap response in ApiResponse
if (httpContext.Response.StatusCode == Status200OK)
{
responseBodyContent = await FormatResponse(response);
await HandleSuccessRequestAsync(httpContext, responseBodyContent, Status200OK);
}
else
await HandleNotSuccessRequestAsync(httpContext, httpContext.Response.StatusCode);
}
stopWatch.Stop();
#region Log Request / Response
//Search the Ignore paths from appsettings to ignore the loggin of certian api paths
if (_enableAPILogging && _ignorePaths.All(e => !request.Path.StartsWithSegments(new PathString(e.ToLower()))))
{
try
{
await responseBody.CopyToAsync(originalBodyStream);
//User id = "sub" y default
ApplicationUser user = httpContext.User.Identity.IsAuthenticated
? await userManager.FindByIdAsync(httpContext.User.Claims.Where(c => c.Type == JwtClaimTypes.Subject).First().Value)
: null;
await SafeLog(requestTime,
stopWatch.ElapsedMilliseconds,
response.StatusCode,
request.Method,
request.Path,
request.QueryString.ToString(),
formattedRequest,
responseBodyContent,
httpContext.Connection.RemoteIpAddress.ToString(),
user);
}
catch (Exception ex)
{
_logger.LogWarning("An Inner Middleware exception occurred on SafeLog: " + ex.Message);
}
}
#endregion
}
catch (Exception ex)
{
_logger.LogWarning("An Inner Middleware exception occurred: " + ex.Message);
await HandleExceptionAsync(httpContext, ex);
}
finally
{
responseBody.Seek(0, SeekOrigin.Begin);
await responseBody.CopyToAsync(originalBodyStream);
}
}
}
}
catch (Exception ex)
{
// We can't do anything if the response has already started, just abort.
if (httpContext.Response.HasStarted)
{
_logger.LogWarning("A Middleware exception occurred, but response has already started!");
throw;
}
await HandleExceptionAsync(httpContext, ex);
throw;
}
}
private Task HandleNotSuccessRequestAsync(HttpContext httpContext, int code)
{
ApiResponse apiResponse = new ApiResponse(code, ResponseMessage.GetDescription(code));
httpContext.Response.StatusCode = code;
return RewriteResponseAsApiResponse(httpContext, apiResponse);
}
private Task HandleSuccessRequestAsync(HttpContext httpContext, object body, int code)
{
string jsonString = string.Empty;
var bodyText = !body.ToString().IsValidJson() ? ConvertToJSONString(body) : body.ToString();
ApiResponse apiResponse = null;
try
{
apiResponse = JsonConvert.DeserializeObject<ApiResponse>(bodyText);
}
catch (Exception)
{
}
var bodyContent = JsonConvert.DeserializeObject<dynamic>(bodyText);
if (apiResponse != null)
{
if (apiResponse.StatusCode == 0)
apiResponse.StatusCode = code;
if ((apiResponse.Result == null) && string.IsNullOrEmpty(apiResponse.Message))
apiResponse = new ApiResponse(code, ResponseMessage.GetDescription(code), bodyContent, null);
}
else
apiResponse = new ApiResponse(code, ResponseMessage.GetDescription(code), bodyContent, null);
return RewriteResponseAsApiResponse(httpContext, apiResponse);
}
private async Task<string> FormatRequest(HttpRequest request)
{
request.EnableBuffering();
var buffer = new byte[Convert.ToInt32(request.ContentLength)];
await request.Body.ReadAsync(buffer, 0, buffer.Length);
var bodyAsText = Encoding.UTF8.GetString(buffer);
request.Body.Seek(0, SeekOrigin.Begin);
return $"{request.Method} {request.Scheme} {request.Host}{request.Path} {request.QueryString} {bodyAsText}";
}
private async Task<string> FormatResponse(HttpResponse response)
{
response.Body.Seek(0, SeekOrigin.Begin);
var plainBodyText = await new StreamReader(response.Body).ReadToEndAsync();
response.Body.Seek(0, SeekOrigin.Begin);
return plainBodyText;
}
//TODO VS Studio Info / Warining message over the Disposable of the StreamReader
//private async Task<string> FormatResponse(HttpResponse response)
//{
// using (StreamReader reader = new StreamReader(response.Body))
// {
// response.Body.Seek(0, SeekOrigin.Begin);
// var plainBodyText = await reader.ReadToEndAsync();
// response.Body.Seek(0, SeekOrigin.Begin);
// return plainBodyText;
// }
//}
private string ConvertToJSONString(object rawJSON)
{
return JsonConvert.SerializeObject(rawJSON, JSONSettings());
}
private bool IsSwagger(HttpContext context)
{
return context.Request.Path.StartsWithSegments("/swagger");
}
private JsonSerializerSettings JSONSettings()
{
return new JsonSerializerSettings
{
ContractResolver = new CamelCasePropertyNamesContractResolver(),
Converters = new List<JsonConverter> { new StringEnumConverter() }
};
}
private async Task SafeLog(DateTime requestTime,
long responseMillis,
int statusCode,
string method,
string path,
string queryString,
string requestBody,
string responseBody,
string ipAddress,
ApplicationUser user)
{
if (requestBody.Length > 256)
requestBody = $"(Truncated to 200 chars) {requestBody.Substring(0, 200)}";
// If the response body was an ApiResponse we should just save the Result object
if (responseBody != null && responseBody.Contains("\"result\":"))
{
try
{
ApiResponse apiResponse = JsonConvert.DeserializeObject<ApiResponse>(responseBody);
responseBody = Regex.Replace(apiResponse.Result.ToString(), @"(""[^""\\]*(?:\\.[^""\\]*)*"")|\s+", "$1");
}
catch { }
}
if (responseBody != null && responseBody.Length > 256)
responseBody = $"(Truncated to 200 chars) {responseBody.Substring(0, 200)}";
if (queryString.Length > 256)
queryString = $"(Truncated to 200 chars) {queryString.Substring(0, 200)}";
using (var scope = _scopeFactory.CreateScope())
{
var dbContext = scope.ServiceProvider.GetRequiredService<ApplicationDbContext>();
dbContext.ApiLogs.Add(new ApiLogItem
{
RequestTime = requestTime,
ResponseMillis = responseMillis,
StatusCode = statusCode,
Method = method,
Path = path,
QueryString = queryString,
RequestBody = requestBody,
ResponseBody = responseBody ?? String.Empty,
IPAddress = ipAddress,
ApplicationUserId = user?.Id
});
await dbContext.SaveChangesAsync();
}
}
private Task ClearCacheHeaders(object state)
{
var response = (HttpResponse)state;
response.Headers[HeaderNames.CacheControl] = "no-cache";
response.Headers[HeaderNames.Pragma] = "no-cache";
response.Headers[HeaderNames.Expires] = "-1";
response.Headers.Remove(HeaderNames.ETag);
return Task.CompletedTask;
}
}
}
| 42.157051 | 160 | 0.533795 | [
"MIT"
] | mobinseven/Questionnaire | src/Server/BlazorBoilerplate.Server/Middleware/APIResponseRequestLoggingMiddleware.cs | 13,155 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.