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.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("Exercise")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("Exercise")] [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("ce20236a-3387-4f4c-99eb-9652127d8c8d")] // 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" ]
BorisLechev/Programming-Basics
Documents/Github/Programming-Fundamentals/11. Programming Fundamentals Extended/4. Dictionaries and LINQ/4.DictionariesAndLinq.Lab/Exercise/Properties/AssemblyInfo.cs
1,387
C#
// Copyright © 2019 onwards, Andrew Whewell // All rights reserved. // // Redistribution and use of this software in source and binary forms, with or without modification, are permitted provided that the following conditions are met: // * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. // * Neither the name of the author nor the names of the program's contributors may be used to endorse or promote products derived from this software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHORS OF THE SOFTWARE BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. using System; using System.Collections.Generic; using System.Text; using Microsoft.VisualStudio.TestTools.UnitTesting; using AWhewell.Owin.Utility; namespace Test.AWhewell.Owin.Utility { [TestClass] public class StringBuilderExtensions_Tests { [TestMethod] [DataRow("", 'e', -1)] [DataRow("Tested", 'e', 1)] [DataRow("Tested", 'T', 0)] [DataRow("Tested", 'E', -1)] public void IndexOf_Char_Returns_Expected_Results(string text, char searchChar, int expected) { var builder = new StringBuilder(text); var actual = builder.IndexOf(searchChar); Assert.AreEqual(expected, actual); } [TestMethod] [DataRow("Tested", 'T', 0, 0)] [DataRow("Tested", 'E', 0, -1)] [DataRow("Tested", 't', 6, -1)] [DataRow("Tested", 't', 60, -1)] [DataRow("Tested", 't', -1, null)] [DataRow("Tested", 'e', 0, 1)] [DataRow("Tested", 'e', 1, 1)] [DataRow("Tested", 'e', 2, 4)] [DataRow("Tested", 'e', 3, 4)] [DataRow("Tested", 'e', 4, 4)] [DataRow("Tested", 'e', 5, -1)] public void IndexOf_Char_And_StartIndex_Returns_Expected_Results(string text, char searchChar, int startIndex, int? expected) { var builder = new StringBuilder(text); var outOfRange = false; var actual = int.MinValue; try { actual = builder.IndexOf(searchChar, startIndex); } catch(ArgumentOutOfRangeException) { outOfRange = true; } if(expected == null) { Assert.IsTrue(outOfRange); } else { Assert.AreEqual(expected, actual); } } [TestMethod] [DataRow("Tested", 'e', 4)] [DataRow("Tested", 'T', 0)] [DataRow("Tested", 'E', -1)] public void LastIndexOf_Char_Returns_Expected_Results(string text, char searchChar, int expected) { var builder = new StringBuilder(text); var actual = builder.LastIndexOf(searchChar); Assert.AreEqual(expected, actual); } [TestMethod] [DataRow("Tested", 'T', 5, 0)] [DataRow("Tested", 'E', 5, -1)] [DataRow("Tested", 't', 6, null)] [DataRow("Tested", 't', -1, -1)] [DataRow("Tested", 't', -10, -1)] [DataRow("Tested", 'e', 5, 4)] [DataRow("Tested", 'e', 4, 4)] [DataRow("Tested", 'e', 3, 1)] [DataRow("Tested", 'e', 2, 1)] [DataRow("Tested", 'e', 1, 1)] [DataRow("Tested", 'e', 0, -1)] public void LastIndexOf_Char_And_StartIndex_Returns_Expected_Results(string text, char searchChar, int startIndex, int? expected) { var builder = new StringBuilder(text); var outOfRange = false; var actual = int.MinValue; try { actual = builder.LastIndexOf(searchChar, startIndex); } catch(ArgumentOutOfRangeException) { outOfRange = true; } if(expected == null) { Assert.IsTrue(outOfRange); } else { Assert.AreEqual(expected, actual); } } [TestMethod] [DataRow("Tested", 'e', true)] [DataRow("Tested", 'E', false)] public void Contains_Returns_Expected_Results(string text, char searchChar, bool expected) { var builder = new StringBuilder(text); var actual = builder.Contains(searchChar); Assert.AreEqual(expected, actual); } [TestMethod] [DataRow("", ",", "a", "a")] [DataRow("a", ",", "b", "a,b")] [DataRow("a", ",", "", "a,")] [DataRow("a", ",", null, "a,")] public void AppendWithSeparator_Returns_Expected_Results(string initialBuilderContent, string separator, object value, string expected) { var builder = new StringBuilder(initialBuilderContent); builder.AppendWithSeparator(separator, value); Assert.AreEqual(expected, builder.ToString()); } } }
41.869565
749
0.601073
[ "BSD-3-Clause" ]
awhewell/owin
Tests/Test.Owin.Utility/StringBuilderExtensions_Tests.cs
5,781
C#
using UnityEngine; using UnityEngine.EventSystems; using System.Collections; using ParadoxNotion.Design; using NodeCanvas.Framework; namespace FlowCanvas.Nodes{ [Name("UI Pointer")] [Category("Events/Object/UI")] [Description("Calls UI Pointer based events on target. The Unity Event system has to be set through 'GameObject/UI/Event System'")] public class UIPointerEvents : MessageEventNode<Transform> { private FlowOutput onPointerDown; private FlowOutput onPointerPressed; private FlowOutput onPointerUp; private FlowOutput onPointerEnter; private FlowOutput onPointerExit; private FlowOutput onPointerClick; private GameObject receiver; private PointerEventData eventData; private bool updatePressed = false; protected override string[] GetTargetMessageEvents(){ return new string[]{ "OnPointerEnter", "OnPointerExit", "OnPointerDown", "OnPointerUp", "OnPointerClick" }; } protected override void RegisterPorts(){ onPointerClick = AddFlowOutput("Click"); onPointerDown = AddFlowOutput("Down"); onPointerPressed= AddFlowOutput("Pressed"); onPointerUp = AddFlowOutput("Up"); onPointerEnter = AddFlowOutput("Enter"); onPointerExit = AddFlowOutput("Exit"); AddValueOutput<GameObject>("Receiver", ()=>{ return receiver; }); AddValueOutput<PointerEventData>("Event Data", ()=> { return eventData; }); } void OnPointerDown(ParadoxNotion.Services.MessageRouter.MessageData<PointerEventData> msg){ this.receiver = ResolveReceiver(msg.receiver).gameObject; this.eventData = msg.value; onPointerDown.Call(new Flow()); updatePressed = true; StartCoroutine(UpdatePressed()); } void OnPointerUp(ParadoxNotion.Services.MessageRouter.MessageData<PointerEventData> msg){ this.receiver = ResolveReceiver(msg.receiver).gameObject; this.eventData = msg.value; onPointerUp.Call(new Flow()); updatePressed = false; } IEnumerator UpdatePressed(){ while(updatePressed){ onPointerPressed.Call(new Flow()); yield return null; } } void OnPointerEnter(ParadoxNotion.Services.MessageRouter.MessageData<PointerEventData> msg){ this.receiver = ResolveReceiver(msg.receiver).gameObject; this.eventData = msg.value; onPointerEnter.Call(new Flow()); } void OnPointerExit(ParadoxNotion.Services.MessageRouter.MessageData<PointerEventData> msg){ this.receiver = ResolveReceiver(msg.receiver).gameObject; this.eventData = msg.value; onPointerExit.Call(new Flow()); } void OnPointerClick(ParadoxNotion.Services.MessageRouter.MessageData<PointerEventData> msg){ this.receiver = ResolveReceiver(msg.receiver).gameObject; this.eventData = msg.value; onPointerClick.Call(new Flow()); } } }
33.592593
132
0.755972
[ "MIT" ]
PaulSuarez1/Nedanstad
Nedanstad/Assets/ParadoxNotion/FlowCanvas/Module/Nodes/Events/Object/UI/UIPointerEvents.cs
2,723
C#
#define DEBUG using System; using System.Diagnostics; using System.Threading.Tasks; namespace Microsoft.AppCenter { public partial class AppCenter { internal AppCenter() { } /* Error message to display for unsupported targets. */ const string ErrorMessage = "[AppCenter] ASSERT: Cannot use App Center on this target. If you are on Android or iOS or UWP, you must add the NuGet packages in the Android and iOS and UWP projects as well. Other targets are not yet supported."; static LogLevel PlatformLogLevel { get; set; } static Task<bool> PlatformIsEnabledAsync() { return Task.FromResult(false); } static Task PlatformSetEnabledAsync(bool enabled) { return Task.FromResult(default(object)); } static Task<Guid?> PlatformGetInstallIdAsync() { return Task.FromResult((Guid?)null); } static void PlatformSetLogUrl(string logUrl) { } static void PlatformSetUserId(string userId) { } static bool PlatformConfigured { get; } static void PlatformConfigure(string appSecret) { Debug.WriteLine(ErrorMessage); } static void PlatformStart(params Type[] services) { Debug.WriteLine(ErrorMessage); } static void PlatformStart(string appSecret, params Type[] services) { Debug.WriteLine(ErrorMessage); } static void PlatformSetCustomProperties(CustomProperties customProperties) { } } }
25.476923
227
0.608092
[ "MIT" ]
annakocheshkova/AppCenter-SDK-DotNet
SDK/AppCenter/Microsoft.AppCenter/AppCenter.cs
1,658
C#
using System; using System.Collections.Generic; using System.IO; using System.Security.AccessControl; using System.Text; namespace NExtra.IO { /// <summary> /// This interface can be implemented by classes that /// can be used to work with file system files. /// </summary> /// <remarks> /// Author: Daniel Saidi [daniel.saidi@gmail.com] /// Link: http://danielsaidi.github.com/nextra /// </remarks> public interface IFile { void AppendAllLines(string path, IEnumerable<string> lines); void AppendAllLines(string path, IEnumerable<string> lines, Encoding encoding); void AppendAllText(string path, string content); void AppendAllText(string path, string content, Encoding encoding); StreamWriter AppendText(string path); void Copy(string sourcePath, string destinationPath); void Copy(string sourcePath, string destinationPath, bool overwrite); FileStream Create(string path); FileStream Create(string path, int bufferSize); FileStream Create(string path, int bufferSize, FileOptions options); FileStream Create(string path, int bufferSize, FileOptions options, FileSecurity fileSecurity); StreamWriter CreateText(string path); void Decrypt(string path); void Delete(string path); void Encrypt(string path); bool Exists(string path); FileSecurity GetAccessControl(string path); FileSecurity GetAccessControl(string path, AccessControlSections includeSections); FileAttributes GetAttributes(string path); DateTime GetCreationTime(string path); DateTime GetCreationTimeUtc(string path); DateTime GetLastAccessTime(string path); DateTime GetLastAccessTimeUtc(string path); DateTime GetLastWriteTime(string path); DateTime GetLastWriteTimeUtc(string path); void Move(string sourcePath, string destinationPath); FileStream Open(string path, FileMode mode); FileStream Open(string path, FileMode mode, FileAccess access); FileStream Open(string path, FileMode mode, FileAccess access, FileShare share); FileStream OpenRead(string path); StreamReader OpenText(string path); FileStream OpenWrite(string path); IEnumerable<byte> ReadAllBytes(string path); IEnumerable<string> ReadAllLines(string path); IEnumerable<string> ReadAllLines(string path, Encoding encoding); string ReadAllText(string path); string ReadAllText(string path, Encoding encoding); IEnumerable<string> ReadLines(string path); IEnumerable<string> ReadLines(string path, Encoding encoding); void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName); void Replace(string sourceFileName, string destinationFileName, string destinationBackupFileName, bool ignoreMetadataErrors); void SetAccessControl(string path, FileSecurity fileSecurity); void SetAttributes(string path, FileAttributes fileAttributes); void SetCreationTime(string path, DateTime creationTime); void SetCreationTimeUtc(string path, DateTime creationTimeUtc); void SetLastAccessTime(string path, DateTime lastAccessTime); void SetLastAccessTimeUtc(string path, DateTime lastAccessTimeUtc); void SetLastWriteTime(string path, DateTime lastWriteTime); void SetLastWriteTimeUtc(string path, DateTime lastWriteTimeUtc); void WriteAllBytes(string path, IEnumerable<byte> bytes); void WriteAllLines(string path, IEnumerable<string> lines); void WriteAllText(string path, string content); } }
52.694444
134
0.705851
[ "MIT" ]
danielsaidi/nextra
NExtra/IO/IFile.cs
3,796
C#
using System; namespace Spectrum { public static unsafe class Fourier { private const int MaxLutBits = 16; // 64k private const int MaxLutBins = 1 << MaxLutBits; private const int LutSize = MaxLutBins / 2; private const double TwoPi = 2.0 * Math.PI; private static UnsafeBuffer _lutBuffer = UnsafeBuffer.Create(LutSize, sizeof(Complex)); private static Complex* _lut; static Fourier() { _lut = (Complex*) _lutBuffer; const double angle = TwoPi / MaxLutBins; for (var i = 0; i < LutSize; i++) { _lut[i] = Complex.FromAngle(angle * i).Conjugate(); } } public static void SpectrumPower(Complex* buffer, float* power, int length) { SpectrumPower(buffer, power, length, 0.0f); } public static void SpectrumPower(Complex[] buffer, float[] power, int length, float offset) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (power == null) { throw new ArgumentNullException("power"); } if (buffer.Length < length) { throw new ArgumentException("buffer.Length should be greater or equal to length"); } if (power.Length < length) { throw new ArgumentException("power.Length should be greater or equal to length"); } for (var i = 0; i < length; i++) { var m = buffer[i].Real * buffer[i].Real + buffer[i].Imag * buffer[i].Imag; var strength = (float)(10.0 * Math.Log10(1e-60 + m)) + offset; power[i] = strength; } } public static void SpectrumPower(Complex* buffer, float* power, int length, float offset) { for (var i = 0; i < length; i++) { var m = buffer[i].Real * buffer[i].Real + buffer[i].Imag * buffer[i].Imag; var strength = (float) (10.0 * Math.Log10(1e-60 + m)) + offset; power[i] = strength; } } public static void ScaleFFT(float* src, byte* dest, int length, float minPower, float maxPower) { var scale = byte.MaxValue / (maxPower - minPower); for (var i = 0; i < length; i++) { var magnitude = src[i]; if (magnitude < minPower) { magnitude = minPower; } else if (magnitude > maxPower) { magnitude = maxPower; } dest[i] = (byte) ((magnitude - minPower) * scale); } } public static void ScaleFFT(float[] src, byte[] dest, int length, float minPower, float maxPower) { var scale = byte.MaxValue / (maxPower - minPower); for (var i = 0; i < length; i++) { var magnitude = src[i]; if (magnitude < minPower) { magnitude = minPower; } else if (magnitude > maxPower) { magnitude = maxPower; } dest[i] = (byte) ((magnitude - minPower) * scale); } } public static void SmoothCopy(byte[] source, byte[] destination, int sourceLength, float scale, int offset) { fixed (byte* srcPtr = source) fixed (byte* dstPtr = destination) { SmoothCopy(srcPtr, dstPtr, sourceLength, destination.Length, scale, offset); } } public static void SmoothCopy(byte* srcPtr, byte* dstPtr, int sourceLength, int destinationLength, float scale, int offset) { var r = sourceLength / scale / destinationLength; if (r > 1.0f) { var n = (int) Math.Ceiling(r); for (var i = 0; i < destinationLength; i++) { var k = (int)(i * r - n * 0.5f); var max = (byte) 0; for (var j = 0; j < n; j++) { var index = k + j + offset; if (index >= 0 && index < sourceLength) { if (max < srcPtr[index]) { max = srcPtr[index]; } } } dstPtr[i] = max; } } else { for (var i = 0; i < destinationLength; i++) { var index = (int)(r * i + offset); if (index >= 0 && index < sourceLength) { dstPtr[i] = srcPtr[index]; } } } } public static void ApplyFFTWindow(Complex[] buffer, float[] window, int length) { if (buffer == null) { throw new ArgumentNullException("buffer"); } if (window == null) { throw new ArgumentNullException("window"); } if (buffer.Length < length) { throw new ArgumentException("buffer.Length should be greater or equal to length"); } if (window.Length < length) { throw new ArgumentException("window.Length should be greater or equal to length"); } for (var i = 0; i < length; i++) { buffer[i].Real *= window[i]; buffer[i].Imag *= window[i]; } } public static void ApplyFFTWindow(Complex* buffer, float* window, int length) { for (var i = 0; i < length; i++) { buffer[i].Real *= window[i]; buffer[i].Imag *= window[i]; } } public static void ForwardTransform(Complex* buffer, int length) { if (length <= MaxLutBins) { ForwardTransformLut(buffer, length); } else { ForwardTransformRot(buffer, length); } } private static void ForwardTransformLut(Complex* buffer, int length) { int nm1 = length - 1; int nd2 = length / 2; int i, j, jm1, k, l, m, n, le, le2, ip, nd4; Complex u, t; m = 0; i = length; while (i > 1) { ++m; i = (i >> 1); } j = nd2; for (i = 1; i < nm1; ++i) { if (i < j) { t = buffer[j]; buffer[j] = buffer[i]; buffer[i] = t; } k = nd2; while (k <= j) { j = j - k; k = k / 2; } j += k; } for (l = 1; l <= m; ++l) { le = 1 << l; le2 = le / 2; n = MaxLutBits - l; for (j = 1; j <= le2; ++j) { jm1 = j - 1; u = _lut[jm1 << n]; for (i = jm1; i <= nm1; i += le) { ip = i + le2; t = u * buffer[ip]; buffer[ip] = buffer[i] - t; buffer[i] += t; } } } nd4 = nd2 / 2; for (i = 0; i < nd4; i++) { t = buffer[i]; buffer[i] = buffer[nd2 - i - 1]; buffer[nd2 - i - 1] = t; t = buffer[nd2 + i]; buffer[nd2 + i] = buffer[nd2 + nd2 - i - 1]; buffer[nd2 + nd2 - i - 1] = t; } } private static void ForwardTransformRot(Complex* buffer, int length) { int nm1 = length - 1; int nd2 = length / 2; int i, j, jm1, k, l, m, le, le2, ip, nd4; Complex u, t; m = 0; i = length; while (i > 1) { ++m; i = (i >> 1); } j = nd2; for (i = 1; i < nm1; ++i) { if (i < j) { t = buffer[j]; buffer[j] = buffer[i]; buffer[i] = t; } k = nd2; while (k <= j) { j = j - k; k = k / 2; } j += k; } for (l = 1; l <= m; ++l) { le = 1 << l; le2 = le / 2; var angle = Math.PI / le2; for (j = 1; j <= le2; ++j) { jm1 = j - 1; u = Complex.FromAngle(angle * jm1).Conjugate(); for (i = jm1; i <= nm1; i += le) { ip = i + le2; t = u * buffer[ip]; buffer[ip] = buffer[i] - t; buffer[i] += t; } } } nd4 = nd2 / 2; for (i = 0; i < nd4; i++) { t = buffer[i]; buffer[i] = buffer[nd2 - i - 1]; buffer[nd2 - i - 1] = t; t = buffer[nd2 + i]; buffer[nd2 + i] = buffer[nd2 + nd2 - i - 1]; buffer[nd2 + nd2 - i - 1] = t; } } } }
29.605797
131
0.364891
[ "MIT" ]
BoshenGuan/SpectrumDemo
SpectrumDemo/Spectrum/Fourier.cs
10,216
C#
using UnityEngine; using UnityEngine.UI; using System.Collections; public class ScrollIndexCallback2 : MonoBehaviour { public Text text; public LayoutElement element; public static float[] randomWidths = new float[3] { 100, 150, 50 }; void ScrollCellIndex(int idx) { string name = "Cell " + idx.ToString(); if (text != null) { text.text = name; } element.preferredWidth = randomWidths[Mathf.Abs(idx) % 3]; gameObject.name = name; } }
25.761905
72
0.593346
[ "MIT" ]
Eternity714/LoopScrollRect
Assets/Demo/Scripts/ScrollIndexCallback2.cs
543
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System.Collections; using OpenSim.Region.ScriptEngine.Interfaces; using key = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using rotation = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Quaternion; using vector = OpenSim.Region.ScriptEngine.Shared.LSL_Types.Vector3; using LSL_List = OpenSim.Region.ScriptEngine.Shared.LSL_Types.list; using LSL_String = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLString; using LSL_Integer = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLInteger; using LSL_Float = OpenSim.Region.ScriptEngine.Shared.LSL_Types.LSLFloat; namespace OpenSim.Region.ScriptEngine.Shared.Api.Interfaces { public enum ThreatLevel { None = 0, Nuisance = 1, VeryLow = 2, Low = 3, Moderate = 4, High = 5, VeryHigh = 6, Severe = 7 }; public interface IOSSL_Api { void CheckThreatLevel(ThreatLevel level, string function); //OpenSim functions string osSetDynamicTextureURL(string dynamicID, string contentType, string url, string extraParams, int timer); string osSetDynamicTextureURLBlend(string dynamicID, string contentType, string url, string extraParams, int timer, int alpha); string osSetDynamicTextureURLBlendFace(string dynamicID, string contentType, string url, string extraParams, bool blend, int disp, int timer, int alpha, int face); string osSetDynamicTextureData(string dynamicID, string contentType, string data, string extraParams, int timer); string osSetDynamicTextureDataBlend(string dynamicID, string contentType, string data, string extraParams, int timer, int alpha); string osSetDynamicTextureDataBlendFace(string dynamicID, string contentType, string data, string extraParams, bool blend, int disp, int timer, int alpha, int face); LSL_Float osTerrainGetHeight(int x, int y); LSL_Integer osTerrainSetHeight(int x, int y, double val); void osTerrainFlush(); int osRegionRestart(double seconds); void osRegionNotice(string msg); bool osConsoleCommand(string Command); void osSetParcelMediaURL(string url); void osSetPrimFloatOnWater(int floatYN); // Avatar Info Commands string osGetAgentIP(string agent); LSL_List osGetAgents(); // Teleport commands void osTeleportAgent(string agent, string regionName, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat); void osTeleportAgent(string agent, uint regionX, uint regionY, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat); void osTeleportAgent(string agent, LSL_Types.Vector3 position, LSL_Types.Vector3 lookat); // Animation commands void osAvatarPlayAnimation(string avatar, string animation); void osAvatarStopAnimation(string avatar, string animation); //texture draw functions string osMovePen(string drawList, int x, int y); string osDrawLine(string drawList, int startX, int startY, int endX, int endY); string osDrawLine(string drawList, int endX, int endY); string osDrawText(string drawList, string text); string osDrawEllipse(string drawList, int width, int height); string osDrawRectangle(string drawList, int width, int height); string osDrawFilledRectangle(string drawList, int width, int height); string osDrawPolygon(string drawList, LSL_List x, LSL_List y); string osDrawFilledPolygon(string drawList, LSL_List x, LSL_List y); string osSetFontName(string drawList, string fontName); string osSetFontSize(string drawList, int fontSize); string osSetPenSize(string drawList, int penSize); string osSetPenColour(string drawList, string colour); string osSetPenCap(string drawList, string direction, string type); string osDrawImage(string drawList, int width, int height, string imageUrl); vector osGetDrawStringSize(string contentType, string text, string fontName, int fontSize); void osSetStateEvents(int events); double osList2Double(LSL_Types.list src, int index); void osSetRegionWaterHeight(double height); void osSetRegionSunSettings(bool useEstateSun, bool sunFixed, double sunHour); void osSetEstateSunSettings(bool sunFixed, double sunHour); double osGetCurrentSunHour(); double osSunGetParam(string param); void osSunSetParam(string param, double value); // Wind Module Functions string osWindActiveModelPluginName(); void osWindParamSet(string plugin, string param, float value); float osWindParamGet(string plugin, string param); string osGetScriptEngineName(); string osGetSimulatorVersion(); Hashtable osParseJSON(string JSON); void osMessageObject(key objectUUID,string message); void osMakeNotecard(string notecardName, LSL_Types.list contents); string osGetNotecardLine(string name, int line); string osGetNotecard(string name); int osGetNumberOfNotecardLines(string name); string osAvatarName2Key(string firstname, string lastname); string osKey2Name(string id); // Grid Info Functions string osGetGridNick(); string osGetGridName(); string osGetGridLoginURI(); LSL_String osFormatString(string str, LSL_List strings); LSL_List osMatchString(string src, string pattern, int start); // Information about data loaded into the region string osLoadedCreationDate(); string osLoadedCreationTime(); string osLoadedCreationID(); LSL_List osGetLinkPrimitiveParams(int linknumber, LSL_List rules); key osNpcCreate(string user, string name, vector position, key cloneFrom); void osNpcMoveTo(key npc, vector position); void osNpcSay(key npc, string message); void osNpcRemove(key npc); } }
47.5
125
0.707702
[ "BSD-3-Clause" ]
Ideia-Boa/diva-distribution
OpenSim/Region/ScriptEngine/Shared/Api/Interface/IOSSL_Api.cs
7,790
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; namespace StackExchange.Opserver.Data.Redis { public partial class RedisInstance { public static RedisInstance Get(RedisConnectionInfo info) { foreach (var i in RedisModule.Instances) { if (i.ConnectionInfo == info) return i; } return null; } public static RedisInstance Get(string connectionString) { if (connectionString.IsNullOrEmpty()) return null; if (connectionString.Contains(":")) { var parts = connectionString.Split(StringSplits.Colon); if (parts.Length != 2) return null; if (int.TryParse(parts[1], out int port)) return Get(parts[0], port); } else { return GetAll(connectionString).FirstOrDefault(); } return null; } public static RedisInstance Get(string host, int port) { foreach (var ri in RedisModule.Instances) { if (ri.Host == host && ri.Port == port) return ri; } var shortHost = host.Split(StringSplits.Period)[0]; foreach (var ri in RedisModule.Instances) { if (ri.Port == port && ri.ShortHost == shortHost) return ri; } return null; } public static RedisInstance Get(int port, IPAddress ipAddress) { foreach (var i in RedisModule.Instances) { if (i.ConnectionInfo.Port != port) continue; foreach (var ip in i.ConnectionInfo.IPAddresses) { if (ip.Equals(ipAddress)) return i; } } return null; } public static List<RedisInstance> GetAll(string node) { return RedisModule.Instances.Where(ri => string.Equals(ri.Host, node, StringComparison.InvariantCultureIgnoreCase)).ToList(); } } }
31.220588
137
0.531324
[ "MIT" ]
supershowwei/Opserver
Opserver.Core/Data/Redis/RedisInstance.Cache.cs
2,125
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using Coda.Payroll.Models.Statutory; using Coda.Payroll.Models.Statutory.Assessments; namespace Coda.Payroll.Abstractions { public interface IStatutorySickPayCalculationEngine { StatutoryCalculationResult<SickPayAssessment> Calculate(SickPayAssessment model, IEnumerable<SickPayAssessment> previousSicknotes = null); } public interface IStatutoryMaternityPayCalculationEngine { StatutoryCalculationResult<MaternityPayAssessment> Calculate(MaternityPayAssessment model); } public interface IStatutoryPaternityPayCalculationEngine { StatutoryCalculationResult<PaternityPayAssessment> Calculate(PaternityPayAssessment model); } }
31.08
146
0.801802
[ "Apache-2.0" ]
WhatFor/Coda.Payroll
Coda.Payroll/Abstractions/IStatutoryCalculationEngine.cs
779
C#
using UnityEngine.EventSystems; namespace Tools.UI.Card { /// <summary> /// GameController hand zone. /// </summary> public class UiZoneHand : UiBaseDropZone { protected override void OnPointerUp(PointerEventData eventData) => CardHand?.Unselect(); } }
24.166667
96
0.662069
[ "MIT" ]
1665800095fghk/UiCard
Assets/Scripts/UICard/UiCardZones/UiZoneHand.cs
292
C#
using Luban.Job.Common.RawDefs; using System.Collections.Generic; namespace Luban.Job.Proto.RawDefs { public class Defines : DefinesCommon { public List<Service> ProtoServices { get; set; } = new List<Service>(); public List<PProto> Protos { get; set; } = new List<PProto>(); public List<PRpc> Rpcs { get; set; } = new List<PRpc>(); } }
25.066667
79
0.640957
[ "MIT" ]
CN-Zxcv/luban
src/Luban.Job.Proto/Source/RawDefs/Defines.cs
376
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 Microsoft.AspNetCore.Razor.Language; using Microsoft.CodeAnalysis.Razor.Completion; using Xunit; namespace Microsoft.AspNetCore.Razor.LanguageServer.Completion { public class DirectiveAttributeTransitionCompletionItemProviderTest { public DirectiveAttributeTransitionCompletionItemProviderTest() { TagHelperDocumentContext = TagHelperDocumentContext.Create(prefix: string.Empty, Array.Empty<TagHelperDescriptor>()); Provider = new DirectiveAttributeTransitionCompletionItemProvider(); } private TagHelperDocumentContext TagHelperDocumentContext { get; } private DirectiveAttributeTransitionCompletionItemProvider Provider { get; } private RazorCompletionItem TransitionCompletionItem => DirectiveAttributeTransitionCompletionItemProvider.TransitionCompletionItem; [Fact] public void GetCompletionItems_AttributeAreaInNonComponentFile_ReturnsEmptyList() { // Arrange var syntaxTree = GetSyntaxTree("<input />", FileKinds.Legacy); var location = new SourceSpan(7, 0); // Act var result = Provider.GetCompletionItems(syntaxTree, TagHelperDocumentContext, location); // Assert Assert.Empty(result); } [Fact] public void GetCompletionItems_OutsideOfFile_ReturnsEmptyList() { // Arrange var syntaxTree = GetSyntaxTree("<input />"); var location = new SourceSpan(50, 0); // Act var result = Provider.GetCompletionItems(syntaxTree, TagHelperDocumentContext, location); // Assert Assert.Empty(result); } [Fact] public void GetCompletionItems_NonAttribute_ReturnsEmptyList() { // Arrange var syntaxTree = GetSyntaxTree("<input />"); var location = new SourceSpan(2, 0); // Act var result = Provider.GetCompletionItems(syntaxTree, TagHelperDocumentContext, location); // Assert Assert.Empty(result); } [Fact] public void GetCompletionItems_ExistingAttribute_ReturnsEmptyList() { // Arrange var syntaxTree = GetSyntaxTree("<input @ />"); var location = new SourceSpan(8, 0); // Act var result = Provider.GetCompletionItems(syntaxTree, TagHelperDocumentContext, location); // Assert Assert.Empty(result); } [Fact] public void GetCompletionItems_AttributeAreaInComponentFile_ReturnsTransitionCompletionItem() { // Arrange var syntaxTree = GetSyntaxTree("<input />"); var location = new SourceSpan(7, 0); // Act var result = Provider.GetCompletionItems(syntaxTree, TagHelperDocumentContext, location); // Assert var item = Assert.Single(result); Assert.Same(item, TransitionCompletionItem); } private static RazorSyntaxTree GetSyntaxTree(string text, string fileKind = null) { fileKind = fileKind ?? FileKinds.Component; var sourceDocument = TestRazorSourceDocument.Create(text); var projectEngine = RazorProjectEngine.Create(builder => { }); var codeDocument = projectEngine.ProcessDesignTime(sourceDocument, fileKind, Array.Empty<RazorSourceDocument>(), Array.Empty<TagHelperDescriptor>()); var syntaxTree = codeDocument.GetSyntaxTree(); return syntaxTree; } } }
35.518519
161
0.641814
[ "Apache-2.0" ]
Pilchie/aspnetcore-tooling
src/Razor/test/Microsoft.AspNetCore.Razor.LanguageServer.Test/Completion/DirectiveAttributeTransitionCompletionItemProviderTest.cs
3,838
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.Buffers; using System.Diagnostics; using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Threading; using System.Threading.Tasks; namespace System.IO { public abstract class Stream : MarshalByRefObject, IDisposable, IAsyncDisposable { public static readonly Stream Null = new NullStream(); /// <summary>To serialize async operations on streams that don't implement their own.</summary> private protected SemaphoreSlim? _asyncActiveSemaphore; [MemberNotNull(nameof(_asyncActiveSemaphore))] private protected SemaphoreSlim EnsureAsyncActiveSemaphoreInitialized() => // Lazily-initialize _asyncActiveSemaphore. As we're never accessing the SemaphoreSlim's // WaitHandle, we don't need to worry about Disposing it in the case of a race condition. #pragma warning disable CS8774 // We lack a NullIffNull annotation for Volatile.Read Volatile.Read(ref _asyncActiveSemaphore) ?? #pragma warning restore CS8774 Interlocked.CompareExchange(ref _asyncActiveSemaphore, new SemaphoreSlim(1, 1), null) ?? _asyncActiveSemaphore; public abstract bool CanRead { get; } public abstract bool CanWrite { get; } public abstract bool CanSeek { get; } public virtual bool CanTimeout => false; public abstract long Length { get; } public abstract long Position { get; set; } public virtual int ReadTimeout { get => throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); set => throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } public virtual int WriteTimeout { get => throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); set => throw new InvalidOperationException(SR.InvalidOperation_TimeoutsNotSupported); } public void CopyTo(Stream destination) => CopyTo(destination, GetCopyBufferSize()); public virtual void CopyTo(Stream destination, int bufferSize) { ValidateCopyToArguments(destination, bufferSize); if (!CanRead) { if (CanWrite) { ThrowHelper.ThrowNotSupportedException_UnreadableStream(); } ThrowHelper.ThrowObjectDisposedException_StreamClosed(GetType().Name); } byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize); try { int bytesRead; while ((bytesRead = Read(buffer, 0, buffer.Length)) != 0) { destination.Write(buffer, 0, bytesRead); } } finally { ArrayPool<byte>.Shared.Return(buffer); } } public Task CopyToAsync(Stream destination) => CopyToAsync(destination, GetCopyBufferSize()); public Task CopyToAsync(Stream destination, int bufferSize) => CopyToAsync(destination, bufferSize, CancellationToken.None); public Task CopyToAsync(Stream destination, CancellationToken cancellationToken) => CopyToAsync(destination, GetCopyBufferSize(), cancellationToken); public virtual Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) { ValidateCopyToArguments(destination, bufferSize); if (!CanRead) { if (CanWrite) { ThrowHelper.ThrowNotSupportedException_UnreadableStream(); } ThrowHelper.ThrowObjectDisposedException_StreamClosed(GetType().Name); } return Core(this, destination, bufferSize, cancellationToken); static async Task Core(Stream source, Stream destination, int bufferSize, CancellationToken cancellationToken) { byte[] buffer = ArrayPool<byte>.Shared.Rent(bufferSize); try { int bytesRead; while ((bytesRead = await source.ReadAsync(new Memory<byte>(buffer), cancellationToken).ConfigureAwait(false)) != 0) { await destination.WriteAsync(new ReadOnlyMemory<byte>(buffer, 0, bytesRead), cancellationToken).ConfigureAwait(false); } } finally { ArrayPool<byte>.Shared.Return(buffer); } } } private int GetCopyBufferSize() { // This value was originally picked to be the largest multiple of 4096 that is still smaller than the large object heap threshold (85K). // The CopyTo{Async} buffer is short-lived and is likely to be collected at Gen0, and it offers a significant improvement in Copy // performance. Since then, the base implementations of CopyTo{Async} have been updated to use ArrayPool, which will end up rounding // this size up to the next power of two (131,072), which will by default be on the large object heap. However, most of the time // the buffer should be pooled, the LOH threshold is now configurable and thus may be different than 85K, and there are measurable // benefits to using the larger buffer size. So, for now, this value remains. const int DefaultCopyBufferSize = 81920; int bufferSize = DefaultCopyBufferSize; if (CanSeek) { long length = Length; long position = Position; if (length <= position) // Handles negative overflows { // There are no bytes left in the stream to copy. // However, because CopyTo{Async} is virtual, we need to // ensure that any override is still invoked to provide its // own validation, so we use the smallest legal buffer size here. bufferSize = 1; } else { long remaining = length - position; if (remaining > 0) { // In the case of a positive overflow, stick to the default size bufferSize = (int)Math.Min(bufferSize, remaining); } } } return bufferSize; } public void Dispose() => Close(); public virtual void Close() { // When initially designed, Stream required that all cleanup logic went into Close(), // but this was thought up before IDisposable was added and never revisited. All subclasses // should put their cleanup now in Dispose(bool). Dispose(true); GC.SuppressFinalize(this); } protected virtual void Dispose(bool disposing) { // Note: Never change this to call other virtual methods on Stream // like Write, since the state on subclasses has already been // torn down. This is the last code to run on cleanup for a stream. } public virtual ValueTask DisposeAsync() { try { Dispose(); return default; } catch (Exception exc) { return ValueTask.FromException(exc); } } public abstract void Flush(); public Task FlushAsync() => FlushAsync(CancellationToken.None); public virtual Task FlushAsync(CancellationToken cancellationToken) => Task.Factory.StartNew( static state => ((Stream)state!).Flush(), this, cancellationToken, TaskCreationOptions.DenyChildAttach, TaskScheduler.Default); [Obsolete("CreateWaitHandle has been deprecated. Use the ManualResetEvent(false) constructor instead.")] protected virtual WaitHandle CreateWaitHandle() => new ManualResetEvent(false); public virtual IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) => BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); internal Task<int> BeginReadInternal( byte[] buffer, int offset, int count, AsyncCallback? callback, object? state, bool serializeAsynchronously, bool apm) { ValidateBufferArguments(buffer, offset, count); if (!CanRead) { ThrowHelper.ThrowNotSupportedException_UnreadableStream(); } // To avoid a race with a stream's position pointer & generating race conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. SemaphoreSlim semaphore = EnsureAsyncActiveSemaphoreInitialized(); Task? semaphoreTask = null; if (serializeAsynchronously) { semaphoreTask = semaphore.WaitAsync(); } else { #pragma warning disable CA1416 // Validate platform compatibility, issue: https://github.com/dotnet/runtime/issues/44543 semaphore.Wait(); #pragma warning restore CA1416 } // Create the task to asynchronously do a Read. This task serves both // as the asynchronous work item and as the IAsyncResult returned to the user. var task = new ReadWriteTask(true /*isRead*/, apm, delegate { // The ReadWriteTask stores all of the parameters to pass to Read. // As we're currently inside of it, we can get the current task // and grab the parameters from it. var thisTask = Task.InternalCurrent as ReadWriteTask; Debug.Assert(thisTask != null && thisTask._stream != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask, and stream should be set"); try { // Do the Read and return the number of bytes read return thisTask._stream.Read(thisTask._buffer!, thisTask._offset, thisTask._count); } finally { // If this implementation is part of Begin/EndXx, then the EndXx method will handle // finishing the async operation. However, if this is part of XxAsync, then there won't // be an end method, and this task is responsible for cleaning up. if (!thisTask._apm) { thisTask._stream.FinishTrackingAsyncOperation(thisTask); } thisTask.ClearBeginState(); // just to help alleviate some memory pressure } }, state, this, buffer, offset, count, callback); // Schedule it if (semaphoreTask != null) { RunReadWriteTaskWhenReady(semaphoreTask, task); } else { RunReadWriteTask(task); } return task; // return it } public virtual int EndRead(IAsyncResult asyncResult) { if (asyncResult is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult); } ReadWriteTask? readTask = asyncResult as ReadWriteTask; if (readTask is null || !readTask._isRead) { ThrowHelper.ThrowArgumentException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple); } else if (readTask._endCalled) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple); } try { return readTask.GetAwaiter().GetResult(); // block until completion, then get result / propagate any exception } finally { FinishTrackingAsyncOperation(readTask); } } public Task<int> ReadAsync(byte[] buffer, int offset, int count) => ReadAsync(buffer, offset, count, CancellationToken.None); public virtual Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled<int>(cancellationToken) : BeginEndReadAsync(buffer, offset, count); public virtual ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) { if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> array)) { return new ValueTask<int>(ReadAsync(array.Array!, array.Offset, array.Count, cancellationToken)); } byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length); return FinishReadAsync(ReadAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer, buffer); static async ValueTask<int> FinishReadAsync(Task<int> readTask, byte[] localBuffer, Memory<byte> localDestination) { try { int result = await readTask.ConfigureAwait(false); new ReadOnlySpan<byte>(localBuffer, 0, result).CopyTo(localDestination.Span); return result; } finally { ArrayPool<byte>.Shared.Return(localBuffer); } } } /// <summary> /// Asynchronously reads bytes from the current stream, advances the position within the stream until the <paramref name="buffer"/> is filled, /// and monitors cancellation requests. /// </summary> /// <param name="buffer">The buffer to write the data into.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous read operation.</returns> /// <exception cref="EndOfStreamException"> /// The end of the stream is reached before filling the <paramref name="buffer"/>. /// </exception> /// <remarks> /// When <paramref name="buffer"/> is empty, this read operation will be completed without waiting for available data in the stream. /// </remarks> public ValueTask ReadExactlyAsync(Memory<byte> buffer, CancellationToken cancellationToken = default) { ValueTask<int> vt = ReadAtLeastAsyncCore(buffer, buffer.Length, throwOnEndOfStream: true, cancellationToken); // transfer the ValueTask<int> to a ValueTask without allocating here. return ValueTask.DangerousCreateFromTypedValueTask(vt); } /// <summary> /// Asynchronously reads <paramref name="count"/> number of bytes from the current stream, advances the position within the stream, /// and monitors cancellation requests. /// </summary> /// <param name="buffer">The buffer to write the data into.</param> /// <param name="offset">The byte offset in <paramref name="buffer"/> at which to begin writing data from the stream.</param> /// <param name="count">The number of bytes to be read from the current stream.</param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns>A task that represents the asynchronous read operation.</returns> /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="offset"/> is outside the bounds of <paramref name="buffer"/>. /// -or- /// <paramref name="count"/> is negative. /// -or- /// The range specified by the combination of <paramref name="offset"/> and <paramref name="count"/> exceeds the /// length of <paramref name="buffer"/>. /// </exception> /// <exception cref="EndOfStreamException"> /// The end of the stream is reached before reading <paramref name="count"/> number of bytes. /// </exception> /// <remarks> /// When <paramref name="count"/> is 0 (zero), this read operation will be completed without waiting for available data in the stream. /// </remarks> public ValueTask ReadExactlyAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken = default) { ValidateBufferArguments(buffer, offset, count); ValueTask<int> vt = ReadAtLeastAsyncCore(buffer.AsMemory(offset, count), count, throwOnEndOfStream: true, cancellationToken); // transfer the ValueTask<int> to a ValueTask without allocating here. return ValueTask.DangerousCreateFromTypedValueTask(vt); } /// <summary> /// Asynchronously reads at least a minimum number of bytes from the current stream, advances the position within the stream by the /// number of bytes read, and monitors cancellation requests. /// </summary> /// <param name="buffer">The region of memory to write the data into.</param> /// <param name="minimumBytes">The minimum number of bytes to read into the buffer.</param> /// <param name="throwOnEndOfStream"> /// <see langword="true"/> to throw an exception if the end of the stream is reached before reading <paramref name="minimumBytes"/> of bytes; /// <see langword="false"/> to return less than <paramref name="minimumBytes"/> when the end of the stream is reached. /// The default is <see langword="true"/>. /// </param> /// <param name="cancellationToken">The token to monitor for cancellation requests.</param> /// <returns> /// A task that represents the asynchronous read operation. The value of its <see cref="ValueTask{TResult}.Result"/> property contains the /// total number of bytes read into the buffer. This is guaranteed to be greater than or equal to <paramref name="minimumBytes"/> when /// <paramref name="throwOnEndOfStream"/> is <see langword="true"/>. This will be less than <paramref name="minimumBytes"/> when the end /// of the stream is reached and <paramref name="throwOnEndOfStream"/> is <see langword="false"/>. This can be less than the number of /// bytes allocated in the buffer if that many bytes are not currently available. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="minimumBytes"/> is negative, or is greater than the length of <paramref name="buffer"/>. /// </exception> /// <exception cref="EndOfStreamException"> /// <paramref name="throwOnEndOfStream"/> is <see langword="true"/> and the end of the stream is reached before reading /// <paramref name="minimumBytes"/> bytes of data. /// </exception> /// <remarks> /// When <paramref name="minimumBytes"/> is 0 (zero), this read operation will be completed without waiting for available data in the stream. /// </remarks> public ValueTask<int> ReadAtLeastAsync(Memory<byte> buffer, int minimumBytes, bool throwOnEndOfStream = true, CancellationToken cancellationToken = default) { ValidateReadAtLeastArguments(buffer.Length, minimumBytes); return ReadAtLeastAsyncCore(buffer, minimumBytes, throwOnEndOfStream, cancellationToken); } // No argument checking is done here. It is up to the caller. [AsyncMethodBuilder(typeof(PoolingAsyncValueTaskMethodBuilder<>))] private async ValueTask<int> ReadAtLeastAsyncCore(Memory<byte> buffer, int minimumBytes, bool throwOnEndOfStream, CancellationToken cancellationToken) { Debug.Assert(minimumBytes <= buffer.Length); int totalRead = 0; while (totalRead < minimumBytes) { int read = await ReadAsync(buffer.Slice(totalRead), cancellationToken).ConfigureAwait(false); if (read == 0) { if (throwOnEndOfStream) { ThrowHelper.ThrowEndOfFileException(); } return totalRead; } totalRead += read; } return totalRead; } #if NATIVEAOT // TODO: https://github.com/dotnet/corert/issues/3251 private static bool HasOverriddenBeginEndRead() => true; private static bool HasOverriddenBeginEndWrite() => true; #else [MethodImpl(MethodImplOptions.InternalCall)] private extern bool HasOverriddenBeginEndRead(); [MethodImpl(MethodImplOptions.InternalCall)] private extern bool HasOverriddenBeginEndWrite(); #endif private Task<int> BeginEndReadAsync(byte[] buffer, int offset, int count) { if (!HasOverriddenBeginEndRead()) { // If the Stream does not override Begin/EndRead, then we can take an optimized path // that skips an extra layer of tasks / IAsyncResults. return BeginReadInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false); } // Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality. return TaskFactory<int>.FromAsyncTrim( this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count }, (stream, args, callback, state) => stream.BeginRead(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler (stream, asyncResult) => stream.EndRead(asyncResult)); // cached by compiler } private struct ReadWriteParameters // struct for arguments to Read and Write calls { internal byte[] Buffer; internal int Offset; internal int Count; } public virtual IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) => BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: false, apm: true); internal Task BeginWriteInternal( byte[] buffer, int offset, int count, AsyncCallback? callback, object? state, bool serializeAsynchronously, bool apm) { ValidateBufferArguments(buffer, offset, count); if (!CanWrite) { ThrowHelper.ThrowNotSupportedException_UnwritableStream(); } // To avoid a race condition with a stream's position pointer & generating conditions // with internal buffer indexes in our own streams that // don't natively support async IO operations when there are multiple // async requests outstanding, we will block the application's main // thread if it does a second IO request until the first one completes. SemaphoreSlim semaphore = EnsureAsyncActiveSemaphoreInitialized(); Task? semaphoreTask = null; if (serializeAsynchronously) { semaphoreTask = semaphore.WaitAsync(); // kick off the asynchronous wait, but don't block } else { #pragma warning disable CA1416 // Validate platform compatibility, issue: https://github.com/dotnet/runtime/issues/44543 semaphore.Wait(); // synchronously wait here #pragma warning restore CA1416 } // Create the task to asynchronously do a Write. This task serves both // as the asynchronous work item and as the IAsyncResult returned to the user. var task = new ReadWriteTask(false /*isRead*/, apm, delegate { // The ReadWriteTask stores all of the parameters to pass to Write. // As we're currently inside of it, we can get the current task // and grab the parameters from it. var thisTask = Task.InternalCurrent as ReadWriteTask; Debug.Assert(thisTask != null && thisTask._stream != null, "Inside ReadWriteTask, InternalCurrent should be the ReadWriteTask, and stream should be set"); try { // Do the Write thisTask._stream.Write(thisTask._buffer!, thisTask._offset, thisTask._count); return 0; // not used, but signature requires a value be returned } finally { // If this implementation is part of Begin/EndXx, then the EndXx method will handle // finishing the async operation. However, if this is part of XxAsync, then there won't // be an end method, and this task is responsible for cleaning up. if (!thisTask._apm) { thisTask._stream.FinishTrackingAsyncOperation(thisTask); } thisTask.ClearBeginState(); // just to help alleviate some memory pressure } }, state, this, buffer, offset, count, callback); // Schedule it if (semaphoreTask != null) { RunReadWriteTaskWhenReady(semaphoreTask, task); } else { RunReadWriteTask(task); } return task; // return it } private static void RunReadWriteTaskWhenReady(Task asyncWaiter, ReadWriteTask readWriteTask) { Debug.Assert(readWriteTask != null); Debug.Assert(asyncWaiter != null); // If the wait has already completed, run the task. if (asyncWaiter.IsCompleted) { Debug.Assert(asyncWaiter.IsCompletedSuccessfully, "The semaphore wait should always complete successfully."); RunReadWriteTask(readWriteTask); } else // Otherwise, wait for our turn, and then run the task. { asyncWaiter.ContinueWith(static (t, state) => { Debug.Assert(t.IsCompletedSuccessfully, "The semaphore wait should always complete successfully."); var rwt = (ReadWriteTask)state!; Debug.Assert(rwt._stream != null, "Validates that this code isn't run a second time."); RunReadWriteTask(rwt); // RunReadWriteTask(readWriteTask); }, readWriteTask, default, TaskContinuationOptions.ExecuteSynchronously, TaskScheduler.Default); } } private static void RunReadWriteTask(ReadWriteTask readWriteTask) { Debug.Assert(readWriteTask != null); // Schedule the task. ScheduleAndStart must happen after the write to _activeReadWriteTask to avoid a race. // Internally, we're able to directly call ScheduleAndStart rather than Start, avoiding // two interlocked operations. However, if ReadWriteTask is ever changed to use // a cancellation token, this should be changed to use Start. readWriteTask.m_taskScheduler = TaskScheduler.Default; readWriteTask.ScheduleAndStart(needsProtection: false); } private void FinishTrackingAsyncOperation(ReadWriteTask task) { Debug.Assert(_asyncActiveSemaphore != null, "Must have been initialized in order to get here."); task._endCalled = true; _asyncActiveSemaphore.Release(); } public virtual void EndWrite(IAsyncResult asyncResult) { if (asyncResult is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult); } ReadWriteTask? writeTask = asyncResult as ReadWriteTask; if (writeTask is null || writeTask._isRead) { ThrowHelper.ThrowArgumentException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple); } else if (writeTask._endCalled) { ThrowHelper.ThrowInvalidOperationException(ExceptionResource.InvalidOperation_WrongAsyncResultOrEndCalledMultiple); } try { writeTask.GetAwaiter().GetResult(); // block until completion, then propagate any exceptions Debug.Assert(writeTask.Status == TaskStatus.RanToCompletion); } finally { FinishTrackingAsyncOperation(writeTask); } } // Task used by BeginRead / BeginWrite to do Read / Write asynchronously. // A single instance of this task serves four purposes: // 1. The work item scheduled to run the Read / Write operation // 2. The state holding the arguments to be passed to Read / Write // 3. The IAsyncResult returned from BeginRead / BeginWrite // 4. The completion action that runs to invoke the user-provided callback. // This last item is a bit tricky. Before the AsyncCallback is invoked, the // IAsyncResult must have completed, so we can't just invoke the handler // from within the task, since it is the IAsyncResult, and thus it's not // yet completed. Instead, we use AddCompletionAction to install this // task as its own completion handler. That saves the need to allocate // a separate completion handler, it guarantees that the task will // have completed by the time the handler is invoked, and it allows // the handler to be invoked synchronously upon the completion of the // task. This all enables BeginRead / BeginWrite to be implemented // with a single allocation. private sealed class ReadWriteTask : Task<int>, ITaskCompletionAction { internal readonly bool _isRead; internal readonly bool _apm; // true if this is from Begin/EndXx; false if it's from XxAsync internal bool _endCalled; internal Stream? _stream; internal byte[]? _buffer; internal readonly int _offset; internal readonly int _count; private AsyncCallback? _callback; private ExecutionContext? _context; internal void ClearBeginState() // Used to allow the args to Read/Write to be made available for GC { _stream = null; _buffer = null; } public ReadWriteTask( bool isRead, bool apm, Func<object?, int> function, object? state, Stream stream, byte[] buffer, int offset, int count, AsyncCallback? callback) : base(function, state, CancellationToken.None, TaskCreationOptions.DenyChildAttach) { Debug.Assert(function != null); Debug.Assert(stream != null); // Store the arguments _isRead = isRead; _apm = apm; _stream = stream; _buffer = buffer; _offset = offset; _count = count; // If a callback was provided, we need to: // - Store the user-provided handler // - Capture an ExecutionContext under which to invoke the handler // - Add this task as its own completion handler so that the Invoke method // will run the callback when this task completes. if (callback != null) { _callback = callback; _context = ExecutionContext.Capture(); base.AddCompletionAction(this); } } private static void InvokeAsyncCallback(object? completedTask) { Debug.Assert(completedTask is ReadWriteTask); var rwc = (ReadWriteTask)completedTask; AsyncCallback? callback = rwc._callback; Debug.Assert(callback != null); rwc._callback = null; callback(rwc); } private static ContextCallback? s_invokeAsyncCallback; void ITaskCompletionAction.Invoke(Task completingTask) { // Get the ExecutionContext. If there is none, just run the callback // directly, passing in the completed task as the IAsyncResult. // If there is one, process it with ExecutionContext.Run. ExecutionContext? context = _context; if (context is null) { AsyncCallback? callback = _callback; Debug.Assert(callback != null); _callback = null; callback(completingTask); } else { _context = null; ContextCallback? invokeAsyncCallback = s_invokeAsyncCallback ??= InvokeAsyncCallback; ExecutionContext.RunInternal(context, invokeAsyncCallback, this); } } bool ITaskCompletionAction.InvokeMayRunArbitraryCode => true; } public Task WriteAsync(byte[] buffer, int offset, int count) => WriteAsync(buffer, offset, count, CancellationToken.None); public virtual Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => // If cancellation was requested, bail early with an already completed task. // Otherwise, return a task that represents the Begin/End methods. cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : BeginEndWriteAsync(buffer, offset, count); public virtual ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) { if (MemoryMarshal.TryGetArray(buffer, out ArraySegment<byte> array)) { return new ValueTask(WriteAsync(array.Array!, array.Offset, array.Count, cancellationToken)); } byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length); buffer.Span.CopyTo(sharedBuffer); return new ValueTask(FinishWriteAsync(WriteAsync(sharedBuffer, 0, buffer.Length, cancellationToken), sharedBuffer)); } private static async Task FinishWriteAsync(Task writeTask, byte[] localBuffer) { try { await writeTask.ConfigureAwait(false); } finally { ArrayPool<byte>.Shared.Return(localBuffer); } } private Task BeginEndWriteAsync(byte[] buffer, int offset, int count) { if (!HasOverriddenBeginEndWrite()) { // If the Stream does not override Begin/EndWrite, then we can take an optimized path // that skips an extra layer of tasks / IAsyncResults. return BeginWriteInternal(buffer, offset, count, null, null, serializeAsynchronously: true, apm: false); } // Otherwise, we need to wrap calls to Begin/EndWrite to ensure we use the derived type's functionality. return TaskFactory<VoidTaskResult>.FromAsyncTrim( this, new ReadWriteParameters { Buffer = buffer, Offset = offset, Count = count }, (stream, args, callback, state) => stream.BeginWrite(args.Buffer, args.Offset, args.Count, callback, state), // cached by compiler (stream, asyncResult) => // cached by compiler { stream.EndWrite(asyncResult); return default; }); } public abstract long Seek(long offset, SeekOrigin origin); public abstract void SetLength(long value); public abstract int Read(byte[] buffer, int offset, int count); public virtual int Read(Span<byte> buffer) { byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length); try { int numRead = Read(sharedBuffer, 0, buffer.Length); if ((uint)numRead > (uint)buffer.Length) { throw new IOException(SR.IO_StreamTooLong); } new ReadOnlySpan<byte>(sharedBuffer, 0, numRead).CopyTo(buffer); return numRead; } finally { ArrayPool<byte>.Shared.Return(sharedBuffer); } } public virtual int ReadByte() { var oneByteArray = new byte[1]; int r = Read(oneByteArray, 0, 1); return r == 0 ? -1 : oneByteArray[0]; } /// <summary> /// Reads bytes from the current stream and advances the position within the stream until the <paramref name="buffer"/> is filled. /// </summary> /// <param name="buffer">A region of memory. When this method returns, the contents of this region are replaced by the bytes read from the current stream.</param> /// <exception cref="EndOfStreamException"> /// The end of the stream is reached before filling the <paramref name="buffer"/>. /// </exception> /// <remarks> /// When <paramref name="buffer"/> is empty, this read operation will be completed without waiting for available data in the stream. /// </remarks> public void ReadExactly(Span<byte> buffer) => _ = ReadAtLeastCore(buffer, buffer.Length, throwOnEndOfStream: true); /// <summary> /// Reads <paramref name="count"/> number of bytes from the current stream and advances the position within the stream. /// </summary> /// <param name="buffer"> /// An array of bytes. When this method returns, the buffer contains the specified byte array with the values /// between <paramref name="offset"/> and (<paramref name="offset"/> + <paramref name="count"/> - 1) replaced /// by the bytes read from the current stream. /// </param> /// <param name="offset">The byte offset in <paramref name="buffer"/> at which to begin storing the data read from the current stream.</param> /// <param name="count">The number of bytes to be read from the current stream.</param> /// <exception cref="ArgumentNullException"><paramref name="buffer"/> is <see langword="null"/>.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="offset"/> is outside the bounds of <paramref name="buffer"/>. /// -or- /// <paramref name="count"/> is negative. /// -or- /// The range specified by the combination of <paramref name="offset"/> and <paramref name="count"/> exceeds the /// length of <paramref name="buffer"/>. /// </exception> /// <exception cref="EndOfStreamException"> /// The end of the stream is reached before reading <paramref name="count"/> number of bytes. /// </exception> /// <remarks> /// When <paramref name="count"/> is 0 (zero), this read operation will be completed without waiting for available data in the stream. /// </remarks> public void ReadExactly(byte[] buffer, int offset, int count) { ValidateBufferArguments(buffer, offset, count); _ = ReadAtLeastCore(buffer.AsSpan(offset, count), count, throwOnEndOfStream: true); } /// <summary> /// Reads at least a minimum number of bytes from the current stream and advances the position within the stream by the number of bytes read. /// </summary> /// <param name="buffer">A region of memory. When this method returns, the contents of this region are replaced by the bytes read from the current stream.</param> /// <param name="minimumBytes">The minimum number of bytes to read into the buffer.</param> /// <param name="throwOnEndOfStream"> /// <see langword="true"/> to throw an exception if the end of the stream is reached before reading <paramref name="minimumBytes"/> of bytes; /// <see langword="false"/> to return less than <paramref name="minimumBytes"/> when the end of the stream is reached. /// The default is <see langword="true"/>. /// </param> /// <returns> /// The total number of bytes read into the buffer. This is guaranteed to be greater than or equal to <paramref name="minimumBytes"/> /// when <paramref name="throwOnEndOfStream"/> is <see langword="true"/>. This will be less than <paramref name="minimumBytes"/> when the /// end of the stream is reached and <paramref name="throwOnEndOfStream"/> is <see langword="false"/>. This can be less than the number /// of bytes allocated in the buffer if that many bytes are not currently available. /// </returns> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="minimumBytes"/> is negative, or is greater than the length of <paramref name="buffer"/>. /// </exception> /// <exception cref="EndOfStreamException"> /// <paramref name="throwOnEndOfStream"/> is <see langword="true"/> and the end of the stream is reached before reading /// <paramref name="minimumBytes"/> bytes of data. /// </exception> /// <remarks> /// When <paramref name="minimumBytes"/> is 0 (zero), this read operation will be completed without waiting for available data in the stream. /// </remarks> public int ReadAtLeast(Span<byte> buffer, int minimumBytes, bool throwOnEndOfStream = true) { ValidateReadAtLeastArguments(buffer.Length, minimumBytes); return ReadAtLeastCore(buffer, minimumBytes, throwOnEndOfStream); } // No argument checking is done here. It is up to the caller. private int ReadAtLeastCore(Span<byte> buffer, int minimumBytes, bool throwOnEndOfStream) { Debug.Assert(minimumBytes <= buffer.Length); int totalRead = 0; while (totalRead < minimumBytes) { int read = Read(buffer.Slice(totalRead)); if (read == 0) { if (throwOnEndOfStream) { ThrowHelper.ThrowEndOfFileException(); } return totalRead; } totalRead += read; } return totalRead; } public abstract void Write(byte[] buffer, int offset, int count); public virtual void Write(ReadOnlySpan<byte> buffer) { byte[] sharedBuffer = ArrayPool<byte>.Shared.Rent(buffer.Length); try { buffer.CopyTo(sharedBuffer); Write(sharedBuffer, 0, buffer.Length); } finally { ArrayPool<byte>.Shared.Return(sharedBuffer); } } public virtual void WriteByte(byte value) => Write(new byte[1] { value }, 0, 1); public static Stream Synchronized(Stream stream) { ArgumentNullException.ThrowIfNull(stream); return stream as SyncStream ?? new SyncStream(stream); } [Obsolete("Do not call or override this method.")] protected virtual void ObjectInvariant() { } /// <summary>Validates arguments provided to reading and writing methods on <see cref="Stream"/>.</summary> /// <param name="buffer">The array "buffer" argument passed to the reading or writing method.</param> /// <param name="offset">The integer "offset" argument passed to the reading or writing method.</param> /// <param name="count">The integer "count" argument passed to the reading or writing method.</param> /// <exception cref="ArgumentNullException"><paramref name="buffer"/> was null.</exception> /// <exception cref="ArgumentOutOfRangeException"> /// <paramref name="offset"/> was outside the bounds of <paramref name="buffer"/>, or /// <paramref name="count"/> was negative, or the range specified by the combination of /// <paramref name="offset"/> and <paramref name="count"/> exceed the length of <paramref name="buffer"/>. /// </exception> [MethodImpl(MethodImplOptions.AggressiveInlining)] protected static void ValidateBufferArguments(byte[] buffer, int offset, int count) { if (buffer is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.buffer); } if (offset < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.offset, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if ((uint)count > buffer.Length - offset) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.count, ExceptionResource.Argument_InvalidOffLen); } } private static void ValidateReadAtLeastArguments(int bufferLength, int minimumBytes) { if (minimumBytes < 0) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.minimumBytes, ExceptionResource.ArgumentOutOfRange_NeedNonNegNum); } if (bufferLength < minimumBytes) { ThrowHelper.ThrowArgumentOutOfRangeException(ExceptionArgument.minimumBytes, ExceptionResource.ArgumentOutOfRange_NotGreaterThanBufferLength); } } /// <summary>Validates arguments provided to the <see cref="CopyTo(Stream, int)"/> or <see cref="CopyToAsync(Stream, int, CancellationToken)"/> methods.</summary> /// <param name="destination">The <see cref="Stream"/> "destination" argument passed to the copy method.</param> /// <param name="bufferSize">The integer "bufferSize" argument passed to the copy method.</param> /// <exception cref="ArgumentNullException"><paramref name="destination"/> was null.</exception> /// <exception cref="ArgumentOutOfRangeException"><paramref name="bufferSize"/> was not a positive value.</exception> /// <exception cref="NotSupportedException"><paramref name="destination"/> does not support writing.</exception> /// <exception cref="ObjectDisposedException"><paramref name="destination"/> does not support writing or reading.</exception> protected static void ValidateCopyToArguments(Stream destination, int bufferSize) { ArgumentNullException.ThrowIfNull(destination); if (bufferSize <= 0) { throw new ArgumentOutOfRangeException(nameof(bufferSize), bufferSize, SR.ArgumentOutOfRange_NeedPosNum); } if (!destination.CanWrite) { if (destination.CanRead) { ThrowHelper.ThrowNotSupportedException_UnwritableStream(); } ThrowHelper.ThrowObjectDisposedException_StreamClosed(destination.GetType().Name); } } /// <summary>Provides a nop stream.</summary> private sealed class NullStream : Stream { internal NullStream() { } public override bool CanRead => true; public override bool CanWrite => true; public override bool CanSeek => true; public override long Length => 0; public override long Position { get => 0; set { } } public override void CopyTo(Stream destination, int bufferSize) { } public override Task CopyToAsync(Stream destination, int bufferSize, CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; protected override void Dispose(bool disposing) { // Do nothing - we don't want NullStream singleton (static) to be closable } public override void Flush() { } public override Task FlushAsync(CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) => TaskToApm.Begin(Task<int>.s_defaultResultTask, callback, state); public override int EndRead(IAsyncResult asyncResult) => TaskToApm.End<int>(asyncResult); public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) => TaskToApm.Begin(Task.CompletedTask, callback, state); public override void EndWrite(IAsyncResult asyncResult) => TaskToApm.End(asyncResult); public override int Read(byte[] buffer, int offset, int count) => 0; public override int Read(Span<byte> buffer) => 0; public override Task<int> ReadAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled<int>(cancellationToken) : Task.FromResult(0); public override ValueTask<int> ReadAsync(Memory<byte> buffer, CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? ValueTask.FromCanceled<int>(cancellationToken) : default; public override int ReadByte() => -1; public override void Write(byte[] buffer, int offset, int count) { } public override void Write(ReadOnlySpan<byte> buffer) { } public override Task WriteAsync(byte[] buffer, int offset, int count, CancellationToken cancellationToken) => cancellationToken.IsCancellationRequested ? Task.FromCanceled(cancellationToken) : Task.CompletedTask; public override ValueTask WriteAsync(ReadOnlyMemory<byte> buffer, CancellationToken cancellationToken = default) => cancellationToken.IsCancellationRequested ? ValueTask.FromCanceled(cancellationToken) : default; public override void WriteByte(byte value) { } public override long Seek(long offset, SeekOrigin origin) => 0; public override void SetLength(long length) { } } /// <summary>Provides a wrapper around a stream that takes a lock for every operation.</summary> private sealed class SyncStream : Stream, IDisposable { private readonly Stream _stream; internal SyncStream(Stream stream) => _stream = stream; public override bool CanRead => _stream.CanRead; public override bool CanWrite => _stream.CanWrite; public override bool CanSeek => _stream.CanSeek; public override bool CanTimeout => _stream.CanTimeout; public override long Length { get { lock (_stream) { return _stream.Length; } } } public override long Position { get { lock (_stream) { return _stream.Position; } } set { lock (_stream) { _stream.Position = value; } } } public override int ReadTimeout { get => _stream.ReadTimeout; set => _stream.ReadTimeout = value; } public override int WriteTimeout { get => _stream.WriteTimeout; set => _stream.WriteTimeout = value; } public override void Close() { lock (_stream) { // On the off chance that some wrapped stream has different // semantics for Close vs. Dispose, let's preserve that. try { _stream.Close(); } finally { base.Dispose(true); } } } protected override void Dispose(bool disposing) { lock (_stream) { try { // Explicitly pick up a potentially methodimpl'ed Dispose if (disposing) { ((IDisposable)_stream).Dispose(); } } finally { base.Dispose(disposing); } } } public override ValueTask DisposeAsync() { lock (_stream) { return _stream.DisposeAsync(); } } public override void Flush() { lock (_stream) { _stream.Flush(); } } public override int Read(byte[] bytes, int offset, int count) { lock (_stream) { return _stream.Read(bytes, offset, count); } } public override int Read(Span<byte> buffer) { lock (_stream) { return _stream.Read(buffer); } } public override int ReadByte() { lock (_stream) { return _stream.ReadByte(); } } public override IAsyncResult BeginRead(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) { #if NATIVEAOT throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251 #else bool overridesBeginRead = _stream.HasOverriddenBeginEndRead(); lock (_stream) { // If the Stream does have its own BeginRead implementation, then we must use that override. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic // which ensures only one asynchronous operation does so with an asynchronous wait rather // than a synchronous wait. A synchronous wait will result in a deadlock condition, because // the EndXx method for the outstanding async operation won't be able to acquire the lock on // _stream due to this call blocked while holding the lock. return overridesBeginRead ? _stream.BeginRead(buffer, offset, count, callback, state) : _stream.BeginReadInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true); } #endif } public override int EndRead(IAsyncResult asyncResult) { if (asyncResult is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult); } lock (_stream) { return _stream.EndRead(asyncResult); } } public override long Seek(long offset, SeekOrigin origin) { lock (_stream) { return _stream.Seek(offset, origin); } } public override void SetLength(long length) { lock (_stream) { _stream.SetLength(length); } } public override void Write(byte[] bytes, int offset, int count) { lock (_stream) { _stream.Write(bytes, offset, count); } } public override void Write(ReadOnlySpan<byte> buffer) { lock (_stream) { _stream.Write(buffer); } } public override void WriteByte(byte b) { lock (_stream) { _stream.WriteByte(b); } } public override IAsyncResult BeginWrite(byte[] buffer, int offset, int count, AsyncCallback? callback, object? state) { #if NATIVEAOT throw new NotImplementedException(); // TODO: https://github.com/dotnet/corert/issues/3251 #else bool overridesBeginWrite = _stream.HasOverriddenBeginEndWrite(); lock (_stream) { // If the Stream does have its own BeginWrite implementation, then we must use that override. // If it doesn't, then we'll use the base implementation, but we'll make sure that the logic // which ensures only one asynchronous operation does so with an asynchronous wait rather // than a synchronous wait. A synchronous wait will result in a deadlock condition, because // the EndXx method for the outstanding async operation won't be able to acquire the lock on // _stream due to this call blocked while holding the lock. return overridesBeginWrite ? _stream.BeginWrite(buffer, offset, count, callback, state) : _stream.BeginWriteInternal(buffer, offset, count, callback, state, serializeAsynchronously: true, apm: true); } #endif } public override void EndWrite(IAsyncResult asyncResult) { if (asyncResult is null) { ThrowHelper.ThrowArgumentNullException(ExceptionArgument.asyncResult); } lock (_stream) { _stream.EndWrite(asyncResult); } } } } }
45.094776
170
0.584192
[ "MIT" ]
ChaseKnowlden/runtime
src/libraries/System.Private.CoreLib/src/System/IO/Stream.cs
60,427
C#
using System; using System.Collections.Generic; using System.Configuration; using System.IO; using System.Reflection; using InfluxDB.Client.Api.Client; using InfluxDB.Client.Core; using InfluxDB.Client.Core.Exceptions; using NUnit.Framework; namespace InfluxDB.Client.Test { [TestFixture] public class InfluxDbClientFactoryTest { [SetUp] public void SetUp() { } [Test] public void CreateInstance() { var client = InfluxDBClientFactory.Create("http://localhost:9999"); Assert.IsNotNull(client); } [Test] public void CreateInstanceUsername() { var client = InfluxDBClientFactory.Create("http://localhost:9999", "user", "secret".ToCharArray()); Assert.IsNotNull(client); } [Test] public void CreateInstanceToken() { var client = InfluxDBClientFactory.Create("http://localhost:9999", "xyz"); Assert.IsNotNull(client); } [Test] public void LoadFromConnectionString() { var client = InfluxDBClientFactory.Create("http://localhost:9999?" + "timeout=1000&readWriteTimeout=3000&logLevel=HEADERS&token=my-token&bucket=my-bucket&org=my-org"); var options = GetDeclaredField<InfluxDBClientOptions>(client.GetType(), client, "_options"); Assert.AreEqual("http://localhost:9999/", options.Url); Assert.AreEqual("my-org", options.Org); Assert.AreEqual("my-bucket", options.Bucket); Assert.AreEqual("my-token".ToCharArray(), options.Token); Assert.AreEqual(LogLevel.Headers, options.LogLevel); Assert.AreEqual(LogLevel.Headers, client.GetLogLevel()); var apiClient = GetDeclaredField<ApiClient>(client.GetType(), client, "_apiClient"); Assert.AreEqual(1_000, apiClient.Configuration.Timeout); Assert.AreEqual(3_000, apiClient.Configuration.ReadWriteTimeout); } [Test] public void LoadFromConnectionStringUnitsMillisecondsSeconds() { var client = InfluxDBClientFactory.Create("http://localhost:9999?" + "timeout=1ms&readWriteTimeout=3s&logLevel=Headers&token=my-token&bucket=my-bucket&org=my-org"); var options = GetDeclaredField<InfluxDBClientOptions>(client.GetType(), client, "_options"); Assert.AreEqual("http://localhost:9999/", options.Url); Assert.AreEqual("my-org", options.Org); Assert.AreEqual("my-bucket", options.Bucket); Assert.AreEqual("my-token".ToCharArray(), options.Token); Assert.AreEqual(LogLevel.Headers, options.LogLevel); Assert.AreEqual(LogLevel.Headers, client.GetLogLevel()); var apiClient = GetDeclaredField<ApiClient>(client.GetType(), client, "_apiClient"); Assert.AreEqual(1, apiClient.Configuration.Timeout); Assert.AreEqual(3_000, apiClient.Configuration.ReadWriteTimeout); } [Test] public void LoadFromConnectionStringUnitsMinutes() { var client = InfluxDBClientFactory.Create("http://localhost:9999?" + "timeout=1ms&readWriteTimeout=3m&logLevel=Headers&token=my-token&bucket=my-bucket&org=my-org"); var options = GetDeclaredField<InfluxDBClientOptions>(client.GetType(), client, "_options"); Assert.AreEqual("http://localhost:9999/", options.Url); Assert.AreEqual("my-org", options.Org); Assert.AreEqual("my-bucket", options.Bucket); Assert.AreEqual("my-token".ToCharArray(), options.Token); Assert.AreEqual(LogLevel.Headers, options.LogLevel); Assert.AreEqual(LogLevel.Headers, client.GetLogLevel()); var apiClient = GetDeclaredField<ApiClient>(client.GetType(), client, "_apiClient"); Assert.AreEqual(1, apiClient.Configuration.Timeout); Assert.AreEqual(180_000, apiClient.Configuration.ReadWriteTimeout); } [Test] public void LoadFromConnectionNotValidDuration() { var ioe = Assert.Throws<InfluxException>(() => InfluxDBClientFactory.Create("http://localhost:9999?" + "timeout=x&readWriteTimeout=3m&logLevel=Headers&token=my-token&bucket=my-bucket&org=my-org")); Assert.AreEqual("'x' is not a valid duration", ioe.Message); } [Test] public void LoadFromConnectionUnknownUnit() { var ioe = Assert.Throws<InfluxException>(() => InfluxDBClientFactory.Create("http://localhost:9999?" + "timeout=1y&readWriteTimeout=3m&logLevel=Headers&token=my-token&bucket=my-bucket&org=my-org")); Assert.AreEqual("unknown unit for '1y'", ioe.Message); } [Test] public void LoadFromConfiguration() { CopyAppConfig(); var client = InfluxDBClientFactory.Create(); var options = GetDeclaredField<InfluxDBClientOptions>(client.GetType(), client, "_options"); Assert.AreEqual("http://localhost:9999", options.Url); Assert.AreEqual("my-org", options.Org); Assert.AreEqual("my-bucket", options.Bucket); Assert.AreEqual("my-token".ToCharArray(), options.Token); Assert.AreEqual(LogLevel.Body, options.LogLevel); Assert.AreEqual(LogLevel.Body, client.GetLogLevel()); var apiClient = GetDeclaredField<ApiClient>(client.GetType(), client, "_apiClient"); Assert.AreEqual(10_000, apiClient.Configuration.Timeout); Assert.AreEqual(5_000, apiClient.Configuration.ReadWriteTimeout); var defaultTags = GetDeclaredField<SortedDictionary<string, string>>(options.PointSettings.GetType(), options.PointSettings, "_defaultTags"); Assert.AreEqual(4, defaultTags.Count); Assert.AreEqual("132-987-655", defaultTags["id"]); Assert.AreEqual("California Miner", defaultTags["customer"]); Assert.AreEqual("${SensorVersion}", defaultTags["version"]); } [Test] public void LoadFromConfigurationWithoutUrl() { CopyAppConfig(); var ce = Assert.Throws<ConfigurationErrorsException>(() => InfluxDBClientOptions.Builder .CreateNew() .LoadConfig("influx2-without-url")); StringAssert.StartsWith("Required attribute 'url' not found.", ce.Message); } [Test] public void LoadFromConfigurationNotExist() { var ce = Assert.Throws<ConfigurationErrorsException>(() => InfluxDBClientOptions.Builder .CreateNew() .LoadConfig("influx2-not-exits")); StringAssert.StartsWith("The configuration doesn't contains a 'influx2'", ce.Message); } [Test] public void V1Configuration() { var client = InfluxDBClientFactory.CreateV1("http://localhost:8086", "my-username", "my-password".ToCharArray(), "database", "week"); var options = GetDeclaredField<InfluxDBClientOptions>(client.GetType(), client, "_options"); Assert.AreEqual("http://localhost:8086", options.Url); Assert.AreEqual("-", options.Org); Assert.AreEqual("database/week", options.Bucket); Assert.AreEqual("my-username:my-password".ToCharArray(), options.Token); client = InfluxDBClientFactory.CreateV1("http://localhost:8086", null, null, "database", null); options = GetDeclaredField<InfluxDBClientOptions>(client.GetType(), client, "_options"); Assert.AreEqual("http://localhost:8086", options.Url); Assert.AreEqual("-", options.Org); Assert.AreEqual("database/", options.Bucket); Assert.AreEqual(":".ToCharArray(), options.Token); } [Test] public void Timeout() { var options = new InfluxDBClientOptions.Builder() .Url("http://localhost:8086") .AuthenticateToken("my-token".ToCharArray()) .TimeOut(TimeSpan.FromSeconds(20)) .ReadWriteTimeOut(TimeSpan.FromSeconds(30)) .Build(); var client = InfluxDBClientFactory.Create(options); var apiClient = GetDeclaredField<ApiClient>(client.GetType(), client, "_apiClient"); Assert.AreEqual(20_000, apiClient.Configuration.Timeout); Assert.AreEqual(30_000, apiClient.Configuration.ReadWriteTimeout); } private static T GetDeclaredField<T>(IReflect type, object instance, string fieldName) { const BindingFlags bindFlags = BindingFlags.Instance | BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.DeclaredOnly; var field = type.GetField(fieldName, bindFlags); return (T) field?.GetValue(instance); } private static void CopyAppConfig() { // copy App.config to assemble format var config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); File.Copy(Directory.GetCurrentDirectory() + "/../../../App.config", config.FilePath, true); } } }
44.239819
183
0.603355
[ "MIT" ]
BigHam/influxdb-client-csharp
Client.Test/InfluxDbClientFactoryTest.cs
9,777
C#
//*******************************************************************************************// // // // Download Free Evaluation Version From: https://bytescout.com/download/web-installer // // // // Also available as Web API! Get Your Free API Key: https://app.pdf.co/signup // // // // Copyright © 2017-2020 ByteScout, Inc. All rights reserved. // // https://www.bytescout.com // // https://pdf.co // // // //*******************************************************************************************// using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Net; using System.Threading; // Cloud API asynchronous "PDF To PNG" job example. // Allows to avoid timeout errors when processing huge or scanned PDF documents. namespace ByteScoutWebApiExample { class Program { // The authentication key (API Key). // Get your own by registering at https://app.pdf.co const String API_KEY = "***********************************"; // Source PDF file // You can also upload your own file into PDF.co and use it as url. Check "Upload File" samples for code snippets: https://github.com/bytescout/pdf-co-api-samples/tree/master/File%20Upload/ const string SourceFileUrl = @"https://bytescout-com.s3.amazonaws.com/files/demo-files/cloud-api/pdf-to-image/sample.pdf"; // Comma-separated list of page indices (or ranges) to process. Leave empty for all pages. Example: '0,2-5,7-'. const string Pages = ""; // PDF document password. Leave empty for unprotected documents. const string Password = ""; // (!) Make asynchronous job const bool Async = true; static void Main(string[] args) { // Create standard .NET web client instance WebClient webClient = new WebClient(); // Set API Key webClient.Headers.Add("x-api-key", API_KEY); try { // URL for `PDF To PNG` API call string url = "https://api.pdf.co/v1/pdf/convert/to/png"; // Prepare requests params as JSON Dictionary<string, object> parameters = new Dictionary<string, object>(); parameters.Add("password", Password); parameters.Add("pages", Pages); parameters.Add("url", SourceFileUrl); parameters.Add("async", Async); // Convert dictionary of params to JSON string jsonPayload = JsonConvert.SerializeObject(parameters); // Execute POST request with JSON payload string response = webClient.UploadString(url, jsonPayload); // Parse JSON response JObject json = JObject.Parse(response); if (json["error"].ToObject<bool>() == false) { // Asynchronous job ID string jobId = json["jobId"].ToString(); // URL of generated JSON file available after the job completion; it will contain URLs of result PNG files. string resultJsonFileUrl = json["url"].ToString(); // Check the job status in a loop. // If you don't want to pause the main thread you can rework the code // to use a separate thread for the status checking and completion. do { string status = CheckJobStatus(jobId); // Possible statuses: "working", "failed", "aborted", "success". // Display timestamp and status (for demo purposes) Console.WriteLine(DateTime.Now.ToLongTimeString() + ": " + status); if (status == "success") { // Download JSON file as string string jsonFileString = webClient.DownloadString(resultJsonFileUrl); JArray resultFilesUrls = JArray.Parse(jsonFileString); // Download generated PNG files int page = 1; foreach (JToken token in resultFilesUrls) { string resultFileUrl = token.ToString(); string localFileName = String.Format(@".\page{0}.png", page); webClient.DownloadFile(resultFileUrl, localFileName); Console.WriteLine("Downloaded \"{0}\".", localFileName); page++; } break; } else if (status == "working") { // Pause for a few seconds Thread.Sleep(3000); } else { Console.WriteLine(status); break; } } while (true); } else { Console.WriteLine(json["message"].ToString()); } } catch (WebException e) { Console.WriteLine(e.ToString()); } webClient.Dispose(); Console.WriteLine(); Console.WriteLine("Press any key..."); Console.ReadKey(); } static string CheckJobStatus(string jobId) { using (WebClient webClient = new WebClient()) { // Set API Key webClient.Headers.Add("x-api-key", API_KEY); string url = "https://api.pdf.co/v1/job/check?jobid=" + jobId; string response = webClient.DownloadString(url); JObject json = JObject.Parse(response); return Convert.ToString(json["status"]); } } } }
34.759494
198
0.54279
[ "Apache-2.0" ]
bytescout/ByteScout-SDK-SourceCode
PDF.co Web API/PDF To PNG/C#/Convert PDF To PNG From URL Asynchronously/Program.cs
5,493
C#
// // Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. // // Microsoft Cognitive Services (formerly Project Oxford): https://www.microsoft.com/cognitive-services // // Microsoft Cognitive Services (formerly Project Oxford) GitHub: // https://github.com/Microsoft/Cognitive-WebLM-Windows // // Copyright (c) Microsoft Corporation // All rights reserved. // // MIT License: // Permission is hereby granted, free of charge, to any person obtaining // a copy of this software and associated documentation files (the // "Software"), to deal in the Software without restriction, including // without limitation the rights to use, copy, modify, merge, publish, // distribute, sublicense, and/or sell copies of the Software, and to // permit persons to whom the Software is furnished to do so, subject to // the following conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED ""AS IS"", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. // using System.Resources; using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("WebLM Client")] [assembly: AssemblyDescription("Microsoft Project Oxford Web Language Model Client")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("Microsoft Project Oxford")] [assembly: AssemblyCopyright("Copyright © 2016")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
44.061224
103
0.769338
[ "MIT" ]
Bhaskers-Blu-Org2/Cognitive-WebLM-Windows
ClientLibrary/Properties/AssemblyInfo.cs
2,162
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 Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; using System.Xml.Linq; using Xunit; namespace Microsoft.NET.HostModel.ComHost.Tests { public class RegFreeComManifestTests { private static XNamespace regFreeComManifestNamespace = "urn:schemas-microsoft-com:asm.v1"; [Fact] public void RegFreeComManifestCorrectlyIncludesComHostFile() { using TestDirectory directory = TestDirectory.Create(); JObject clsidMap = new JObject { }; string clsidmapPath = Path.Combine(directory.Path, "test.clsidmap"); string json = JsonConvert.SerializeObject(clsidMap); string comHostName = "comhost.dll"; File.WriteAllText(clsidmapPath, json); string regFreeComManifestPath = Path.Combine(directory.Path, "test.manifest"); RegFreeComManifest.CreateManifestFromClsidmap("assemblyName", comHostName, "1.0.0.0", clsidmapPath, regFreeComManifestPath); using FileStream manifestStream = File.OpenRead(regFreeComManifestPath); XElement manifest = XElement.Load(manifestStream); XElement fileElement = manifest.Element(regFreeComManifestNamespace + "file"); Assert.NotNull(fileElement); Assert.Equal(comHostName, fileElement.Attribute("name").Value); } [Fact] public void EntryInClsidMapAddedToRegFreeComManifest() { using TestDirectory directory = TestDirectory.Create(); string guid = "{190f1974-fa98-4922-8ed4-cf748630abbe}"; string assemblyName = "ComLibrary"; string typeName = "ComLibrary.Server"; string assemblyVersion = "1.0.0.0"; JObject clsidMap = new JObject { { guid, new JObject() { {"assembly", assemblyName }, {"type", typeName } } } }; string clsidmapPath = Path.Combine(directory.Path, "test.clsidmap"); string json = JsonConvert.SerializeObject(clsidMap); string comHostName = "comhost.dll"; File.WriteAllText(clsidmapPath, json); string regFreeComManifestPath = Path.Combine(directory.Path, "test.manifest"); RegFreeComManifest.CreateManifestFromClsidmap(assemblyName, comHostName, assemblyVersion, clsidmapPath, regFreeComManifestPath); using FileStream manifestStream = File.OpenRead(regFreeComManifestPath); XElement manifest = XElement.Load(manifestStream); XElement fileElement = manifest.Element(regFreeComManifestNamespace + "file"); Assert.Single(fileElement.Elements(regFreeComManifestNamespace + "comClass").Where(cls => cls.Attribute("clsid").Value == guid)); } [Fact] public void EntryInClsidMapAddedToRegFreeComManifestIncludesProgId() { using TestDirectory directory = TestDirectory.Create(); string guid = "{190f1974-fa98-4922-8ed4-cf748630abbe}"; string assemblyName = "ComLibrary"; string typeName = "ComLibrary.Server"; string progId = "CustomProgId"; string assemblyVersion = "1.0.0.0"; JObject clsidMap = new JObject { { guid, new JObject() { {"assembly", assemblyName }, {"type", typeName }, { "progid", progId } } } }; string clsidmapPath = Path.Combine(directory.Path, "test.clsidmap"); string json = JsonConvert.SerializeObject(clsidMap); string comHostName = "comhost.dll"; File.WriteAllText(clsidmapPath, json); string regFreeComManifestPath = Path.Combine(directory.Path, "test.manifest"); RegFreeComManifest.CreateManifestFromClsidmap(assemblyName, comHostName, assemblyVersion, clsidmapPath, regFreeComManifestPath); using FileStream manifestStream = File.OpenRead(regFreeComManifestPath); XElement manifest = XElement.Load(manifestStream); XElement fileElement = manifest.Element(regFreeComManifestNamespace + "file"); Assert.Single(fileElement.Elements(regFreeComManifestNamespace + "comClass").Where(cls => cls.Attribute("clsid").Value == guid && cls.Attribute("progid").Value == progId)); } } }
38.893443
184
0.642571
[ "MIT" ]
06needhamt/runtime
src/installer/tests/Microsoft.NET.HostModel.Tests/Microsoft.NET.HostModel.ComHost.Tests/RegFreeComManifestTests.cs
4,747
C#
using System.Web.Http; namespace WebArticleLibrary { public static class WebApiConfig { public static void Register(HttpConfiguration config) { // Web API configuration and services // Web API routes config.MapHttpAttributeRoutes(); config.Routes.MapHttpRoute( name: "DefaultApi", routeTemplate: "api/{controller}/{action}/{id}", defaults: new { id = RouteParameter.Optional } ); config.Filters.Add(new CustomAuthorizeAttribute()); } } }
25.791667
65
0.549273
[ "MIT" ]
Jahn08/Angular-MVC-Application
WebArticleLibrary/WebApiConfig.cs
621
C#
/* Copyright 2010-present MongoDB Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ using System.Linq.Expressions; using MongoDB.Driver.Linq.Linq3Implementation.Ast.Filters; using MongoDB.Driver.Linq.Linq3Implementation.Serializers; namespace MongoDB.Driver.Linq.Linq3Implementation.Translators.ExpressionToFilterTranslators.ToFilterFieldTranslators { internal static class ExpressionToFilterFieldTranslator { // public static methods public static AstFilterField Translate(TranslationContext context, Expression expression) { switch (expression.NodeType) { case ExpressionType.ArrayIndex: return ArrayIndexExpressionToFilterFieldTranslator.Translate(context, (BinaryExpression)expression); case ExpressionType.MemberAccess: return MemberExpressionToFilterFieldTranslator.Translate(context, (MemberExpression)expression); case ExpressionType.Call: return MethodCallExpressionToFilterFieldTranslator.Translate(context, (MethodCallExpression)expression); case ExpressionType.Parameter: return ParameterExpressionToFilterFieldTranslator.Translate(context, (ParameterExpression)expression); case ExpressionType.Convert: return ConvertExpressionToFilterFieldTranslator.Translate(context, (UnaryExpression)expression); } throw new ExpressionNotSupportedException(expression); } public static AstFilterField TranslateEnumerable(TranslationContext context, Expression expression) { var field = Translate(context, expression); if (field.Serializer is IWrappedEnumerableSerializer wrappedEnumerableSerializer) { var enumerableSerializer = IEnumerableSerializer.Create(wrappedEnumerableSerializer.EnumerableElementSerializer); field = field.SubField(wrappedEnumerableSerializer.EnumerableFieldName, enumerableSerializer); } return field; } } }
47.698113
149
0.747627
[ "Apache-2.0" ]
BorisDog/mongo-csharp-driver
src/MongoDB.Driver/Linq/Linq3Implementation/Translators/ExpressionToFilterTranslators/ToFilterFieldTranslators/ExpressionToFilterFieldTranslator.cs
2,530
C#
using System; namespace Flexinets.Radius.Core { public class DictionaryVendorAttribute : DictionaryAttribute { public readonly UInt32 VendorId; public readonly UInt32 VendorCode; /// <summary> /// Create a dictionary vendor specific attribute /// </summary> /// <param name="vendorId"></param> /// <param name="name"></param> /// <param name="vendorCode"></param> /// <param name="type"></param> public DictionaryVendorAttribute(UInt32 vendorId, String name, UInt32 vendorCode, String type) : base(name, 26, type) { VendorId = vendorId; VendorCode = vendorCode; } } }
28.48
125
0.588483
[ "MIT" ]
henriqueof/Flexinets.Radius.Core
Flexinets.Radius.Core/DictionaryVendorAttribute.cs
714
C#
using Lucene.Net.Support; using System.Diagnostics; using System.Globalization; using System.IO; using System.Text; using System.Text.RegularExpressions; namespace Lucene.Net.Analysis.Ja.Util { /* * 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. */ public class ConnectionCostsBuilder { private static readonly Regex whiteSpaceRegex = new Regex("\\s+", RegexOptions.Compiled); private ConnectionCostsBuilder() { } public static ConnectionCostsWriter Build(string filename) { using (Stream inputStream = new FileStream(filename, FileMode.Open, FileAccess.Read)) { StreamReader streamReader = new StreamReader(inputStream, Encoding.ASCII); string line = streamReader.ReadLine(); string[] dimensions = whiteSpaceRegex.Split(line).TrimEnd(); Debug.Assert(dimensions.Length == 2); int forwardSize = int.Parse(dimensions[0], CultureInfo.InvariantCulture); int backwardSize = int.Parse(dimensions[1], CultureInfo.InvariantCulture); Debug.Assert(forwardSize > 0 && backwardSize > 0); ConnectionCostsWriter costs = new ConnectionCostsWriter(forwardSize, backwardSize); while ((line = streamReader.ReadLine()) != null) { string[] fields = whiteSpaceRegex.Split(line).TrimEnd(); Debug.Assert(fields.Length == 3); int forwardId = int.Parse(fields[0], CultureInfo.InvariantCulture); int backwardId = int.Parse(fields[1], CultureInfo.InvariantCulture); int cost = int.Parse(fields[2], CultureInfo.InvariantCulture); costs.Add(forwardId, backwardId, cost); } return costs; } } } }
38.671429
99
0.634651
[ "Apache-2.0" ]
DiogenesPolanco/lucenenet
src/Lucene.Net.Analysis.Kuromoji/Tools/ConnectionCostsBuilder.cs
2,709
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801 { using Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="VnetInfo" /> /// </summary> public partial class VnetInfoTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="VnetInfo" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="VnetInfo" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Functions.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="VnetInfo" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="VnetInfo" />.</param> /// <returns> /// an instance of <see cref="VnetInfo" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IVnetInfo ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Functions.Models.Api20190801.IVnetInfo).IsAssignableFrom(type)) { return sourceValue; } try { return VnetInfo.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return VnetInfo.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return VnetInfo.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
51.102041
249
0.584531
[ "MIT" ]
Agazoth/azure-powershell
src/Functions/generated/api/Models/Api20190801/VnetInfo.TypeConverter.cs
7,366
C#
using System; using Cinematic.Common; using MongoDB.Bson.Serialization.Attributes; namespace Cinematic.DataAccess.Entities { [BsonIgnoreExtraElements] public class Seat { [BsonId] public Guid Id { get; set; } public string Row { get; set; } public string Number { get; set; } public Guid TheaterId { get; set; } public ReservationStatus Status { get; set; } public Guid UserId { get; set; } public Guid PlayId { get; set; } } }
22.16
53
0.572202
[ "MIT" ]
saraheldah/cinematic
CinematicBackend/Cinematic.DataAccess/Entities/Seat.cs
554
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Facebook; using FacebookAds.Interfaces; /// <summary> /// The MIT License (MIT) /// /// Copyright (c) 2017 - Luke Paris (Paradoxis) | Searchresult Performancemarketing /// /// 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. /// </summary> /// <date>2017-11-12 14:56:48</date> /// <author>Luke Paris (Paradoxis) | luke@paradoxis.nl</author> /// /// <remarks> /// This file was automatically generated using the Facebook Ads /// PHP SDK to C# converter found in this library under '/src/SdkConverter/' /// For more information please refer to the official documentation /// </remarks> namespace FacebookAds.Object { public class DeliveryEstimate : AbstractCrudObject { /// <summary> /// Initializes a new instance of the <see cref="DeliveryEstimate"/> class. /// </summary> /// <param name="id">The identifier.</param> /// <param name="parentId">The parent identifier.</param> /// <param name="client">The client.</param> public DeliveryEstimate(string id, string parentId = null, FacebookClient client = null) : base(id, parentId, client) { } /// <summary>Gets the endpoint of the API call.</summary> /// <returns>Endpoint URL</returns> protected override string GetEndpoint() { return ""; } } }
38.875
129
0.697749
[ "MIT" ]
AsimKhan2019/Facebook-Ads-SDK-C-
src/FacebookAds/FacebookAds/Object/DeliveryEstimate.cs
2,488
C#
namespace Blueprint.Notifications { /// <summary> /// A template that represents a single communication protocol's (e.g. SMS, SMTP) /// template, an object that belongs to a single Notification and is used /// to send communication when a notification is raised. /// </summary> public interface INotificationTemplate { } }
32.272727
85
0.684507
[ "Apache-2.0" ]
TCBroad/blueprint
src/Blueprint.Notifications/INotificationTemplate.cs
357
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.ElasticLoadBalancing { /// <summary> /// Provides a load balancer cookie stickiness policy, which allows an ELB to control the sticky session lifetime of the browser. /// /// /// /// &gt; This content is derived from https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/r/lb_cookie_stickiness_policy.html.markdown. /// </summary> public partial class LoadBalancerCookieStickinessPolicy : Pulumi.CustomResource { /// <summary> /// The time period after which /// the session cookie should be considered stale, expressed in seconds. /// </summary> [Output("cookieExpirationPeriod")] public Output<int?> CookieExpirationPeriod { get; private set; } = null!; /// <summary> /// The load balancer port to which the policy /// should be applied. This must be an active listener on the load /// balancer. /// </summary> [Output("lbPort")] public Output<int> LbPort { get; private set; } = null!; /// <summary> /// The load balancer to which the policy /// should be attached. /// </summary> [Output("loadBalancer")] public Output<string> LoadBalancer { get; private set; } = null!; /// <summary> /// The name of the stickiness policy. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Create a LoadBalancerCookieStickinessPolicy resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public LoadBalancerCookieStickinessPolicy(string name, LoadBalancerCookieStickinessPolicyArgs args, CustomResourceOptions? options = null) : base("aws:elasticloadbalancing/loadBalancerCookieStickinessPolicy:LoadBalancerCookieStickinessPolicy", name, args ?? ResourceArgs.Empty, MakeResourceOptions(options, "")) { } private LoadBalancerCookieStickinessPolicy(string name, Input<string> id, LoadBalancerCookieStickinessPolicyState? state = null, CustomResourceOptions? options = null) : base("aws:elasticloadbalancing/loadBalancerCookieStickinessPolicy:LoadBalancerCookieStickinessPolicy", name, state, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing LoadBalancerCookieStickinessPolicy resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="state">Any extra arguments used during the lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static LoadBalancerCookieStickinessPolicy Get(string name, Input<string> id, LoadBalancerCookieStickinessPolicyState? state = null, CustomResourceOptions? options = null) { return new LoadBalancerCookieStickinessPolicy(name, id, state, options); } } public sealed class LoadBalancerCookieStickinessPolicyArgs : Pulumi.ResourceArgs { /// <summary> /// The time period after which /// the session cookie should be considered stale, expressed in seconds. /// </summary> [Input("cookieExpirationPeriod")] public Input<int>? CookieExpirationPeriod { get; set; } /// <summary> /// The load balancer port to which the policy /// should be applied. This must be an active listener on the load /// balancer. /// </summary> [Input("lbPort", required: true)] public Input<int> LbPort { get; set; } = null!; /// <summary> /// The load balancer to which the policy /// should be attached. /// </summary> [Input("loadBalancer", required: true)] public Input<string> LoadBalancer { get; set; } = null!; /// <summary> /// The name of the stickiness policy. /// </summary> [Input("name")] public Input<string>? Name { get; set; } public LoadBalancerCookieStickinessPolicyArgs() { } } public sealed class LoadBalancerCookieStickinessPolicyState : Pulumi.ResourceArgs { /// <summary> /// The time period after which /// the session cookie should be considered stale, expressed in seconds. /// </summary> [Input("cookieExpirationPeriod")] public Input<int>? CookieExpirationPeriod { get; set; } /// <summary> /// The load balancer port to which the policy /// should be applied. This must be an active listener on the load /// balancer. /// </summary> [Input("lbPort")] public Input<int>? LbPort { get; set; } /// <summary> /// The load balancer to which the policy /// should be attached. /// </summary> [Input("loadBalancer")] public Input<string>? LoadBalancer { get; set; } /// <summary> /// The name of the stickiness policy. /// </summary> [Input("name")] public Input<string>? Name { get; set; } public LoadBalancerCookieStickinessPolicyState() { } } }
40.619632
185
0.624981
[ "ECL-2.0", "Apache-2.0" ]
Dominik-K/pulumi-aws
sdk/dotnet/Elasticloadbalancing/LoadBalancerCookieStickinessPolicy.cs
6,621
C#
using System; namespace ProjectV.DesktopApp.Domain { public interface IErrorHandler { void HandleError(Exception ex); } }
14.4
39
0.680556
[ "Apache-2.0" ]
Vasar007/FilmsEvaluator
ProjectV/Applications/ProjectV.DesktopApp/Domain/IErrorHandler.cs
146
C#
/** \file ReadTable.cs \author Nikitha Krithnan and W. Spencer Smith \brief Provides a function for reading glass ASTM data */ using System; using System.Collections.Generic; using System.IO; public class ReadTable { /** \brief Reads glass ASTM data from a file with the given file name \param filename name of the input file \param z_vector list of z values \param x_matrix lists of x values at different z values \param y_matrix lists of y values at different z values */ public static void read_table(string filename, List<double> z_vector, List<List<double>> x_matrix, List<List<double>> y_matrix) { StreamWriter outfile; outfile = new StreamWriter("log.txt", true); outfile.WriteLine("function read_table called with inputs: {"); outfile.Write(" filename = "); outfile.Write(filename); outfile.WriteLine(", "); outfile.Write(" z_vector = "); outfile.Write("["); for (int list_i1 = 0; list_i1 < z_vector.Count - 1; list_i1++) { outfile.Write(z_vector[list_i1]); outfile.Write(", "); } if (z_vector.Count > 0) { outfile.Write(z_vector[z_vector.Count - 1]); } outfile.Write("]"); outfile.WriteLine(", "); outfile.Write(" x_matrix = "); outfile.Write("["); for (int list_i2 = 0; list_i2 < x_matrix.Count - 1; list_i2++) { outfile.Write("["); for (int list_i1 = 0; list_i1 < x_matrix[list_i2].Count - 1; list_i1++) { outfile.Write(x_matrix[list_i2][list_i1]); outfile.Write(", "); } if (x_matrix[list_i2].Count > 0) { outfile.Write(x_matrix[list_i2][x_matrix[list_i2].Count - 1]); } outfile.Write("]"); outfile.Write(", "); } if (x_matrix.Count > 0) { outfile.Write("["); for (int list_i1 = 0; list_i1 < x_matrix[x_matrix.Count - 1].Count - 1; list_i1++) { outfile.Write(x_matrix[x_matrix.Count - 1][list_i1]); outfile.Write(", "); } if (x_matrix[x_matrix.Count - 1].Count > 0) { outfile.Write(x_matrix[x_matrix.Count - 1][x_matrix[x_matrix.Count - 1].Count - 1]); } outfile.Write("]"); } outfile.Write("]"); outfile.WriteLine(", "); outfile.Write(" y_matrix = "); outfile.Write("["); for (int list_i2 = 0; list_i2 < y_matrix.Count - 1; list_i2++) { outfile.Write("["); for (int list_i1 = 0; list_i1 < y_matrix[list_i2].Count - 1; list_i1++) { outfile.Write(y_matrix[list_i2][list_i1]); outfile.Write(", "); } if (y_matrix[list_i2].Count > 0) { outfile.Write(y_matrix[list_i2][y_matrix[list_i2].Count - 1]); } outfile.Write("]"); outfile.Write(", "); } if (y_matrix.Count > 0) { outfile.Write("["); for (int list_i1 = 0; list_i1 < y_matrix[y_matrix.Count - 1].Count - 1; list_i1++) { outfile.Write(y_matrix[y_matrix.Count - 1][list_i1]); outfile.Write(", "); } if (y_matrix[y_matrix.Count - 1].Count > 0) { outfile.Write(y_matrix[y_matrix.Count - 1][y_matrix[y_matrix.Count - 1].Count - 1]); } outfile.Write("]"); } outfile.WriteLine("]"); outfile.WriteLine(" }"); outfile.Close(); StreamReader infile; string line; List<string> linetokens = new List<string>(0); List<string> lines = new List<string>(0); infile = new StreamReader(filename); line = infile.ReadLine(); linetokens = new List<string>(line.Split(',')); for (int stringlist_i = 0; stringlist_i < linetokens.Count / 1; stringlist_i += 1) { z_vector.Add(Double.Parse(linetokens[stringlist_i * 1 + 0])); } outfile = new StreamWriter("log.txt", true); outfile.Write("var 'z_vector' assigned "); outfile.Write("["); for (int list_i1 = 0; list_i1 < z_vector.Count - 1; list_i1++) { outfile.Write(z_vector[list_i1]); outfile.Write(", "); } if (z_vector.Count > 0) { outfile.Write(z_vector[z_vector.Count - 1]); } outfile.Write("]"); outfile.WriteLine(" in module ReadTable"); outfile.Close(); while (!(infile.EndOfStream)) { lines.Add(infile.ReadLine()); } for (int i = 0; i < lines.Count; i += 1) { linetokens = new List<string>(lines[i].Split(',')); List<double> x_matrix_temp = new List<double> {}; List<double> y_matrix_temp = new List<double> {}; for (int stringlist_i = 0; stringlist_i < linetokens.Count / 2; stringlist_i += 1) { x_matrix_temp.Add(Double.Parse(linetokens[stringlist_i * 2 + 0])); y_matrix_temp.Add(Double.Parse(linetokens[stringlist_i * 2 + 1])); } x_matrix.Add(x_matrix_temp); y_matrix.Add(y_matrix_temp); } outfile = new StreamWriter("log.txt", true); outfile.Write("var 'x_matrix' assigned "); outfile.Write("["); for (int list_i2 = 0; list_i2 < x_matrix.Count - 1; list_i2++) { outfile.Write("["); for (int list_i1 = 0; list_i1 < x_matrix[list_i2].Count - 1; list_i1++) { outfile.Write(x_matrix[list_i2][list_i1]); outfile.Write(", "); } if (x_matrix[list_i2].Count > 0) { outfile.Write(x_matrix[list_i2][x_matrix[list_i2].Count - 1]); } outfile.Write("]"); outfile.Write(", "); } if (x_matrix.Count > 0) { outfile.Write("["); for (int list_i1 = 0; list_i1 < x_matrix[x_matrix.Count - 1].Count - 1; list_i1++) { outfile.Write(x_matrix[x_matrix.Count - 1][list_i1]); outfile.Write(", "); } if (x_matrix[x_matrix.Count - 1].Count > 0) { outfile.Write(x_matrix[x_matrix.Count - 1][x_matrix[x_matrix.Count - 1].Count - 1]); } outfile.Write("]"); } outfile.Write("]"); outfile.WriteLine(" in module ReadTable"); outfile.Close(); outfile = new StreamWriter("log.txt", true); outfile.Write("var 'y_matrix' assigned "); outfile.Write("["); for (int list_i2 = 0; list_i2 < y_matrix.Count - 1; list_i2++) { outfile.Write("["); for (int list_i1 = 0; list_i1 < y_matrix[list_i2].Count - 1; list_i1++) { outfile.Write(y_matrix[list_i2][list_i1]); outfile.Write(", "); } if (y_matrix[list_i2].Count > 0) { outfile.Write(y_matrix[list_i2][y_matrix[list_i2].Count - 1]); } outfile.Write("]"); outfile.Write(", "); } if (y_matrix.Count > 0) { outfile.Write("["); for (int list_i1 = 0; list_i1 < y_matrix[y_matrix.Count - 1].Count - 1; list_i1++) { outfile.Write(y_matrix[y_matrix.Count - 1][list_i1]); outfile.Write(", "); } if (y_matrix[y_matrix.Count - 1].Count > 0) { outfile.Write(y_matrix[y_matrix.Count - 1][y_matrix[y_matrix.Count - 1].Count - 1]); } outfile.Write("]"); } outfile.Write("]"); outfile.WriteLine(" in module ReadTable"); outfile.Close(); infile.Close(); } }
41.492063
133
0.521551
[ "BSD-2-Clause" ]
Ant13731/Drasil
code/stable/glassbr/src/csharp/ReadTable.cs
7,842
C#
using System; namespace Mermaid.InteractiveExtension; public class MermaidMarkdown { internal string Background { get; set; } internal string Width { get; set; } internal string Height { get; set; } public override string ToString() { return _value; } private readonly string _value; public MermaidMarkdown(string value) { Background = "white"; Width = string.Empty; Height = string.Empty; _value = value ?? throw new ArgumentNullException(nameof(value)); } }
22.666667
73
0.647059
[ "MIT" ]
JakeRadMSFT/dotnet-interactive-extension-lab
src/Mermaid.InteractiveExtension/MermaidMarkdown.cs
546
C#
using QuieroPizza.Web.Models; using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; namespace QuieroPizza.Web.Controllers { public class ProductosController : Controller { // GET: Productos public ActionResult Index() { var producto1 = new ProductoModel(); producto1.Id = 1; producto1.Descripcion = "Pizza 6 quesos"; var producto2 = new ProductoModel(); producto2.Id = 2; producto2.Descripcion = "Pizza 4 Estaciones"; var producto3 = new ProductoModel(); producto3.Id = 3; producto3.Descripcion = "Pizza Jamon y Queso"; var listadeProductos = new List<ProductoModel>(); listadeProductos.Add(producto1); listadeProductos.Add(producto2); listadeProductos.Add(producto3); return View(listadeProductos); } } }
24.243902
61
0.596579
[ "MIT" ]
kimbanegas15/quieropizza
QuieroPizza/QuieroPizza.Web/Controllers/ProductosController.cs
996
C#
using NPOI.OpenXmlFormats.Spreadsheet; using NPOI.SS; using NPOI.SS.Formula; using NPOI.SS.Formula.Eval; using NPOI.SS.Formula.PTG; using NPOI.SS.UserModel; using NPOI.SS.Util; using NPOI.Util; using NPOI.XSSF.Model; using System; using System.Globalization; namespace NPOI.XSSF.UserModel { /// High level representation of a cell in a row of a spreadsheet. /// <p> /// Cells can be numeric, formula-based or string-based (text). The cell type /// specifies this. String cells cannot conatin numbers and numeric cells cannot /// contain strings (at least according to our model). Client apps should do the /// conversions themselves. Formula cells have the formula string, as well as /// the formula result, which can be numeric or string. /// </p> /// <p> /// Cells should have their number (0 based) before being Added to a row. Only /// cells that have values should be Added. /// </p> public class XSSFCell : ICell { private static string FALSE_AS_STRING = "0"; private static string TRUE_AS_STRING = "1"; /// the xml bean Containing information about the cell's location, value, /// data type, formatting, and formula private CT_Cell _cell; /// the XSSFRow this cell belongs to private XSSFRow _row; /// 0-based column index private int _cellNum; /// Table of strings shared across this workbook. /// If two cells contain the same string, then the cell value is the same index into SharedStringsTable private SharedStringsTable _sharedStringSource; /// Table of cell styles shared across all cells in a workbook. private StylesTable _stylesSource; /// Returns the sheet this cell belongs to /// /// @return the sheet this cell belongs to public ISheet Sheet { get { return _row.Sheet; } } /// Returns the row this cell belongs to /// /// @return the row this cell belongs to public IRow Row { get { return _row; } } /// Get the value of the cell as a bool. /// <p> /// For strings, numbers, and errors, we throw an exception. For blank cells we return a false. /// </p> /// @return the value of the cell as a bool /// @throws InvalidOperationException if the cell type returned by {@link #CellType} /// is not CellType.Boolean, CellType.Blank or CellType.Formula public bool BooleanCellValue { get { CellType cellType = CellType; switch (cellType) { case CellType.Blank: return false; case CellType.Boolean: if (_cell.IsSetV()) { return TRUE_AS_STRING.Equals(_cell.v); } return false; case CellType.Formula: if (_cell.IsSetV()) { return TRUE_AS_STRING.Equals(_cell.v); } return false; default: throw TypeMismatch(CellType.Boolean, cellType, false); } } } /// Get the value of the cell as a number. /// <p> /// For strings we throw an exception. For blank cells we return a 0. /// For formulas or error cells we return the precalculated value; /// </p> /// @return the value of the cell as a number /// @throws InvalidOperationException if the cell type returned by {@link #CellType} is CellType.String /// @exception NumberFormatException if the cell value isn't a parsable <code>double</code>. /// @see DataFormatter for turning this number into a string similar to that which Excel would render this number as. public double NumericCellValue { get { CellType cellType = CellType; switch (cellType) { case CellType.Blank: return 0.0; case CellType.Numeric: case CellType.Formula: if (_cell.IsSetV()) { try { return double.Parse(_cell.v, CultureInfo.InvariantCulture); } catch (FormatException) { throw TypeMismatch(CellType.Numeric, CellType.String, false); } } return 0.0; default: throw TypeMismatch(CellType.Numeric, cellType, false); } } } /// Get the value of the cell as a string /// <p> /// For numeric cells we throw an exception. For blank cells we return an empty string. /// For formulaCells that are not string Formulas, we throw an exception /// </p> /// @return the value of the cell as a string public string StringCellValue { get { IRichTextString richStringCellValue = RichStringCellValue; if (richStringCellValue != null) { return richStringCellValue.String; } return null; } } /// Get the value of the cell as a XSSFRichTextString /// <p> /// For numeric cells we throw an exception. For blank cells we return an empty string. /// For formula cells we return the pre-calculated value if a string, otherwise an exception /// </p> /// @return the value of the cell as a XSSFRichTextString public IRichTextString RichStringCellValue { get { CellType cellType = CellType; XSSFRichTextString xSSFRichTextString; switch (cellType) { case CellType.Blank: xSSFRichTextString = new XSSFRichTextString(""); break; case CellType.String: if (_cell.t == ST_CellType.inlineStr) { xSSFRichTextString = ((!_cell.IsSetIs()) ? ((!_cell.IsSetV()) ? new XSSFRichTextString("") : new XSSFRichTextString(_cell.v)) : new XSSFRichTextString(_cell.@is)); } else if (_cell.t == ST_CellType.str) { xSSFRichTextString = new XSSFRichTextString(_cell.IsSetV() ? _cell.v : ""); } else if (_cell.IsSetV()) { int idx = int.Parse(_cell.v); xSSFRichTextString = new XSSFRichTextString(_sharedStringSource.GetEntryAt(idx)); } else { xSSFRichTextString = new XSSFRichTextString(""); } break; case CellType.Formula: CheckFormulaCachedValueType(CellType.String, GetBaseCellType(false)); xSSFRichTextString = new XSSFRichTextString(_cell.IsSetV() ? _cell.v : ""); break; default: throw TypeMismatch(CellType.String, cellType, false); } xSSFRichTextString.SetStylesTableReference(_stylesSource); return xSSFRichTextString; } } /// <summary> /// Return a formula for the cell, for example, <code>SUM(C4:E4)</code> /// </summary> public string CellFormula { get { CellType cellType = CellType; if (cellType != CellType.Formula) { throw TypeMismatch(CellType.Formula, cellType, false); } CT_CellFormula f = _cell.f; if (IsPartOfArrayFormulaGroup && f == null) { ICell firstCellInArrayFormula = ((XSSFSheet)Sheet).GetFirstCellInArrayFormula(this); return firstCellInArrayFormula.CellFormula; } if (f.t == ST_CellFormulaType.shared) { return ConvertSharedFormula((int)f.si); } return f.Value; } set { SetCellFormula(value); } } /// <summary> /// Returns zero-based column index of this cell /// </summary> public int ColumnIndex { get { return _cellNum; } } /// <summary> /// Returns zero-based row index of a row in the sheet that contains this cell /// </summary> public int RowIndex { get { return _row.RowNum; } } /// <summary> /// Return the cell's style. /// </summary> public ICellStyle CellStyle { get { XSSFCellStyle result = null; if (_stylesSource != null && _stylesSource.NumCellStyles > 0) { long num = _cell.IsSetS() ? _cell.s : 0; result = _stylesSource.GetStyleAt((int)num); } return result; } set { if (value == null) { if (_cell.IsSetS()) { _cell.unsetS(); } } else { XSSFCellStyle xSSFCellStyle = (XSSFCellStyle)value; xSSFCellStyle.VerifyBelongsToStylesSource(_stylesSource); long num = _stylesSource.PutStyle(xSSFCellStyle); _cell.s = (uint)num; } } } /// <summary> /// Return the cell type. /// </summary> public CellType CellType { get { if (_cell.f != null || ((XSSFSheet)Sheet).IsCellInArrayFormulaContext(this)) { return CellType.Formula; } return GetBaseCellType(true); } } /// <summary> /// Only valid for formula cells /// </summary> public CellType CachedFormulaResultType { get { if (_cell.f == null) { throw new InvalidOperationException("Only formula cells have cached results"); } return GetBaseCellType(false); } } /// <summary> /// Get the value of the cell as a date. /// </summary> public DateTime DateCellValue { get { CellType cellType = CellType; if (cellType == CellType.Blank) { return DateTime.MinValue; } double numericCellValue = NumericCellValue; bool use1904windowing = ((XSSFWorkbook)Sheet.Workbook).IsDate1904(); return DateUtil.GetJavaDate(numericCellValue, use1904windowing); } } /// <summary> /// Returns the error message, such as #VALUE! /// </summary> public string ErrorCellString { get { CellType baseCellType = GetBaseCellType(true); if (baseCellType != CellType.Error) { throw TypeMismatch(CellType.Error, baseCellType, false); } return _cell.v; } } /// <summary> /// Get the value of the cell as an error code. /// For strings, numbers, and bools, we throw an exception. /// For blank cells we return a 0. /// </summary> public byte ErrorCellValue { get { string errorCellString = ErrorCellString; if (errorCellString == null) { return 0; } return FormulaError.ForString(errorCellString).Code; } } /// <summary> /// Returns cell comment associated with this cell /// </summary> public IComment CellComment { get { return Sheet.GetCellComment(_row.RowNum, ColumnIndex); } set { if (value == null) { RemoveCellComment(); } else { value.Row = RowIndex; value.Column = ColumnIndex; } } } /// <summary> /// Returns hyperlink associated with this cell /// </summary> public IHyperlink Hyperlink { get { return ((XSSFSheet)Sheet).GetHyperlink(_row.RowNum, _cellNum); } set { XSSFHyperlink xSSFHyperlink = (XSSFHyperlink)value; xSSFHyperlink.SetCellReference(new CellReference(_row.RowNum, _cellNum).FormatAsString()); ((XSSFSheet)Sheet).AddHyperlink(xSSFHyperlink); } } public CellRangeAddress ArrayFormulaRange { get { XSSFCell firstCellInArrayFormula = ((XSSFSheet)Sheet).GetFirstCellInArrayFormula(this); if (firstCellInArrayFormula == null) { throw new InvalidOperationException("Cell " + GetReference() + " is not part of an array formula."); } string @ref = firstCellInArrayFormula._cell.f.@ref; return CellRangeAddress.ValueOf(@ref); } } public bool IsPartOfArrayFormulaGroup { get { return ((XSSFSheet)Sheet).IsCellInArrayFormulaContext(this); } } public bool IsMergedCell { get { return Sheet.IsMergedRegion(new CellRangeAddress(RowIndex, RowIndex, ColumnIndex, ColumnIndex)); } } /// Construct a XSSFCell. /// /// @param row the parent row. /// @param cell the xml bean Containing information about the cell. public XSSFCell(XSSFRow row, CT_Cell cell) { _cell = cell; _row = row; if (cell.r != null) { _cellNum = new CellReference(cell.r).Col; } else { int lastCellNum = row.LastCellNum; if (lastCellNum != -1) { _cellNum = row.GetCell(lastCellNum - 1).ColumnIndex + 1; } } _sharedStringSource = ((XSSFWorkbook)row.Sheet.Workbook).GetSharedStringSource(); _stylesSource = ((XSSFWorkbook)row.Sheet.Workbook).GetStylesSource(); } /// @return table of strings shared across this workbook protected SharedStringsTable GetSharedStringSource() { return _sharedStringSource; } /// @return table of cell styles shared across this workbook protected StylesTable GetStylesSource() { return _stylesSource; } /// Set a bool value for the cell /// /// @param value the bool value to Set this cell to. For formulas we'll Set the /// precalculated value, for bools we'll Set its value. For other types we /// will change the cell to a bool cell and Set its value. public void SetCellValue(bool value) { _cell.t = ST_CellType.b; _cell.v = (value ? TRUE_AS_STRING : FALSE_AS_STRING); } /// Set a numeric value for the cell /// /// @param value the numeric value to Set this cell to. For formulas we'll Set the /// precalculated value, for numerics we'll Set its value. For other types we /// will change the cell to a numeric cell and Set its value. public void SetCellValue(double value) { if (double.IsInfinity(value)) { _cell.t = ST_CellType.e; _cell.v = FormulaError.DIV0.String; } else if (double.IsNaN(value)) { _cell.t = ST_CellType.e; _cell.v = FormulaError.NUM.String; } else { _cell.t = ST_CellType.n; _cell.v = value.ToString(CultureInfo.InvariantCulture); } } private static void CheckFormulaCachedValueType(CellType expectedTypeCode, CellType cachedValueType) { if (cachedValueType != expectedTypeCode) { throw TypeMismatch(expectedTypeCode, cachedValueType, true); } } /// Set a string value for the cell. /// /// @param str value to Set the cell to. For formulas we'll Set the formula /// cached string result, for String cells we'll Set its value. For other types we will /// change the cell to a string cell and Set its value. /// If value is null then we will change the cell to a Blank cell. public void SetCellValue(string str) { SetCellValue((str == null) ? null : new XSSFRichTextString(str)); } /// Set a string value for the cell. /// /// @param str value to Set the cell to. For formulas we'll Set the 'pre-Evaluated result string, /// for String cells we'll Set its value. For other types we will /// change the cell to a string cell and Set its value. /// If value is null then we will change the cell to a Blank cell. public void SetCellValue(IRichTextString str) { if (str == null || string.IsNullOrEmpty(str.String)) { SetCellType(CellType.Blank); } else { CellType cellType = CellType; CellType cellType2 = cellType; if (cellType2 == CellType.Formula) { _cell.v = str.String; _cell.t = ST_CellType.str; } else if (_cell.t == ST_CellType.inlineStr) { _cell.v = str.String; } else { _cell.t = ST_CellType.s; XSSFRichTextString xSSFRichTextString = (XSSFRichTextString)str; xSSFRichTextString.SetStylesTableReference(_stylesSource); int num = _sharedStringSource.AddEntry(xSSFRichTextString.GetCTRst()); _cell.v = num.ToString(); } } } /// <summary> /// Creates a non shared formula from the shared formula counterpart /// </summary> /// <param name="si">Shared Group Index</param> /// <returns>non shared formula created for the given shared formula and this cell</returns> private string ConvertSharedFormula(int si) { XSSFSheet xSSFSheet = (XSSFSheet)Sheet; CT_CellFormula sharedFormula = xSSFSheet.GetSharedFormula(si); if (sharedFormula == null) { throw new InvalidOperationException("Master cell of a shared formula with sid=" + si + " was not found"); } string value = sharedFormula.Value; string @ref = sharedFormula.@ref; CellRangeAddress cellRangeAddress = CellRangeAddress.ValueOf(@ref); int sheetIndex = xSSFSheet.Workbook.GetSheetIndex(xSSFSheet); XSSFEvaluationWorkbook xSSFEvaluationWorkbook = XSSFEvaluationWorkbook.Create(xSSFSheet.Workbook); SharedFormula sharedFormula2 = new SharedFormula(SpreadsheetVersion.EXCEL2007); Ptg[] ptgs = FormulaParser.Parse(value, xSSFEvaluationWorkbook, FormulaType.Cell, sheetIndex); Ptg[] ptgs2 = sharedFormula2.ConvertSharedFormulas(ptgs, RowIndex - cellRangeAddress.FirstRow, ColumnIndex - cellRangeAddress.FirstColumn); return FormulaRenderer.ToFormulaString(xSSFEvaluationWorkbook, ptgs2); } /// Sets formula for this cell. /// <p> /// Note, this method only Sets the formula string and does not calculate the formula value. /// To Set the precalculated value use {@link #setCellValue(double)} or {@link #setCellValue(String)} /// </p> /// /// @param formula the formula to Set, e.g. <code>"SUM(C4:E4)"</code>. /// If the argument is <code>null</code> then the current formula is Removed. /// @throws NPOI.ss.formula.FormulaParseException if the formula has incorrect syntax or is otherwise invalid /// @throws InvalidOperationException if the operation is not allowed, for example, /// when the cell is a part of a multi-cell array formula public void SetCellFormula(string formula) { if (IsPartOfArrayFormulaGroup) { NotifyArrayFormulaChanging(); } SetFormula(formula, FormulaType.Cell); } internal void SetCellArrayFormula(string formula, CellRangeAddress range) { SetFormula(formula, FormulaType.Array); CT_CellFormula f = _cell.f; f.t = ST_CellFormulaType.array; f.@ref = range.FormatAsString(); } private void SetFormula(string formula, FormulaType formulaType) { IWorkbook workbook = _row.Sheet.Workbook; if (formula == null) { ((XSSFWorkbook)workbook).OnDeleteFormula(this); if (_cell.IsSetF()) { _cell.unsetF(); } } else { IFormulaParsingWorkbook workbook2 = XSSFEvaluationWorkbook.Create(workbook); FormulaParser.Parse(formula, workbook2, formulaType, workbook.GetSheetIndex(Sheet)); CT_CellFormula cT_CellFormula = new CT_CellFormula(); cT_CellFormula.Value = formula; _cell.f = cT_CellFormula; if (_cell.IsSetV()) { _cell.unsetV(); } } } /// <summary> /// Returns an A1 style reference to the location of this cell /// </summary> /// <returns>A1 style reference to the location of this cell</returns> public string GetReference() { string r = _cell.r; if (r == null) { return new CellReference(this).FormatAsString(); } return r; } /// <summary> /// Detect cell type based on the "t" attribute of the CT_Cell bean /// </summary> /// <param name="blankCells"></param> /// <returns></returns> private CellType GetBaseCellType(bool blankCells) { switch (_cell.t) { case ST_CellType.b: return CellType.Boolean; case ST_CellType.n: if (!_cell.IsSetV() && blankCells) { return CellType.Blank; } return CellType.Numeric; case ST_CellType.e: return CellType.Error; case ST_CellType.s: case ST_CellType.str: case ST_CellType.inlineStr: return CellType.String; default: throw new InvalidOperationException("Illegal cell type: " + _cell.t); } } /// <summary> /// Set a date value for the cell. Excel treats dates as numeric so you will need to format the cell as a date. /// </summary> /// <param name="value">the date value to Set this cell to. For formulas we'll set the precalculated value, /// for numerics we'll Set its value. For other types we will change the cell to a numeric cell and Set its value. </param> public void SetCellValue(DateTime value) { bool use1904windowing = ((XSSFWorkbook)Sheet.Workbook).IsDate1904(); SetCellValue(DateUtil.GetExcelDate(value, use1904windowing)); } public void SetCellErrorValue(byte errorCode) { FormulaError cellErrorValue = FormulaError.ForInt(errorCode); SetCellErrorValue(cellErrorValue); } /// <summary> /// Set a error value for the cell /// </summary> /// <param name="error">the error value to Set this cell to. /// For formulas we'll Set the precalculated value , for errors we'll set /// its value. For other types we will change the cell to an error cell and Set its value. /// </param> public void SetCellErrorValue(FormulaError error) { _cell.t = ST_CellType.e; _cell.v = error.String; } /// <summary> /// Sets this cell as the active cell for the worksheet. /// </summary> public void SetAsActiveCell() { ((XSSFSheet)Sheet).SetActiveCell(GetReference()); } /// <summary> /// Blanks this cell. Blank cells have no formula or value but may have styling. /// This method erases all the data previously associated with this cell. /// </summary> private void SetBlank() { CT_Cell cT_Cell = new CT_Cell(); cT_Cell.r = _cell.r; if (_cell.IsSetS()) { cT_Cell.s = _cell.s; } _cell.Set(cT_Cell); } /// <summary> /// Sets column index of this cell /// </summary> /// <param name="num"></param> internal void SetCellNum(int num) { CheckBounds(num); _cellNum = num; string r = new CellReference(RowIndex, ColumnIndex).FormatAsString(); _cell.r = r; } /// <summary> /// Set the cells type (numeric, formula or string) /// </summary> /// <param name="cellType"></param> public void SetCellType(CellType cellType) { CellType cellType2 = CellType; if (IsPartOfArrayFormulaGroup) { NotifyArrayFormulaChanging(); } if (cellType2 == CellType.Formula && cellType != CellType.Formula) { ((XSSFWorkbook)Sheet.Workbook).OnDeleteFormula(this); } switch (cellType) { case CellType.Blank: SetBlank(); break; case CellType.Boolean: { string v = ConvertCellValueToBoolean() ? TRUE_AS_STRING : FALSE_AS_STRING; _cell.t = ST_CellType.b; _cell.v = v; break; } case CellType.Numeric: _cell.t = ST_CellType.n; break; case CellType.Error: _cell.t = ST_CellType.e; break; case CellType.String: if (cellType2 != CellType.String) { string str = ConvertCellValueToString(); XSSFRichTextString xSSFRichTextString = new XSSFRichTextString(str); xSSFRichTextString.SetStylesTableReference(_stylesSource); int num = _sharedStringSource.AddEntry(xSSFRichTextString.GetCTRst()); _cell.v = num.ToString(); } _cell.t = ST_CellType.s; break; case CellType.Formula: if (!_cell.IsSetF()) { CT_CellFormula cT_CellFormula = new CT_CellFormula(); cT_CellFormula.Value = "0"; _cell.f = cT_CellFormula; if (_cell.IsSetT()) { _cell.unsetT(); } } break; default: throw new ArgumentException("Illegal cell type: " + cellType); } if (cellType != CellType.Formula && _cell.IsSetF()) { _cell.unsetF(); } } /// <summary> /// Returns a string representation of the cell /// </summary> /// <returns>Formula cells return the formula string, rather than the formula result. /// Dates are displayed in dd-MMM-yyyy format /// Errors are displayed as #ERR&lt;errIdx&gt; /// </returns> public override string ToString() { switch (CellType) { case CellType.Blank: return ""; case CellType.Boolean: if (!BooleanCellValue) { return "FALSE"; } return "TRUE"; case CellType.Error: return ErrorEval.GetText(ErrorCellValue); case CellType.Formula: return CellFormula; case CellType.Numeric: if (DateUtil.IsCellDateFormatted(this)) { FormatBase formatBase = new SimpleDateFormat("dd-MMM-yyyy"); return formatBase.Format(DateCellValue, CultureInfo.CurrentCulture); } return string.Concat(NumericCellValue); case CellType.String: return RichStringCellValue.ToString(); default: return "Unknown Cell Type: " + CellType; } } /// Returns the raw, underlying ooxml value for the cell /// <p> /// If the cell Contains a string, then this value is an index into /// the shared string table, pointing to the actual string value. Otherwise, /// the value of the cell is expressed directly in this element. Cells Containing formulas express /// the last calculated result of the formula in this element. /// </p> /// /// @return the raw cell value as Contained in the underlying CT_Cell bean, /// <code>null</code> for blank cells. public string GetRawValue() { return _cell.v; } /// <summary> /// Used to help format error messages /// </summary> /// <param name="cellTypeCode"></param> /// <returns></returns> private static string GetCellTypeName(CellType cellTypeCode) { switch (cellTypeCode) { case CellType.Blank: return "blank"; case CellType.String: return "text"; case CellType.Boolean: return "bool"; case CellType.Error: return "error"; case CellType.Numeric: return "numeric"; case CellType.Formula: return "formula"; default: return "#unknown cell type (" + cellTypeCode + ")#"; } } /// Used to help format error messages private static Exception TypeMismatch(CellType expectedTypeCode, CellType actualTypeCode, bool IsFormulaCell) { string message = "Cannot get a " + GetCellTypeName(expectedTypeCode) + " value from a " + GetCellTypeName(actualTypeCode) + " " + (IsFormulaCell ? "formula " : "") + "cell"; return new InvalidOperationException(message); } /// @throws RuntimeException if the bounds are exceeded. private static void CheckBounds(int cellIndex) { SpreadsheetVersion eXCEL = SpreadsheetVersion.EXCEL2007; int lastColumnIndex = SpreadsheetVersion.EXCEL2007.LastColumnIndex; if (cellIndex < 0 || cellIndex > lastColumnIndex) { throw new ArgumentException("Invalid column index (" + cellIndex + "). Allowable column range for " + eXCEL.ToString() + " is (0.." + lastColumnIndex + ") or ('A'..'" + eXCEL.LastColumnName + "')"); } } /// <summary> /// Removes the comment for this cell, if there is one. /// </summary> public void RemoveCellComment() { IComment cellComment = CellComment; if (cellComment != null) { string reference = GetReference(); XSSFSheet xSSFSheet = (XSSFSheet)Sheet; xSSFSheet.GetCommentsTable(false).RemoveComment(reference); xSSFSheet.GetVMLDrawing(false).RemoveCommentShape(RowIndex, ColumnIndex); } } /// Returns the xml bean containing information about the cell's location (reference), value, /// data type, formatting, and formula /// /// @return the xml bean containing information about this cell internal CT_Cell GetCTCell() { return _cell; } /// Chooses a new bool value for the cell when its type is changing.<p /> /// /// Usually the caller is calling SetCellType() with the intention of calling /// SetCellValue(bool) straight afterwards. This method only exists to give /// the cell a somewhat reasonable value until the SetCellValue() call (if at all). /// TODO - perhaps a method like SetCellTypeAndValue(int, Object) should be introduced to avoid this private bool ConvertCellValueToBoolean() { CellType cellType = CellType; if (cellType == CellType.Formula) { cellType = GetBaseCellType(false); } switch (cellType) { case CellType.Boolean: return TRUE_AS_STRING.Equals(_cell.v); case CellType.String: { int idx = int.Parse(_cell.v); XSSFRichTextString xSSFRichTextString = new XSSFRichTextString(_sharedStringSource.GetEntryAt(idx)); string @string = xSSFRichTextString.String; return bool.Parse(@string); } case CellType.Numeric: return double.Parse(_cell.v, CultureInfo.InvariantCulture) != 0.0; case CellType.Blank: case CellType.Error: return false; default: throw new RuntimeException("Unexpected cell type (" + cellType + ")"); } } private string ConvertCellValueToString() { CellType cellType = CellType; switch (cellType) { case CellType.Blank: return ""; case CellType.Boolean: if (!TRUE_AS_STRING.Equals(_cell.v)) { return "FALSE"; } return "TRUE"; case CellType.String: { int idx = int.Parse(_cell.v); XSSFRichTextString xSSFRichTextString = new XSSFRichTextString(_sharedStringSource.GetEntryAt(idx)); return xSSFRichTextString.String; } case CellType.Numeric: case CellType.Error: return _cell.v; default: throw new InvalidOperationException("Unexpected cell type (" + cellType + ")"); case CellType.Formula: { cellType = GetBaseCellType(false); string v = _cell.v; switch (cellType) { case CellType.Boolean: if (TRUE_AS_STRING.Equals(v)) { return "TRUE"; } if (FALSE_AS_STRING.Equals(v)) { return "FALSE"; } throw new InvalidOperationException("Unexpected bool cached formula value '" + v + "'."); case CellType.Numeric: case CellType.String: case CellType.Error: return v; default: throw new InvalidOperationException("Unexpected formula result type (" + cellType + ")"); } } } } /// The purpose of this method is to validate the cell state prior to modification /// /// @see #NotifyArrayFormulaChanging() internal void NotifyArrayFormulaChanging(string msg) { if (IsPartOfArrayFormulaGroup) { CellRangeAddress arrayFormulaRange = ArrayFormulaRange; if (arrayFormulaRange.NumberOfCells > 1) { throw new InvalidOperationException(msg); } Row.Sheet.RemoveArrayFormula(this); } } /// <summary> /// Called when this cell is modified.The purpose of this method is to validate the cell state prior to modification. /// </summary> /// <exception cref="T:System.InvalidOperationException">if modification is not allowed</exception> internal void NotifyArrayFormulaChanging() { CellReference cellReference = new CellReference(this); string msg = "Cell " + cellReference.FormatAsString() + " is part of a multi-cell array formula. You cannot change part of an array."; NotifyArrayFormulaChanging(msg); } public ICell CopyCellTo(int targetIndex) { return CellUtil.CopyCell(Row, ColumnIndex, targetIndex); } } }
27.990584
203
0.66975
[ "MIT" ]
iNeverSleeeeep/NPOI-For-Unity
NPOI.XSSF.UserModel/XSSFCell.cs
29,726
C#
namespace Microsoft.Protocols.TestSuites.MS_ASAIRS { using System.Collections.Generic; using Microsoft.Protocols.TestSuites.Common; using Microsoft.Protocols.TestTools; using Microsoft.VisualStudio.TestTools.UnitTesting; using DataStructures = Microsoft.Protocols.TestSuites.Common.DataStructures; using Request = Microsoft.Protocols.TestSuites.Common.Request; /// <summary> /// This scenario is designed to test the Location element and its sub elements, which is used by the Sync command, Search command and ItemOperations command. /// </summary> [TestClass] public class S05_Location : TestSuiteBase { #region Class initialize and clean up /// <summary> /// Initialize the class. /// </summary> /// <param name="testContext">VSTS test context.</param> [ClassInitialize] public static void ClassInitialize(TestContext testContext) { TestClassBase.Initialize(testContext); } /// <summary> /// Clear the class. /// </summary> [ClassCleanup] public static void ClassCleanUp() { TestClassBase.Cleanup(); } #endregion #region MSASAIRS_S05_TC01_Location /// <summary> /// This case is designed to test element Location and its sub elements. /// </summary> [TestCategory("MSASAIRS"), TestMethod()] public void MSASAIRS_S05_TC01_Location() { Site.Assume.AreNotEqual<string>("12.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Location element is supported when the MS-ASProtocolVersion header is set to 16.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.0", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Location element is supported when the MS-ASProtocolVersion header is set to 16.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); Site.Assume.AreNotEqual<string>("14.1", Common.GetConfigurationPropertyValue("ActiveSyncProtocolVersion", this.Site), "The Location element is supported when the MS-ASProtocolVersion header is set to 16.0. MS-ASProtocolVersion header value is determined using Common PTFConfig property named ActiveSyncProtocolVersion."); #region Call Sync command with Add element to add an appointment to the server Request.SyncCollectionAddApplicationData applicationData = new Request.SyncCollectionAddApplicationData(); List<object> items = new List<object>(); List<Request.ItemsChoiceType8> itemsElementName = new List<Request.ItemsChoiceType8>(); string subject = Common.GenerateResourceName(Site, "Subject"); items.Add(subject); itemsElementName.Add(Request.ItemsChoiceType8.Subject); // MeetingStauts is set to 0, which means it is an appointment with no attendees. byte meetingStatus = 0; items.Add(meetingStatus); itemsElementName.Add(Request.ItemsChoiceType8.MeetingStatus); Request.Location location = new Request.Location(); location.Accuracy = (double)1; location.AccuracySpecified = true; location.Altitude = (double)55.46; location.AltitudeAccuracy = (double)1; location.AltitudeAccuracySpecified = true; location.AltitudeSpecified = true; location.Annotation = "Location sample annotation"; location.City = "Location sample city"; location.Country = "Location sample country"; location.DisplayName = "Location sample dislay name"; location.Latitude = (double)11.56; location.LatitudeSpecified = true; location.LocationUri = "Location Uri"; location.Longitude = (double)1.9; location.LongitudeSpecified = true; location.PostalCode = "Location sample postal code"; location.State = "Location sample state"; location.Street = "Location sample street"; items.Add(location); itemsElementName.Add(Request.ItemsChoiceType8.Location); applicationData.Items = items.ToArray(); applicationData.ItemsElementName = itemsElementName.ToArray(); SyncRequest syncAddRequest = TestSuiteHelper.CreateSyncAddRequest(this.GetInitialSyncKey(this.User1Information.CalendarCollectionId), this.User1Information.CalendarCollectionId, applicationData); DataStructures.SyncStore syncAddResponse = this.ASAIRSAdapter.Sync(syncAddRequest); Site.Assert.IsTrue(syncAddResponse.AddResponses[0].Status.Equals("1"), "The sync add operation should be success; It is:{0} actually", syncAddResponse.AddResponses[0].Status); // Add the appointment to clean up list. this.RecordCaseRelativeItems(this.User1Information.UserName, this.User1Information.CalendarCollectionId, subject); #endregion #region Call Sync command to get the new added calendar item. DataStructures.Sync syncItem = this.GetSyncResult(subject, this.User1Information.CalendarCollectionId, null, null, null); #endregion #region Call ItemOperations command to reterive the added calendar item. this.GetItemOperationsResult(this.User1Information.CalendarCollectionId, syncItem.ServerId, null, null, null, null); #endregion #region Call Sync command to remove the location of the added calender item. // Create empty change items list. List<object> changeItems = new List<object>(); List<Request.ItemsChoiceType7> changeItemsElementName = new List<Request.ItemsChoiceType7>(); // Create an empty location. location = new Request.Location(); // Add the location field name into the change items element name list. changeItemsElementName.Add(Request.ItemsChoiceType7.Location); // Add the empty location value to the change items value list. changeItems.Add(location); // Create sync collection change. Request.SyncCollectionChange collectionChange = new Request.SyncCollectionChange { ServerId = syncItem.ServerId, ApplicationData = new Request.SyncCollectionChangeApplicationData { ItemsElementName = changeItemsElementName.ToArray(), Items = changeItems.ToArray() } }; // Create change sync collection Request.SyncCollection collection = new Request.SyncCollection { SyncKey = this.SyncKey, CollectionId = this.User1Information.CalendarCollectionId, Commands = new object[] { collectionChange } }; // Create change sync request. SyncRequest syncChangeRequest = Common.CreateSyncRequest(new Request.SyncCollection[] { collection }); // Change the location of the added calender by Sync request. DataStructures.SyncStore syncChangeResponse = this.ASAIRSAdapter.Sync(syncChangeRequest); Site.Assert.IsTrue(syncChangeResponse.CollectionStatus.Equals(1), "The sync change operation should be success; It is:{0} actually", syncChangeResponse.CollectionStatus); #region Call Sync command to get the new changed calendar item that removed the location. syncItem = this.GetSyncResult(subject, this.User1Information.CalendarCollectionId, null, null, null); #endregion #region Call ItemOperations command to reterive the changed calendar item that removed the location. DataStructures.ItemOperations itemOperations = this.GetItemOperationsResult(this.User1Information.CalendarCollectionId, syncItem.ServerId, null, null, null, null); #endregion // Add the debug information Site.Log.Add(LogEntryKind.Debug, "Verify MS-ASAIRS_R1001013"); // Verify MS-ASAIRS requirement: MS-ASAIRS_R1001013 Site.CaptureRequirementIfIsNull( itemOperations.Calendar.Location1.DisplayName, 1001013, @"[In Location] The client's request can include an empty Location element to remove the location from an item."); #endregion if (Common.IsRequirementEnabled(53, this.Site)) { #region Call Search command to search the added calendar item. this.GetSearchResult(subject, this.User1Information.CalendarCollectionId, null, null, null); #endregion } } #endregion } }
53.094118
333
0.670064
[ "MIT" ]
ChangDu2021/Interop-TestSuites
ExchangeActiveSync/Source/MS-ASAIRS/TestSuite/S05_Location.cs
9,028
C#
namespace SIS.Framework.Routers { using ActionResults.Contracts; using Attributes; using Attributes.Methods; using Controllers; using HTTP.Enums; using HTTP.Extensions; using HTTP.Headers; using HTTP.Requests.Contracts; using HTTP.Responses; using HTTP.Responses.Contracts; using Services; using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.IO; using System.Linq; using System.Reflection; using System.Text; using WebServer.Api; using WebServer.Results; public class ControllerRouter : IHttpHandler { private readonly IDependencyContainer dependencyContainer; public ControllerRouter(IDependencyContainer dependencyContainer) { this.dependencyContainer = dependencyContainer; } public IHttpResponse Handle(IHttpRequest request) { var response = this.TryHandleResourceRequest(request); if (response != null) { return response; } var controllerName = string.Empty; var actionName = string.Empty; var requestMethod = request.RequestMethod.ToString(); if (request.Url == "/") { controllerName = MvcContext.Get.DefaulControllerName; actionName = MvcContext.Get.DefaultActionName; } else { var requestUrlSplit = request.Path.Split( new [] {"/"}, StringSplitOptions.RemoveEmptyEntries); controllerName = requestUrlSplit[0].Capitalize(); actionName = requestUrlSplit[1].Capitalize(); } var controller = this.GetController(controllerName); controller.Request = request; var action = this.GetAction(requestMethod, controller, actionName); if (action is null) { return new HttpResponse(HttpResponseStatusCode.NotFound); } return this.PrepareResponse(controller, action); } private IHttpResponse PrepareResponse(Controller controller, MethodInfo action) { var response = new HttpResponse(); controller.Response = response; var actionParameters = this.MapActionParameters(action, controller); IActionResult actionResult = (IActionResult)action.Invoke(controller, actionParameters); string invocationResult = actionResult.Invoke(); if (actionResult is IViewable) { response.Headers.Add(new HttpHeader(HttpHeader.ContentType, "text/html")); response.Content = Encoding.UTF8.GetBytes(invocationResult); response.StatusCode = HttpResponseStatusCode.Ok; return response; } if (actionResult is IRedirectable) { response.StatusCode = HttpResponseStatusCode.SeeOther; response.Headers.Add(new HttpHeader(HttpHeader.Location, invocationResult)); return response; } throw new InvalidOperationException("The view result is not supported."); } private object[] MapActionParameters(MethodInfo action, Controller controller) { ParameterInfo[] actionParametersInfo = action.GetParameters(); object[] mappedActionParameters = new object[actionParametersInfo.Length]; for (int i = 0; i < mappedActionParameters.Length; i++) { ParameterInfo currentParameterInfo = actionParametersInfo[i]; if (currentParameterInfo.ParameterType.IsPrimitive || currentParameterInfo.ParameterType == typeof(string)) { mappedActionParameters[i] = ProcessPrimitiveParameter(currentParameterInfo, controller.Request); } else { object bindingModel = ProcessBindingModelParameters(currentParameterInfo, controller.Request); controller.ModelState.IsValid = this.IsValidModel(bindingModel, currentParameterInfo.ParameterType); mappedActionParameters[i] = bindingModel; } } return mappedActionParameters; } private bool? IsValidModel(object bindingModel, Type bindingModelType) { var properties = bindingModelType.GetProperties(); foreach (var property in properties) { var propertyValidationAttributes = property .GetCustomAttributes() .Where(a => a is ValidationAttribute) .Cast<ValidationAttribute>() .ToList(); foreach (var validationAttribute in propertyValidationAttributes) { var propertyValue = property.GetValue(bindingModel); if (!validationAttribute.IsValid(propertyValue)) { return false; } } } return true; } private object ProcessBindingModelParameters(ParameterInfo parameter, IHttpRequest request) { Type bindingModelType = parameter.ParameterType; var bindingModelInstance = Activator.CreateInstance(bindingModelType); var bindingModelProperties = bindingModelType.GetProperties(); foreach (var property in bindingModelProperties) { try { object value = this.GetParameterFromRequestData(request, property.Name.ToCamelCase()); property.SetValue(bindingModelInstance, Convert.ChangeType(value, property.PropertyType)); } catch { Console.WriteLine($"The {property.Name} field could not be mapped."); } } return Convert.ChangeType(bindingModelInstance, bindingModelType); } private object ProcessPrimitiveParameter(ParameterInfo parameter, IHttpRequest request) { object value = this.GetParameterFromRequestData(request, parameter.Name.ToCamelCase()); return Convert.ChangeType(value, parameter.ParameterType); } private object GetParameterFromRequestData(IHttpRequest request, string parameterName) { if (request.QueryData.ContainsKey(parameterName)) { return request.QueryData[parameterName]; } if (request.FormData.ContainsKey(parameterName)) { return request.FormData[parameterName]; } return null; } private IHttpResponse TryHandleResourceRequest(IHttpRequest request) { var requestPath = request.Path; if (requestPath.Contains(".")) { var filePath = $"{MvcContext.Get.RootDirectoryRelativePath}Resources{requestPath}"; if (!File.Exists(filePath)) { return new HttpResponse(HttpResponseStatusCode.NotFound); } var fileContent = File.ReadAllBytes(filePath); return new InlineResourceResult(fileContent); } return null; } private MethodInfo GetAction( string requestMethod, Controller controller, string actionName) { var actions = this .GetSuitableMethods(controller, actionName) .ToList(); if (!actions.Any()) { return null; } foreach (var action in actions) { var httpMethodAttributes = action .GetCustomAttributes() .Where(ca => ca is HttpMethodAttribute) .Cast<HttpMethodAttribute>() .ToList(); if (!httpMethodAttributes.Any() && requestMethod.ToUpper() == HttpRequestMethod.Get.ToString().ToUpper()) { return action; } foreach (var httpMethodAttribute in httpMethodAttributes) { if (httpMethodAttribute.IsValid(requestMethod)) { return action; } } } return null; } private IEnumerable<MethodInfo> GetSuitableMethods( Controller controller, string actionName) { if (controller is null) { return new MethodInfo[0]; } var routeMethods = controller .GetType() .GetMethods() .Where(mi => mi.GetCustomAttributes() .Where(ca => ca is RouteAttribute) .Cast<RouteAttribute>() .Any(a => a.Path == $"/{actionName.ToLower()}")); return controller .GetType() .GetMethods() .Where(mi => mi.Name.ToLower() == actionName.ToLower()) .Union(routeMethods); } private Controller GetController(string controllerName) { if (string.IsNullOrWhiteSpace(controllerName)) { return null; } var fullyQualifiedControllerName = string.Format("{0}.{1}.{2}{3}, {0}", MvcContext.Get.AssemblyName, MvcContext.Get.ControllersFolder, controllerName, MvcContext.Get.ControllerSuffix); var controllerType = Type.GetType(fullyQualifiedControllerName); if (controllerType is null) { return null; } var controller = (Controller)this.dependencyContainer.CreateInstance(controllerType); return controller; } } }
34.428571
120
0.552157
[ "MIT" ]
PeterAsenov22/C-Web-Course
WebFundamentals/SIS-HttpServer/SIS/SIS.Framework/Routers/ControllerRouter.cs
10,365
C#
// MIT License // // Copyright (c) 2017 Maarten van Sambeek. // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in all // copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE // SOFTWARE. namespace ConnectQl.Results { using System.Collections.Generic; using System.Linq; using ConnectQl.AsyncEnumerables; using ConnectQl.Interfaces; using ConnectQl.Internal; using JetBrains.Annotations; /// <summary> /// The execute result. /// </summary> internal class ExecuteResult : IExecuteResult { /// <summary> /// Initializes a new instance of the <see cref="ExecuteResult" /> class. /// </summary> /// <param name="affectedRecords"> /// The affected records. /// </param> /// <param name="rows"> /// The rows. /// </param> public ExecuteResult(long affectedRecords, IAsyncEnumerable<Row> rows) { this.QueryResults = new[] { new QueryResult(affectedRecords, rows), }; this.Jobs = new Job[0]; } /// <summary> /// Initializes a new instance of the <see cref="ExecuteResult" /> class. /// </summary> public ExecuteResult() { this.QueryResults = new QueryResult[0]; this.Jobs = new Job[0]; } /// <summary> /// Initializes a new instance of the <see cref="ExecuteResult" /> class. /// </summary> /// <param name="job"> /// The job. /// </param> public ExecuteResult(IJob job) { this.QueryResults = new QueryResult[0]; this.Jobs = new[] { job, }; } /// <summary> /// Initializes a new instance of the <see cref="ExecuteResult" /> class. /// </summary> /// <param name="combinedResults"> /// The combined results. /// </param> internal ExecuteResult(IEnumerable<IExecuteResult> combinedResults) : this(combinedResults, null) { } /// <summary> /// Initializes a new instance of the <see cref="ExecuteResult" /> class. /// </summary> /// <param name="combinedResults"> /// The combined Results. /// </param> /// <param name="messages"> /// The messages. /// </param> internal ExecuteResult([NotNull] IEnumerable<IExecuteResult> combinedResults, [CanBeNull] MessageWriter messages) { combinedResults = combinedResults.ToArray(); this.QueryResults = combinedResults.SelectMany(c => c.QueryResults).ToArray(); this.Jobs = combinedResults.SelectMany(c => c.Jobs).ToArray(); this.Warnings = messages?.Where(msg => msg.Type == ResultMessageType.Warning).ToArray() ?? new Message[0]; } /// <summary> /// Gets the jobs. /// </summary> public IReadOnlyList<IJob> Jobs { get; } /// <summary> /// Gets the query results. /// </summary> public IReadOnlyList<IQueryResult> QueryResults { get; } /// <summary> /// Gets or sets the warnings. /// </summary> public IReadOnlyList<IMessage> Warnings { get; set; } } }
35.704
121
0.569572
[ "MIT" ]
MaartenX/ConnectQL
src/ConnectQl/Results/ExecuteResult.cs
4,463
C#
#region License // Copyright (c) 2007 James Newton-King // // 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.IO; using System.Runtime.Serialization; #if !NETFX_CORE using NUnit.Framework; #else using Microsoft.VisualStudio.TestPlatform.UnitTestFramework; using TestFixture = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestClassAttribute; using Test = Microsoft.VisualStudio.TestPlatform.UnitTestFramework.TestMethodAttribute; #endif #if NET20 using Newtonsoft.Json.Utilities.LinqBridge; #else using System.Linq; #endif using Newtonsoft.Json.Serialization; using Newtonsoft.Json.Tests.TestObjects; using System.Reflection; using Newtonsoft.Json.Utilities; using System.Globalization; namespace Newtonsoft.Json.Tests.Serialization { public class DynamicContractResolver : DefaultContractResolver { private readonly char _startingWithChar; public DynamicContractResolver(char startingWithChar) : base(false) { _startingWithChar = startingWithChar; } protected override IList<JsonProperty> CreateProperties(Type type, MemberSerialization memberSerialization) { IList<JsonProperty> properties = base.CreateProperties(type, memberSerialization); // only serializer properties that start with the specified character properties = properties.Where(p => p.PropertyName.StartsWith(_startingWithChar.ToString())).ToList(); return properties; } } public class EscapedPropertiesContractResolver : DefaultContractResolver { protected internal override string ResolvePropertyName(string propertyName) { return base.ResolvePropertyName(propertyName + @"-'-""-"); } } public class Book { public string BookName { get; set; } public decimal BookPrice { get; set; } public string AuthorName { get; set; } public int AuthorAge { get; set; } public string AuthorCountry { get; set; } } public class IPersonContractResolver : DefaultContractResolver { protected override JsonContract CreateContract(Type objectType) { if (objectType == typeof(Employee)) objectType = typeof(IPerson); return base.CreateContract(objectType); } } public class AddressWithDataMember { #if !NET20 [DataMember(Name = "CustomerAddress1")] #endif public string AddressLine1 { get; set; } } [TestFixture] public class ContractResolverTests : TestFixtureBase { [Test] public void SerializeWithEscapedPropertyName() { string json = JsonConvert.SerializeObject( new AddressWithDataMember { AddressLine1 = "value!" }, new JsonSerializerSettings { ContractResolver = new EscapedPropertiesContractResolver() }); Assert.AreEqual(@"{""AddressLine1-'-\""-"":""value!""}", json); JsonTextReader reader = new JsonTextReader(new StringReader(json)); reader.Read(); reader.Read(); Assert.AreEqual(@"AddressLine1-'-""-", reader.Value); } #if !NET20 [Test] public void DeserializeDataMemberClassWithNoDataContract() { var resolver = new DefaultContractResolver(); var contract = (JsonObjectContract)resolver.ResolveContract(typeof(AddressWithDataMember)); Assert.AreEqual("AddressLine1", contract.Properties[0].PropertyName); } #endif [Test] public void ResolveProperties_IgnoreStatic() { var resolver = new DefaultContractResolver(); var contract = (JsonObjectContract)resolver.ResolveContract(typeof(NumberFormatInfo)); Assert.IsFalse(contract.Properties.Any(c => c.PropertyName == "InvariantInfo")); } [Test] public void SerializeInterface() { Employee employee = new Employee { BirthDate = new DateTime(1977, 12, 30, 1, 1, 1, DateTimeKind.Utc), FirstName = "Maurice", LastName = "Moss", Department = "IT", JobTitle = "Support" }; string iPersonJson = JsonConvert.SerializeObject(employee, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new IPersonContractResolver() }); Assert.AreEqual(@"{ ""FirstName"": ""Maurice"", ""LastName"": ""Moss"", ""BirthDate"": ""1977-12-30T01:01:01Z"" }", iPersonJson); } [Test] public void SingleTypeWithMultipleContractResolvers() { Book book = new Book { BookName = "The Gathering Storm", BookPrice = 16.19m, AuthorName = "Brandon Sanderson", AuthorAge = 34, AuthorCountry = "United States of America" }; string startingWithA = JsonConvert.SerializeObject(book, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('A') }); // { // "AuthorName": "Brandon Sanderson", // "AuthorAge": 34, // "AuthorCountry": "United States of America" // } string startingWithB = JsonConvert.SerializeObject(book, Formatting.Indented, new JsonSerializerSettings { ContractResolver = new DynamicContractResolver('B') }); // { // "BookName": "The Gathering Storm", // "BookPrice": 16.19 // } Assert.AreEqual(@"{ ""AuthorName"": ""Brandon Sanderson"", ""AuthorAge"": 34, ""AuthorCountry"": ""United States of America"" }", startingWithA); Assert.AreEqual(@"{ ""BookName"": ""The Gathering Storm"", ""BookPrice"": 16.19 }", startingWithB); } #if !(NETFX_CORE || PORTABLE || PORTABLE40) [Test] public void SerializeCompilerGeneratedMembers() { StructTest structTest = new StructTest { IntField = 1, IntProperty = 2, StringField = "Field", StringProperty = "Property" }; DefaultContractResolver skipCompilerGeneratedResolver = new DefaultContractResolver { DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public }; string skipCompilerGeneratedJson = JsonConvert.SerializeObject(structTest, Formatting.Indented, new JsonSerializerSettings { ContractResolver = skipCompilerGeneratedResolver }); Assert.AreEqual(@"{ ""StringField"": ""Field"", ""IntField"": 1, ""StringProperty"": ""Property"", ""IntProperty"": 2 }", skipCompilerGeneratedJson); DefaultContractResolver includeCompilerGeneratedResolver = new DefaultContractResolver { DefaultMembersSearchFlags = BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public, SerializeCompilerGeneratedMembers = true }; string includeCompilerGeneratedJson = JsonConvert.SerializeObject(structTest, Formatting.Indented, new JsonSerializerSettings { ContractResolver = includeCompilerGeneratedResolver }); Assert.AreEqual(@"{ ""StringField"": ""Field"", ""IntField"": 1, ""<StringProperty>k__BackingField"": ""Property"", ""<IntProperty>k__BackingField"": 2, ""StringProperty"": ""Property"", ""IntProperty"": 2 }", includeCompilerGeneratedJson); } #endif } }
34.140684
115
0.632253
[ "MIT" ]
SinnerSchraderMobileMirrors/Newtonsoft.Json
Src/Newtonsoft.Json.Tests/Serialization/ContractResolverTests.cs
8,981
C#
using Mirror; namespace WeaverClientRpcTests.ClientRpcCantBeStatic { class ClientRpcCantBeStatic : NetworkBehaviour { [ClientRpc] static void RpcCantBeStatic() { } } }
17.909091
52
0.695431
[ "MIT" ]
10allday/OpenMMO
Plugins/3rdParty/Mirror/Tests/Editor/Weaver/WeaverClientRpcTests~/ClientRpcCantBeStatic.cs
197
C#
using System; using System.Collections.ObjectModel; using System.IO; using System.Linq; namespace FileSignatures { /// <summary> /// Specifies the format of a file. /// </summary> public abstract class FileFormat : IEquatable<FileFormat> { /// <summary> /// Initializes a new instance of the FileFormat class which has the specified signature and media type. /// </summary> /// <param name="signature">The header signature of the format.</param> /// <param name="headerLength">The number of bytes required to determine the format.</param> /// <param name="mediaType">The media type of the format.</param> /// <param name="extension">The appropriate file extension for the format.</param> protected FileFormat(byte[] signature, string mediaType, string extension) : this(signature, signature == null ? 0 : signature.Length, mediaType, extension, 0) { } /// <summary> /// Initializes a new instance of the FileFormat class which has the specified signature and media type. /// </summary> /// <param name="signature">The header signature of the format.</param> /// <param name="mediaType">The media type of the format.</param> /// <param name="extension">The appropriate file extension for the format.</param> /// <param name="offset">The offset at which the signature is located.</param> protected FileFormat(byte[] signature, string mediaType, string extension, int offset) : this(signature, signature == null ? offset : signature.Length + offset, mediaType, extension, offset) { } /// <summary> /// Initializes a new instance of the FileFormat class which has the specified signature and media type. /// </summary> /// <param name="signature">The header signature of the format.</param> /// <param name="headerLength">The number of bytes required to determine the format.</param> /// <param name="mediaType">The media type of the format.</param> /// <param name="extension">The appropriate file extension for the format.</param> protected FileFormat(byte[] signature, int headerLength, string mediaType, string extension) : this(signature, headerLength, mediaType, extension, 0) { } /// <summary> /// Initializes a new instance of the FileFormat class which has the specified signature and media type. /// </summary> /// <param name="signature">The header signature of the format.</param> /// <param name="headerLength">The number of bytes required to determine the format.</param> /// <param name="mediaType">The media type of the format.</param> /// <param name="extension">The appropriate file extension for the format.</param> /// <param name="offset">The offset at which the signature is located.</param> protected FileFormat(byte[] signature, int headerLength, string mediaType, string extension, int offset) { if (signature == null) { throw new ArgumentNullException(nameof(signature)); } if (string.IsNullOrEmpty(mediaType)) { throw new ArgumentNullException(nameof(mediaType)); } Signature = new ReadOnlyCollection<byte>(signature); HeaderLength = headerLength; Offset = offset; Extension = extension; MediaType = mediaType; } /// <summary> /// Gets a byte signature which can be used to identify the file format. /// </summary> public ReadOnlyCollection<byte> Signature { get; } /// <summary> /// Gets the number of bytes required to determine the format. /// A value of <see cref="int.MaxValue"/> indicates that the entire file is required to determine the format. /// </summary> public int HeaderLength { get; } /// <summary> /// Gets the appropriate file extension for the format. /// </summary> public string Extension { get; } /// <summary> /// Gets the media type identifier for the format. /// </summary> public string MediaType { get; } /// <summary> /// Gets the offset in the file at which the signature is located. /// </summary> public int Offset { get; } /// <summary> /// Returns a value indicating whether the format matches a file header. /// </summary> /// <param name="header">The stream to check.</param> public virtual bool IsMatch(Stream stream) { if (stream == null || (stream.Length < HeaderLength && HeaderLength < int.MaxValue) || Offset > stream.Length) { return false; } stream.Position = Offset; for (int i = 0; i < Signature.Count; i++) { var b = stream.ReadByte(); if (b != Signature[i]) { return false; } } return true; } /// <summary> /// Determines whether the object is equal to this FileFormat. /// </summary> /// <param name="obj">The object to compare.</param> public override bool Equals(object obj) { return Equals(obj as FileFormat); } /// <summary> /// Determines whether the format is equal to this FileFormat. /// </summary> /// <param name="fileFormat">The format to compare.</param> public bool Equals(FileFormat? fileFormat) { if(fileFormat == null) { return false; } if(ReferenceEquals(this, fileFormat)) { return true; } if(GetType() != fileFormat.GetType()) { return false; } return fileFormat.Signature.SequenceEqual(Signature); } /// <summary> /// Serves as the default hash function. /// </summary> public override int GetHashCode() { unchecked { if (Signature == null) { return 0; } int hash = 17; foreach (byte element in Signature) { hash = hash * 31 + element.GetHashCode(); } return hash; } } /// <summary> /// Returns a string that represents this format. /// </summary> public override string ToString() { return MediaType; } } }
36.391534
198
0.557284
[ "MIT" ]
markacola/FileSignatures
src/FileSignatures/FileFormat.cs
6,880
C#
using System; using System.Threading; class FallingRocks { static int dwarfPosition = 0; static int rockPositionX = 0; static int rockPositionY = 0; static int points = 0; static Random randomGenerator = new Random(); static char[] rocks = {'^', '@', '*', '&', '+', '%', '$', '#', '!', '.', ';'}; static void RemoveScrollBars() { Console.BufferHeight = Console.WindowHeight; Console.BufferWidth = Console.WindowWidth; } static void SetInitialPositions() { dwarfPosition = Console.WindowWidth / 2 - 4; } static void DrawDwarf() { PrintAtPosition(dwarfPosition, Console.WindowHeight - 1, '('); PrintAtPosition(dwarfPosition + 1, Console.WindowHeight - 1, '-'); PrintAtPosition(dwarfPosition + 2, Console.WindowHeight - 1, 'O'); PrintAtPosition(dwarfPosition + 3, Console.WindowHeight - 1, '-'); PrintAtPosition(dwarfPosition + 4, Console.WindowHeight - 1, ')'); } static void PrintAtPosition(int x, int y, char symbol) { Console.SetCursorPosition(x, y); Console.Write(symbol); } static void GenerateFallingRocksAndDensity() { int kindOfRock = randomGenerator.Next(0, 11); int numberOfFallingRocks = randomGenerator.Next(1, 6); int densityOfFallingRocks = randomGenerator.Next(0, 80); for (int i = 0; i < densityOfFallingRocks; i++) { PrintRocksAtPosition(rockPositionX + i, rockPositionY, rocks[kindOfRock], i); } } static void PrintRocksAtPosition(int x, int y, char symbol, int densityOfRocks) { Console.SetCursorPosition(x, y); for (int spaces = 0; spaces < densityOfRocks; spaces++) { Console.Write(" "); } Console.Write(symbol); } static void RocksFall() { if (rockPositionY < Console.WindowHeight - 1) { rockPositionY++; } } static void DrawRocks() { GenerateFallingRocksAndDensity(); //RocksFall(); } static void MoveDwarfRight() { if (dwarfPosition < Console.WindowWidth - 6) { dwarfPosition++; } } static void MoveDwarfLeft() { if (dwarfPosition > 0) { dwarfPosition--; } } static void PrintResult() { Console.SetCursorPosition(0, 0); Console.Write("---Game over... Your score is {0}!---", points); } static void Main() { RemoveScrollBars(); SetInitialPositions(); while (true) { if (Console.KeyAvailable == true) { ConsoleKeyInfo keyPressed = Console.ReadKey(); if (keyPressed.Key == ConsoleKey.LeftArrow) { MoveDwarfLeft(); } if (keyPressed.Key == ConsoleKey.RightArrow) { MoveDwarfRight(); } } Console.Clear(); DrawDwarf(); DrawRocks(); //PrintResult(); Thread.Sleep(500); } } }
26.438017
93
0.537981
[ "MIT" ]
vladislav-karamfilov/TelerikAcademy
C# Projects/ConsoleApplication2/ConsoleApplication2/FallingRocks.cs
3,201
C#
using Microsoft.Owin; using Owin; using Microsoft.Owin.Cors; [assembly: OwinStartup(typeof(Divergent.Finance.API.Startup))] namespace Divergent.Finance.API { public partial class Startup { public void Configuration(IAppBuilder app) { app.UseCors(CorsOptions.AllowAll); } } }
19.176471
62
0.671779
[ "Apache-2.0" ]
HScheenen/Workshop
exercises/01-composite-ui/after/Divergent.Finance.API/Startup.cs
328
C#
/* ---------------------------------------------------------------------------- * This file was automatically generated by SWIG (http://www.swig.org). * Version 2.0.1 * * Do not make changes to this file unless you know what you are doing--modify * the SWIG interface file instead. * ----------------------------------------------------------------------------- */ namespace RakNet { using System; using System.Runtime.InteropServices; public class SWIGTYPE_p_double { private HandleRef swigCPtr; internal SWIGTYPE_p_double(IntPtr cPtr, bool futureUse) { swigCPtr = new HandleRef(this, cPtr); } protected SWIGTYPE_p_double() { swigCPtr = new HandleRef(null, IntPtr.Zero); } internal static HandleRef getCPtr(SWIGTYPE_p_double obj) { return (obj == null) ? new HandleRef(null, IntPtr.Zero) : obj.swigCPtr; } } }
27.419355
83
0.584706
[ "Apache-2.0" ]
Colton-Soneson/FissionEditor
VulkanEditor/SDK/Source/Raknet/DependentExtensions/Swig/InternalSwigItems/InternalSwigWindowsCSharpSample/InternalSwigTestApp/SwigFiles/SWIGTYPE_p_double.cs
850
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.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; using Xunit.Abstractions; namespace Microsoft.CodeAnalysis.CSharp.UnitTests { public class DeclarationParsingTests : ParsingTests { public DeclarationParsingTests(ITestOutputHelper output) : base(output) { } protected override SyntaxTree ParseTree(string text, CSharpParseOptions options) { return SyntaxFactory.ParseSyntaxTree(text, options ?? TestOptions.Regular); } [Fact] public void TestExternAlias() { var text = "extern alias a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Externs.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ea = file.Externs[0]; Assert.NotEqual(default, ea.ExternKeyword); Assert.Equal(SyntaxKind.ExternKeyword, ea.ExternKeyword.Kind()); Assert.NotEqual(default, ea.AliasKeyword); Assert.Equal(SyntaxKind.AliasKeyword, ea.AliasKeyword.Kind()); Assert.False(ea.AliasKeyword.IsMissing); Assert.NotEqual(default, ea.Identifier); Assert.Equal("a", ea.Identifier.ToString()); Assert.NotEqual(default, ea.SemicolonToken); } [Fact] public void TestUsing() { var text = "using a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.Null(ud.Alias); Assert.True(ud.StaticKeyword == default(SyntaxToken)); Assert.NotNull(ud.Name); Assert.Equal("a", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingStatic() { var text = "using static a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.Equal(SyntaxKind.StaticKeyword, ud.StaticKeyword.Kind()); Assert.Null(ud.Alias); Assert.NotNull(ud.Name); Assert.Equal("a", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingStaticInWrongOrder() { var text = "static using a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToFullString()); var errors = file.Errors(); Assert.True(errors.Length > 0); Assert.Equal((int)ErrorCode.ERR_NamespaceUnexpected, errors[0].Code); } [Fact] public void TestDuplicateStatic() { var text = "using static static a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); var errors = file.Errors(); Assert.True(errors.Length > 0); Assert.Equal((int)ErrorCode.ERR_IdentifierExpectedKW, errors[0].Code); } [Fact] public void TestUsingNamespace() { var text = "using namespace a;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); var errors = file.Errors(); Assert.True(errors.Length > 0); Assert.Equal((int)ErrorCode.ERR_IdentifierExpectedKW, errors[0].Code); } [Fact] public void TestUsingDottedName() { var text = "using a.b;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.True(ud.StaticKeyword == default(SyntaxToken)); Assert.Null(ud.Alias); Assert.NotNull(ud.Name); Assert.Equal("a.b", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingStaticDottedName() { var text = "using static a.b;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.Equal(SyntaxKind.StaticKeyword, ud.StaticKeyword.Kind()); Assert.Null(ud.Alias); Assert.NotNull(ud.Name); Assert.Equal("a.b", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingStaticGenericName() { var text = "using static a<int?>;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.Equal(SyntaxKind.StaticKeyword, ud.StaticKeyword.Kind()); Assert.Null(ud.Alias); Assert.NotNull(ud.Name); Assert.Equal("a<int?>", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingAliasName() { var text = "using a = b;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.NotNull(ud.Alias); Assert.NotNull(ud.Alias.Name); Assert.Equal("a", ud.Alias.Name.ToString()); Assert.NotEqual(default, ud.Alias.EqualsToken); Assert.NotNull(ud.Name); Assert.Equal("b", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestUsingAliasGenericName() { var text = "using a = b<c>;"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Usings.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); var ud = file.Usings[0]; Assert.NotEqual(default, ud.UsingKeyword); Assert.Equal(SyntaxKind.UsingKeyword, ud.UsingKeyword.Kind()); Assert.NotNull(ud.Alias); Assert.NotNull(ud.Alias.Name); Assert.Equal("a", ud.Alias.Name.ToString()); Assert.NotEqual(default, ud.Alias.EqualsToken); Assert.NotNull(ud.Name); Assert.Equal("b<c>", ud.Name.ToString()); Assert.NotEqual(default, ud.SemicolonToken); } [Fact] public void TestGlobalAttribute() { var text = "[assembly:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttribute_Verbatim() { var text = "[@assembly:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("@assembly", ad.Target.Identifier.ToString()); Assert.Equal("assembly", ad.Target.Identifier.ValueText); Assert.Equal(SyntaxKind.IdentifierToken, ad.Target.Identifier.Kind()); Assert.Equal(AttributeLocation.Assembly, ad.Target.Identifier.ToAttributeLocation()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttribute_Escape() { var text = @"[as\u0073embly:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal(@"as\u0073embly", ad.Target.Identifier.ToString()); Assert.Equal("assembly", ad.Target.Identifier.ValueText); Assert.Equal(SyntaxKind.IdentifierToken, ad.Target.Identifier.Kind()); Assert.Equal(AttributeLocation.Assembly, ad.Target.Identifier.ToAttributeLocation()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalModuleAttribute() { var text = "[module:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("module", ad.Target.Identifier.ToString()); Assert.Equal(SyntaxKind.ModuleKeyword, ad.Target.Identifier.Kind()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalModuleAttribute_Verbatim() { var text = "[@module:a]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("@module", ad.Target.Identifier.ToString()); Assert.Equal(SyntaxKind.IdentifierToken, ad.Target.Identifier.Kind()); Assert.Equal(AttributeLocation.Module, ad.Target.Identifier.ToAttributeLocation()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttributeWithParentheses() { var text = "[assembly:a()]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.Equal(SyntaxKind.AssemblyKeyword, ad.Target.Identifier.Kind()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.NotNull(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.OpenParenToken); Assert.Equal(0, ad.Attributes[0].ArgumentList.Arguments.Count); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.CloseParenToken); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttributeWithMultipleArguments() { var text = "[assembly:a(b, c)]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.NotNull(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.OpenParenToken); Assert.Equal(2, ad.Attributes[0].ArgumentList.Arguments.Count); Assert.Equal("b", ad.Attributes[0].ArgumentList.Arguments[0].ToString()); Assert.Equal("c", ad.Attributes[0].ArgumentList.Arguments[1].ToString()); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.CloseParenToken); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttributeWithNamedArguments() { var text = "[assembly:a(b = c)]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.NotNull(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.OpenParenToken); Assert.Equal(1, ad.Attributes[0].ArgumentList.Arguments.Count); Assert.Equal("b = c", ad.Attributes[0].ArgumentList.Arguments[0].ToString()); Assert.NotNull(ad.Attributes[0].ArgumentList.Arguments[0].NameEquals); Assert.NotNull(ad.Attributes[0].ArgumentList.Arguments[0].NameEquals.Name); Assert.Equal("b", ad.Attributes[0].ArgumentList.Arguments[0].NameEquals.Name.ToString()); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.Arguments[0].NameEquals.EqualsToken); Assert.NotNull(ad.Attributes[0].ArgumentList.Arguments[0].Expression); Assert.Equal("c", ad.Attributes[0].ArgumentList.Arguments[0].Expression.ToString()); Assert.NotEqual(default, ad.Attributes[0].ArgumentList.CloseParenToken); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestGlobalAttributeWithMultipleAttributes() { var text = "[assembly:a, b]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(2, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotNull(ad.Attributes[1].Name); Assert.Equal("b", ad.Attributes[1].Name.ToString()); Assert.Null(ad.Attributes[1].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestMultipleGlobalAttributeDeclarations() { var text = "[assembly:a] [assembly:b]"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(2, file.AttributeLists.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.AttributeList, file.AttributeLists[0].Kind()); var ad = (AttributeListSyntax)file.AttributeLists[0]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("a", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); ad = (AttributeListSyntax)file.AttributeLists[1]; Assert.NotEqual(default, ad.OpenBracketToken); Assert.NotNull(ad.Target); Assert.NotEqual(default, ad.Target.Identifier); Assert.Equal("assembly", ad.Target.Identifier.ToString()); Assert.NotEqual(default, ad.Target.ColonToken); Assert.Equal(1, ad.Attributes.Count); Assert.NotNull(ad.Attributes[0].Name); Assert.Equal("b", ad.Attributes[0].Name.ToString()); Assert.Null(ad.Attributes[0].ArgumentList); Assert.NotEqual(default, ad.CloseBracketToken); } [Fact] public void TestNamespace() { var text = "namespace a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(0, ns.Usings.Count); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestNamespaceWithDottedName() { var text = "namespace a.b.c { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a.b.c", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(0, ns.Usings.Count); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestNamespaceWithUsing() { var text = "namespace a { using b.c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(1, ns.Usings.Count); Assert.Equal("using b.c;", ns.Usings[0].ToString()); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestNamespaceWithExternAlias() { var text = "namespace a { extern alias b; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(1, ns.Externs.Count); Assert.Equal("extern alias b;", ns.Externs[0].ToString()); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestNamespaceWithExternAliasFollowingUsingBad() { var text = "namespace a { using b; extern alias c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToFullString()); Assert.Equal(1, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(1, ns.Usings.Count); Assert.Equal("using b;", ns.Usings[0].ToString()); Assert.Equal(0, ns.Externs.Count); Assert.Equal(0, ns.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestNamespaceWithNestedNamespace() { var text = "namespace a { namespace b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.NamespaceDeclaration, file.Members[0].Kind()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ns.NamespaceKeyword); Assert.NotNull(ns.Name); Assert.Equal("a", ns.Name.ToString()); Assert.NotEqual(default, ns.OpenBraceToken); Assert.Equal(0, ns.Usings.Count); Assert.Equal(1, ns.Members.Count); Assert.Equal(SyntaxKind.NamespaceDeclaration, ns.Members[0].Kind()); var ns2 = (NamespaceDeclarationSyntax)ns.Members[0]; Assert.NotEqual(default, ns2.NamespaceKeyword); Assert.NotNull(ns2.Name); Assert.Equal("b", ns2.Name.ToString()); Assert.NotEqual(default, ns2.OpenBraceToken); Assert.Equal(0, ns2.Usings.Count); Assert.Equal(0, ns2.Members.Count); Assert.NotEqual(default, ns.CloseBraceToken); } [Fact] public void TestClass() { var text = "class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithPublic() { var text = "public class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.PublicKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithInternal() { var text = "internal class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.InternalKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithStatic() { var text = "static class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.StaticKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithSealed() { var text = "sealed class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.SealedKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithAbstract() { var text = "abstract class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.AbstractKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithPartial() { var text = "partial class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.PartialKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithAttribute() { var text = "[attr] class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, cs.AttributeLists.Count); Assert.Equal("[attr]", cs.AttributeLists[0].ToString()); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleAttributes() { var text = "[attr1] [attr2] class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(2, cs.AttributeLists.Count); Assert.Equal("[attr1]", cs.AttributeLists[0].ToString()); Assert.Equal("[attr2]", cs.AttributeLists[1].ToString()); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleAttributesInAList() { var text = "[attr1, attr2] class a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(1, cs.AttributeLists.Count); Assert.Equal("[attr1, attr2]", cs.AttributeLists[0].ToString()); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithBaseType() { var text = "class a : b { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.NotNull(cs.BaseList); Assert.NotEqual(default, cs.BaseList.ColonToken); Assert.Equal(1, cs.BaseList.Types.Count); Assert.Equal("b", cs.BaseList.Types[0].Type.ToString()); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleBases() { var text = "class a : b, c { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.NotNull(cs.BaseList); Assert.NotEqual(default, cs.BaseList.ColonToken); Assert.Equal(2, cs.BaseList.Types.Count); Assert.Equal("b", cs.BaseList.Types[0].Type.ToString()); Assert.Equal("c", cs.BaseList.Types[1].Type.ToString()); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithTypeConstraintBound() { var text = "class a<b> where b : c { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(bound.Type); Assert.Equal("c", bound.Type.ToString()); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNonGenericClassWithTypeConstraintBound() { var text = "class a where b : c { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); var errors = file.Errors(); Assert.Equal(0, errors.Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(bound.Type); Assert.Equal("c", bound.Type.ToString()); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); CreateCompilation(text).GetDeclarationDiagnostics().Verify( // (1,9): error CS0080: Constraints are not allowed on non-generic declarations // class a where b : c { } Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(1, 9)); } [Fact] public void TestNonGenericMethodWithTypeConstraintBound() { var text = "class a { void M() where b : c { } }"; CreateCompilation(text).GetDeclarationDiagnostics().Verify( // (1,20): error CS0080: Constraints are not allowed on non-generic declarations // class a { void M() where b : c { } } Diagnostic(ErrorCode.ERR_ConstraintOnlyAllowedOnGenericDecl, "where").WithLocation(1, 20)); } [Fact] public void TestClassWithNewConstraintBound() { var text = "class a<b> where b : new() { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.ConstructorConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (ConstructorConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, bound.NewKeyword); Assert.False(bound.NewKeyword.IsMissing); Assert.NotEqual(default, bound.OpenParenToken); Assert.False(bound.OpenParenToken.IsMissing); Assert.NotEqual(default, bound.CloseParenToken); Assert.False(bound.CloseParenToken.IsMissing); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithClassConstraintBound() { var text = "class a<b> where b : class { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.ClassConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (ClassOrStructConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, bound.ClassOrStructKeyword); Assert.False(bound.ClassOrStructKeyword.IsMissing); Assert.Equal(SyntaxKind.ClassKeyword, bound.ClassOrStructKeyword.Kind()); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithStructConstraintBound() { var text = "class a<b> where b : struct { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.StructConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var bound = (ClassOrStructConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, bound.ClassOrStructKeyword); Assert.False(bound.ClassOrStructKeyword.IsMissing); Assert.Equal(SyntaxKind.StructKeyword, bound.ClassOrStructKeyword.Kind()); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleConstraintBounds() { var text = "class a<b> where b : class, c, new() { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(3, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.ClassConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var classBound = (ClassOrStructConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, classBound.ClassOrStructKeyword); Assert.False(classBound.ClassOrStructKeyword.IsMissing); Assert.Equal(SyntaxKind.ClassKeyword, classBound.ClassOrStructKeyword.Kind()); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[1].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[1]; Assert.NotNull(typeBound.Type); Assert.Equal("c", typeBound.Type.ToString()); Assert.Equal(SyntaxKind.ConstructorConstraint, cs.ConstraintClauses[0].Constraints[2].Kind()); var bound = (ConstructorConstraintSyntax)cs.ConstraintClauses[0].Constraints[2]; Assert.NotEqual(default, bound.NewKeyword); Assert.False(bound.NewKeyword.IsMissing); Assert.NotEqual(default, bound.OpenParenToken); Assert.False(bound.OpenParenToken.IsMissing); Assert.NotEqual(default, bound.CloseParenToken); Assert.False(bound.CloseParenToken.IsMissing); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleConstraints() { var text = "class a<b> where b : c where b : new() { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(2, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(typeBound.Type); Assert.Equal("c", typeBound.Type.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[1].Name); Assert.Equal("b", cs.ConstraintClauses[1].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].ColonToken); Assert.False(cs.ConstraintClauses[1].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[1].Constraints.Count); Assert.Equal(SyntaxKind.ConstructorConstraint, cs.ConstraintClauses[1].Constraints[0].Kind()); var bound = (ConstructorConstraintSyntax)cs.ConstraintClauses[1].Constraints[0]; Assert.NotEqual(default, bound.NewKeyword); Assert.False(bound.NewKeyword.IsMissing); Assert.NotEqual(default, bound.OpenParenToken); Assert.False(bound.OpenParenToken.IsMissing); Assert.NotEqual(default, bound.CloseParenToken); Assert.False(bound.CloseParenToken.IsMissing); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestClassWithMultipleConstraints001() { var text = "class a<b> where b : c where b { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(2, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(2, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(typeBound.Type); Assert.Equal("c", typeBound.Type.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[1].Name); Assert.Equal("b", cs.ConstraintClauses[1].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].ColonToken); Assert.True(cs.ConstraintClauses[1].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[1].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[1].Constraints[0].Kind()); var bound = (TypeConstraintSyntax)cs.ConstraintClauses[1].Constraints[0]; Assert.True(bound.Type.IsMissing); } [Fact] public void TestClassWithMultipleConstraints002() { var text = "class a<b> where b : c where { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(3, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.Null(cs.BaseList); Assert.Equal(2, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotNull(typeBound.Type); Assert.Equal("c", typeBound.Type.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[1].WhereKeyword); Assert.True(cs.ConstraintClauses[1].Name.IsMissing); Assert.True(cs.ConstraintClauses[1].ColonToken.IsMissing); Assert.Equal(1, cs.ConstraintClauses[1].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[1].Constraints[0].Kind()); var bound = (TypeConstraintSyntax)cs.ConstraintClauses[1].Constraints[0]; Assert.True(bound.Type.IsMissing); } [Fact] public void TestClassWithMultipleBasesAndConstraints() { var text = "class a<b> : c, d where b : class, e, new() { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Equal("<b>", cs.TypeParameterList.ToString()); Assert.NotNull(cs.BaseList); Assert.NotEqual(default, cs.BaseList.ColonToken); Assert.Equal(2, cs.BaseList.Types.Count); Assert.Equal("c", cs.BaseList.Types[0].Type.ToString()); Assert.Equal("d", cs.BaseList.Types[1].Type.ToString()); Assert.Equal(1, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.ConstraintClauses[0].WhereKeyword); Assert.NotNull(cs.ConstraintClauses[0].Name); Assert.Equal("b", cs.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, cs.ConstraintClauses[0].ColonToken); Assert.False(cs.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(3, cs.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.ClassConstraint, cs.ConstraintClauses[0].Constraints[0].Kind()); var classBound = (ClassOrStructConstraintSyntax)cs.ConstraintClauses[0].Constraints[0]; Assert.NotEqual(default, classBound.ClassOrStructKeyword); Assert.False(classBound.ClassOrStructKeyword.IsMissing); Assert.Equal(SyntaxKind.ClassKeyword, classBound.ClassOrStructKeyword.Kind()); Assert.Equal(SyntaxKind.TypeConstraint, cs.ConstraintClauses[0].Constraints[1].Kind()); var typeBound = (TypeConstraintSyntax)cs.ConstraintClauses[0].Constraints[1]; Assert.NotNull(typeBound.Type); Assert.Equal("e", typeBound.Type.ToString()); Assert.Equal(SyntaxKind.ConstructorConstraint, cs.ConstraintClauses[0].Constraints[2].Kind()); var bound = (ConstructorConstraintSyntax)cs.ConstraintClauses[0].Constraints[2]; Assert.NotEqual(default, bound.NewKeyword); Assert.False(bound.NewKeyword.IsMissing); Assert.NotEqual(default, bound.OpenParenToken); Assert.False(bound.OpenParenToken.IsMissing); Assert.NotEqual(default, bound.CloseParenToken); Assert.False(bound.CloseParenToken.IsMissing); Assert.NotEqual(default, cs.OpenBraceToken); Assert.Equal(0, cs.Members.Count); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestInterface() { var text = "interface a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.InterfaceDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.InterfaceKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestGenericInterface() { var text = "interface A<B> { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.InterfaceDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.InterfaceKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); var gn = cs.TypeParameterList; Assert.Equal("<B>", gn.ToString()); Assert.Equal("A", cs.Identifier.ToString()); Assert.Equal(0, gn.Parameters[0].AttributeLists.Count); Assert.Equal(SyntaxKind.None, gn.Parameters[0].VarianceKeyword.Kind()); Assert.Equal("B", gn.Parameters[0].Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestGenericInterfaceWithAttributesAndVariance() { var text = "interface A<[B] out C> { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.InterfaceDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.InterfaceKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); var gn = cs.TypeParameterList; Assert.Equal("<[B] out C>", gn.ToString()); Assert.Equal("A", cs.Identifier.ToString()); Assert.Equal(1, gn.Parameters[0].AttributeLists.Count); Assert.Equal("B", gn.Parameters[0].AttributeLists[0].Attributes[0].Name.ToString()); Assert.NotEqual(default, gn.Parameters[0].VarianceKeyword); Assert.Equal(SyntaxKind.OutKeyword, gn.Parameters[0].VarianceKeyword.Kind()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestStruct() { var text = "struct a { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.StructKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedClass() { var text = "class a { class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedPrivateClass() { var text = "class a { private class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.PrivateKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedProtectedClass() { var text = "class a { protected class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.ProtectedKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedProtectedInternalClass() { var text = "class a { protected internal class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(2, cs.Modifiers.Count); Assert.Equal(SyntaxKind.ProtectedKeyword, cs.Modifiers[0].Kind()); Assert.Equal(SyntaxKind.InternalKeyword, cs.Modifiers[1].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedInternalProtectedClass() { var text = "class a { internal protected class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(2, cs.Modifiers.Count); Assert.Equal(SyntaxKind.InternalKeyword, cs.Modifiers[0].Kind()); Assert.Equal(SyntaxKind.ProtectedKeyword, cs.Modifiers[1].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedPublicClass() { var text = "class a { public class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.PublicKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestNestedInternalClass() { var text = "class a { internal class b { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, cs.Members[0].Kind()); cs = (TypeDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(1, cs.Modifiers.Count); Assert.Equal(SyntaxKind.InternalKeyword, cs.Modifiers[0].Kind()); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("b", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); } [Fact] public void TestDelegate() { var text = "delegate a b();"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithRefReturnType() { var text = "delegate ref a b();"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("ref a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestDelegateWithRefReadonlyReturnType() { var text = "delegate ref readonly a b();"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("ref readonly a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithBuiltInReturnTypes() { TestDelegateWithBuiltInReturnType(SyntaxKind.VoidKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.BoolKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.SByteKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.IntKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.UIntKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.ShortKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.UShortKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.LongKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.ULongKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.FloatKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.DoubleKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.DecimalKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.StringKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.CharKeyword); TestDelegateWithBuiltInReturnType(SyntaxKind.ObjectKeyword); } private void TestDelegateWithBuiltInReturnType(SyntaxKind builtInType) { var typeText = SyntaxFacts.GetText(builtInType); var text = "delegate " + typeText + " b();"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal(typeText, ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithBuiltInParameterTypes() { TestDelegateWithBuiltInParameterType(SyntaxKind.BoolKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.SByteKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.IntKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.UIntKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.ShortKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.UShortKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.LongKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.ULongKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.FloatKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.DoubleKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.DecimalKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.StringKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.CharKeyword); TestDelegateWithBuiltInParameterType(SyntaxKind.ObjectKeyword); } private void TestDelegateWithBuiltInParameterType(SyntaxKind builtInType) { var typeText = SyntaxFacts.GetText(builtInType); var text = "delegate a b(" + typeText + " c);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal(typeText, ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("c", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithParameter() { var text = "delegate a b(c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithMultipleParameters() { var text = "delegate a b(c d, e f);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(2, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ds.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[1].Type); Assert.Equal("e", ds.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ds.ParameterList.Parameters[1].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithRefParameter() { var text = "delegate a b(ref c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(1, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.Equal(SyntaxKind.RefKeyword, ds.ParameterList.Parameters[0].Modifiers[0].Kind()); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithOutParameter() { var text = "delegate a b(out c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(1, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.Equal(SyntaxKind.OutKeyword, ds.ParameterList.Parameters[0].Modifiers[0].Kind()); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithParamsParameter() { var text = "delegate a b(params c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(1, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.Equal(SyntaxKind.ParamsKeyword, ds.ParameterList.Parameters[0].Modifiers[0].Kind()); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithArgListParameter() { var text = "delegate a b(__arglist);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); var errors = file.Errors(); Assert.Equal(0, errors.Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.Null(ds.ParameterList.Parameters[0].Type); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestDelegateWithParameterAttribute() { var text = "delegate a b([attr] c d);"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.DelegateDeclaration, file.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)file.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("a", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("b", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ds.ParameterList.Parameters.Count); Assert.Equal(1, ds.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal("[attr]", ds.ParameterList.Parameters[0].AttributeLists[0].ToString()); Assert.Equal(0, ds.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ds.ParameterList.Parameters[0].Type); Assert.Equal("c", ds.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ds.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ds.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestNestedDelegate() { var text = "class a { delegate b c(); }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.DelegateDeclaration, cs.Members[0].Kind()); var ds = (DelegateDeclarationSyntax)cs.Members[0]; Assert.NotEqual(default, ds.DelegateKeyword); Assert.NotNull(ds.ReturnType); Assert.Equal("b", ds.ReturnType.ToString()); Assert.NotEqual(default, ds.Identifier); Assert.Equal("c", ds.Identifier.ToString()); Assert.NotEqual(default, ds.ParameterList.OpenParenToken); Assert.False(ds.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ds.ParameterList.Parameters.Count); Assert.NotEqual(default, ds.ParameterList.CloseParenToken); Assert.False(ds.ParameterList.CloseParenToken.IsMissing); Assert.NotEqual(default, ds.SemicolonToken); Assert.False(ds.SemicolonToken.IsMissing); } [Fact] public void TestClassMethod() { var text = "class a { b X() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithRefReturn() { var text = "class a { ref b X() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("ref b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestClassMethodWithRefReadonlyReturn() { var text = "class a { ref readonly b X() { } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("ref readonly b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithRef() { var text = "class a { ref }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(1, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, cs.Members[0].Kind()); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestClassMethodWithRefReadonly() { var text = "class a { ref readonly }"; var file = this.ParseFile(text, parseOptions: TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(1, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IncompleteMember, cs.Members[0].Kind()); } private void TestClassMethodModifiers(params SyntaxKind[] modifiers) { var text = "class a { " + string.Join(" ", modifiers.Select(SyntaxFacts.GetText)) + " b X() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(modifiers.Length, ms.Modifiers.Count); for (int i = 0; i < modifiers.Length; ++i) { Assert.Equal(modifiers[i], ms.Modifiers[i].Kind()); } Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodAccessModes() { TestClassMethodModifiers(SyntaxKind.PublicKeyword); TestClassMethodModifiers(SyntaxKind.PrivateKeyword); TestClassMethodModifiers(SyntaxKind.InternalKeyword); TestClassMethodModifiers(SyntaxKind.ProtectedKeyword); } [Fact] public void TestClassMethodModifiersOrder() { TestClassMethodModifiers(SyntaxKind.PublicKeyword, SyntaxKind.VirtualKeyword); TestClassMethodModifiers(SyntaxKind.VirtualKeyword, SyntaxKind.PublicKeyword); TestClassMethodModifiers(SyntaxKind.InternalKeyword, SyntaxKind.ProtectedKeyword, SyntaxKind.VirtualKeyword); TestClassMethodModifiers(SyntaxKind.InternalKeyword, SyntaxKind.VirtualKeyword, SyntaxKind.ProtectedKeyword); } [Fact] public void TestClassMethodWithPartial() { var text = "class a { partial void M() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(1, ms.Modifiers.Count); Assert.Equal(SyntaxKind.PartialKeyword, ms.Modifiers[0].Kind()); Assert.NotNull(ms.ReturnType); Assert.Equal("void", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestStructMethodWithReadonly() { var text = "struct a { readonly void M() { } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var structDecl = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, structDecl.AttributeLists.Count); Assert.Equal(0, structDecl.Modifiers.Count); Assert.NotEqual(default, structDecl.Keyword); Assert.Equal(SyntaxKind.StructKeyword, structDecl.Keyword.Kind()); Assert.NotEqual(default, structDecl.Identifier); Assert.Equal("a", structDecl.Identifier.ToString()); Assert.Null(structDecl.BaseList); Assert.Equal(0, structDecl.ConstraintClauses.Count); Assert.NotEqual(default, structDecl.OpenBraceToken); Assert.NotEqual(default, structDecl.CloseBraceToken); Assert.Equal(1, structDecl.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, structDecl.Members[0].Kind()); var ms = (MethodDeclarationSyntax)structDecl.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(1, ms.Modifiers.Count); Assert.Equal(SyntaxKind.ReadOnlyKeyword, ms.Modifiers[0].Kind()); Assert.NotNull(ms.ReturnType); Assert.Equal("void", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestReadOnlyRefReturning() { var text = "struct a { readonly ref readonly int M() { } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var structDecl = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, structDecl.AttributeLists.Count); Assert.Equal(0, structDecl.Modifiers.Count); Assert.NotEqual(default, structDecl.Keyword); Assert.Equal(SyntaxKind.StructKeyword, structDecl.Keyword.Kind()); Assert.NotEqual(default, structDecl.Identifier); Assert.Equal("a", structDecl.Identifier.ToString()); Assert.Null(structDecl.BaseList); Assert.Equal(0, structDecl.ConstraintClauses.Count); Assert.NotEqual(default, structDecl.OpenBraceToken); Assert.NotEqual(default, structDecl.CloseBraceToken); Assert.Equal(1, structDecl.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, structDecl.Members[0].Kind()); var ms = (MethodDeclarationSyntax)structDecl.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(1, ms.Modifiers.Count); Assert.Equal(SyntaxKind.ReadOnlyKeyword, ms.Modifiers[0].Kind()); Assert.Equal(SyntaxKind.RefType, ms.ReturnType.Kind()); var rt = (RefTypeSyntax)ms.ReturnType; Assert.Equal(SyntaxKind.RefKeyword, rt.RefKeyword.Kind()); Assert.Equal(SyntaxKind.ReadOnlyKeyword, rt.ReadOnlyKeyword.Kind()); Assert.Equal("int", rt.Type.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestStructExpressionPropertyWithReadonly() { var text = "struct a { readonly int M => 42; }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var structDecl = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, structDecl.AttributeLists.Count); Assert.Equal(0, structDecl.Modifiers.Count); Assert.NotEqual(default, structDecl.Keyword); Assert.Equal(SyntaxKind.StructKeyword, structDecl.Keyword.Kind()); Assert.NotEqual(default, structDecl.Identifier); Assert.Equal("a", structDecl.Identifier.ToString()); Assert.Null(structDecl.BaseList); Assert.Equal(0, structDecl.ConstraintClauses.Count); Assert.NotEqual(default, structDecl.OpenBraceToken); Assert.NotEqual(default, structDecl.CloseBraceToken); Assert.Equal(1, structDecl.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, structDecl.Members[0].Kind()); var propertySyntax = (PropertyDeclarationSyntax)structDecl.Members[0]; Assert.Equal(0, propertySyntax.AttributeLists.Count); Assert.Equal(1, propertySyntax.Modifiers.Count); Assert.Equal(SyntaxKind.ReadOnlyKeyword, propertySyntax.Modifiers[0].Kind()); Assert.NotNull(propertySyntax.Type); Assert.Equal("int", propertySyntax.Type.ToString()); Assert.NotEqual(default, propertySyntax.Identifier); Assert.Equal("M", propertySyntax.Identifier.ToString()); Assert.NotNull(propertySyntax.ExpressionBody); Assert.NotEqual(SyntaxKind.None, propertySyntax.ExpressionBody.ArrowToken.Kind()); Assert.NotNull(propertySyntax.ExpressionBody.Expression); Assert.Equal(SyntaxKind.SemicolonToken, propertySyntax.SemicolonToken.Kind()); } [Fact] public void TestStructGetterPropertyWithReadonly() { var text = "struct a { int P { readonly get { return 42; } } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.StructDeclaration, file.Members[0].Kind()); var structDecl = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, structDecl.AttributeLists.Count); Assert.Equal(0, structDecl.Modifiers.Count); Assert.NotEqual(default, structDecl.Keyword); Assert.Equal(SyntaxKind.StructKeyword, structDecl.Keyword.Kind()); Assert.NotEqual(default, structDecl.Identifier); Assert.Equal("a", structDecl.Identifier.ToString()); Assert.Null(structDecl.BaseList); Assert.Equal(0, structDecl.ConstraintClauses.Count); Assert.NotEqual(default, structDecl.OpenBraceToken); Assert.NotEqual(default, structDecl.CloseBraceToken); Assert.Equal(1, structDecl.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, structDecl.Members[0].Kind()); var propertySyntax = (PropertyDeclarationSyntax)structDecl.Members[0]; Assert.Equal(0, propertySyntax.AttributeLists.Count); Assert.Equal(0, propertySyntax.Modifiers.Count); Assert.NotNull(propertySyntax.Type); Assert.Equal("int", propertySyntax.Type.ToString()); Assert.NotEqual(default, propertySyntax.Identifier); Assert.Equal("P", propertySyntax.Identifier.ToString()); var accessors = propertySyntax.AccessorList.Accessors; Assert.Equal(1, accessors.Count); Assert.Equal(1, accessors[0].Modifiers.Count); Assert.Equal(SyntaxKind.ReadOnlyKeyword, accessors[0].Modifiers[0].Kind()); } [Fact] public void TestStructBadExpressionProperty() { var text = @"public struct S { public int P readonly => 0; } "; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(3, file.Errors().Length); Assert.Equal(ErrorCode.ERR_SemicolonExpected, (ErrorCode)file.Errors()[0].Code); Assert.Equal(ErrorCode.ERR_InvalidMemberDecl, (ErrorCode)file.Errors()[1].Code); Assert.Equal(ErrorCode.ERR_InvalidMemberDecl, (ErrorCode)file.Errors()[2].Code); } [Fact] public void TestClassMethodWithParameter() { var text = "class a { b X(c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithMultipleParameters() { var text = "class a { b X(c d, e f) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(2, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ms.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[1].Type); Assert.Equal("e", ms.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ms.ParameterList.Parameters[1].Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } private void TestClassMethodWithParameterModifier(SyntaxKind mod) { var text = "class a { b X(" + SyntaxFacts.GetText(mod) + " c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(1, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.Equal(mod, ms.ParameterList.Parameters[0].Modifiers[0].Kind()); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithParameterModifiers() { TestClassMethodWithParameterModifier(SyntaxKind.RefKeyword); TestClassMethodWithParameterModifier(SyntaxKind.OutKeyword); TestClassMethodWithParameterModifier(SyntaxKind.ParamsKeyword); TestClassMethodWithParameterModifier(SyntaxKind.ThisKeyword); } [Fact] public void TestClassMethodWithArgListParameter() { var text = "class a { b X(__arglist) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.Null(ms.ParameterList.Parameters[0].Type); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal(SyntaxKind.ArgListKeyword, ms.ParameterList.Parameters[0].Identifier.Kind()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithBuiltInReturnTypes() { TestClassMethodWithBuiltInReturnType(SyntaxKind.VoidKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.BoolKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.SByteKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.IntKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.UIntKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.ShortKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.UShortKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.LongKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.ULongKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.FloatKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.DoubleKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.DecimalKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.StringKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.CharKeyword); TestClassMethodWithBuiltInReturnType(SyntaxKind.ObjectKeyword); } private void TestClassMethodWithBuiltInReturnType(SyntaxKind type) { var typeText = SyntaxFacts.GetText(type); var text = "class a { " + typeText + " M() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal(typeText, ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestClassMethodWithBuiltInParameterTypes() { TestClassMethodWithBuiltInParameterType(SyntaxKind.BoolKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.SByteKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.IntKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.UIntKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.ShortKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.UShortKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.LongKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.ULongKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.FloatKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.DoubleKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.DecimalKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.StringKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.CharKeyword); TestClassMethodWithBuiltInParameterType(SyntaxKind.ObjectKeyword); } private void TestClassMethodWithBuiltInParameterType(SyntaxKind type) { var typeText = SyntaxFacts.GetText(type); var text = "class a { b X(" + typeText + " c) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("X", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal(typeText, ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("c", ms.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestGenericClassMethod() { var text = "class a { b<c> M() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b<c>", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.Equal("M", ms.Identifier.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(0, ms.ConstraintClauses.Count); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [Fact] public void TestGenericClassMethodWithTypeConstraintBound() { var text = "class a { b X<c>() where b : d { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.MethodDeclaration, cs.Members[0].Kind()); var ms = (MethodDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotNull(ms.ReturnType); Assert.Equal("b", ms.ReturnType.ToString()); Assert.NotEqual(default, ms.Identifier); Assert.NotNull(ms.TypeParameterList); Assert.Equal("X", ms.Identifier.ToString()); Assert.Equal("<c>", ms.TypeParameterList.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.False(ms.ParameterList.OpenParenToken.IsMissing); Assert.Equal(0, ms.ParameterList.Parameters.Count); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.False(ms.ParameterList.CloseParenToken.IsMissing); Assert.Equal(1, ms.ConstraintClauses.Count); Assert.NotEqual(default, ms.ConstraintClauses[0].WhereKeyword); Assert.NotNull(ms.ConstraintClauses[0].Name); Assert.Equal("b", ms.ConstraintClauses[0].Name.ToString()); Assert.NotEqual(default, ms.ConstraintClauses[0].ColonToken); Assert.False(ms.ConstraintClauses[0].ColonToken.IsMissing); Assert.Equal(1, ms.ConstraintClauses[0].Constraints.Count); Assert.Equal(SyntaxKind.TypeConstraint, ms.ConstraintClauses[0].Constraints[0].Kind()); var typeBound = (TypeConstraintSyntax)ms.ConstraintClauses[0].Constraints[0]; Assert.NotNull(typeBound.Type); Assert.Equal("d", typeBound.Type.ToString()); Assert.NotNull(ms.Body); Assert.NotEqual(SyntaxKind.None, ms.Body.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, ms.Body.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, ms.SemicolonToken.Kind()); } [WorkItem(899685, "DevDiv/Personal")] [Fact] public void TestGenericClassConstructor() { var text = @" class Class1<T>{ public Class1() { } } "; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); // verify that we can roundtrip Assert.Equal(text, file.ToFullString()); // verify that we don't produce any errors Assert.Equal(0, file.Errors().Length); } [Fact] public void TestClassConstructor() { var text = "class a { a() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(SyntaxKind.None, cs.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, cs.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, cs.SemicolonToken.Kind()); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ConstructorDeclaration, cs.Members[0].Kind()); var cn = (ConstructorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cn.AttributeLists.Count); Assert.Equal(0, cn.Modifiers.Count); Assert.NotNull(cn.Body); Assert.NotEqual(default, cn.Body.OpenBraceToken); Assert.NotEqual(default, cn.Body.CloseBraceToken); } private void TestClassConstructorWithModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " a() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(SyntaxKind.None, cs.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, cs.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, cs.SemicolonToken.Kind()); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ConstructorDeclaration, cs.Members[0].Kind()); var cn = (ConstructorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, cn.AttributeLists.Count); Assert.Equal(1, cn.Modifiers.Count); Assert.Equal(mod, cn.Modifiers[0].Kind()); Assert.NotNull(cn.Body); Assert.NotEqual(default, cn.Body.OpenBraceToken); Assert.NotEqual(default, cn.Body.CloseBraceToken); } [Fact] public void TestClassConstructorWithModifiers() { TestClassConstructorWithModifier(SyntaxKind.PublicKeyword); TestClassConstructorWithModifier(SyntaxKind.PrivateKeyword); TestClassConstructorWithModifier(SyntaxKind.ProtectedKeyword); TestClassConstructorWithModifier(SyntaxKind.InternalKeyword); TestClassConstructorWithModifier(SyntaxKind.StaticKeyword); } [Fact] public void TestClassDestructor() { var text = "class a { ~a() { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(SyntaxKind.None, cs.OpenBraceToken.Kind()); Assert.NotEqual(SyntaxKind.None, cs.CloseBraceToken.Kind()); Assert.Equal(SyntaxKind.None, cs.SemicolonToken.Kind()); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.DestructorDeclaration, cs.Members[0].Kind()); var cn = (DestructorDeclarationSyntax)cs.Members[0]; Assert.NotEqual(default, cn.TildeToken); Assert.Equal(0, cn.AttributeLists.Count); Assert.Equal(0, cn.Modifiers.Count); Assert.NotNull(cn.Body); Assert.NotEqual(default, cn.Body.OpenBraceToken); Assert.NotEqual(default, cn.Body.CloseBraceToken); } [Fact] public void TestClassField() { var text = "class a { b c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithBuiltInTypes() { TestClassFieldWithBuiltInType(SyntaxKind.BoolKeyword); TestClassFieldWithBuiltInType(SyntaxKind.SByteKeyword); TestClassFieldWithBuiltInType(SyntaxKind.IntKeyword); TestClassFieldWithBuiltInType(SyntaxKind.UIntKeyword); TestClassFieldWithBuiltInType(SyntaxKind.ShortKeyword); TestClassFieldWithBuiltInType(SyntaxKind.UShortKeyword); TestClassFieldWithBuiltInType(SyntaxKind.LongKeyword); TestClassFieldWithBuiltInType(SyntaxKind.ULongKeyword); TestClassFieldWithBuiltInType(SyntaxKind.FloatKeyword); TestClassFieldWithBuiltInType(SyntaxKind.DoubleKeyword); TestClassFieldWithBuiltInType(SyntaxKind.DecimalKeyword); TestClassFieldWithBuiltInType(SyntaxKind.StringKeyword); TestClassFieldWithBuiltInType(SyntaxKind.CharKeyword); TestClassFieldWithBuiltInType(SyntaxKind.ObjectKeyword); } private void TestClassFieldWithBuiltInType(SyntaxKind type) { var typeText = SyntaxFacts.GetText(type); var text = "class a { " + typeText + " c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal(typeText, fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } private void TestClassFieldModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " b c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(1, fs.Modifiers.Count); Assert.Equal(mod, fs.Modifiers[0].Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldModifiers() { TestClassFieldModifier(SyntaxKind.PublicKeyword); TestClassFieldModifier(SyntaxKind.PrivateKeyword); TestClassFieldModifier(SyntaxKind.ProtectedKeyword); TestClassFieldModifier(SyntaxKind.InternalKeyword); TestClassFieldModifier(SyntaxKind.StaticKeyword); TestClassFieldModifier(SyntaxKind.ReadOnlyKeyword); TestClassFieldModifier(SyntaxKind.VolatileKeyword); TestClassFieldModifier(SyntaxKind.ExternKeyword); } private void TestClassEventFieldModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " event b c; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventFieldDeclaration, cs.Members[0].Kind()); var fs = (EventFieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(1, fs.Modifiers.Count); Assert.Equal(mod, fs.Modifiers[0].Kind()); Assert.NotEqual(default, fs.EventKeyword); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassEventFieldModifiers() { TestClassEventFieldModifier(SyntaxKind.PublicKeyword); TestClassEventFieldModifier(SyntaxKind.PrivateKeyword); TestClassEventFieldModifier(SyntaxKind.ProtectedKeyword); TestClassEventFieldModifier(SyntaxKind.InternalKeyword); TestClassEventFieldModifier(SyntaxKind.StaticKeyword); TestClassEventFieldModifier(SyntaxKind.ReadOnlyKeyword); TestClassEventFieldModifier(SyntaxKind.VolatileKeyword); TestClassEventFieldModifier(SyntaxKind.ExternKeyword); } [Fact] public void TestClassConstField() { var text = "class a { const b c = d; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(1, fs.Modifiers.Count); Assert.Equal(SyntaxKind.ConstKeyword, fs.Modifiers[0].Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("d", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithInitializer() { var text = "class a { b c = e; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("e", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithArrayInitializer() { var text = "class a { b c = { }; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal(SyntaxKind.ArrayInitializerExpression, fs.Declaration.Variables[0].Initializer.Value.Kind()); Assert.Equal("{ }", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithMultipleVariables() { var text = "class a { b c, d, e; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(3, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[1].Identifier); Assert.Equal("d", fs.Declaration.Variables[1].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[1].ArgumentList); Assert.Null(fs.Declaration.Variables[1].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[2].Identifier); Assert.Equal("e", fs.Declaration.Variables[2].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[2].ArgumentList); Assert.Null(fs.Declaration.Variables[2].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFieldWithMultipleVariablesAndInitializers() { var text = "class a { b c = x, d = y, e = z; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(0, fs.Modifiers.Count); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(3, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[0].ArgumentList); Assert.NotNull(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[0].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[0].Initializer.Value); Assert.Equal("x", fs.Declaration.Variables[0].Initializer.Value.ToString()); Assert.NotEqual(default, fs.Declaration.Variables[1].Identifier); Assert.Equal("d", fs.Declaration.Variables[1].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[1].ArgumentList); Assert.NotNull(fs.Declaration.Variables[1].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[1].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[1].Initializer.Value); Assert.Equal("y", fs.Declaration.Variables[1].Initializer.Value.ToString()); Assert.NotEqual(default, fs.Declaration.Variables[2].Identifier); Assert.Equal("e", fs.Declaration.Variables[2].Identifier.ToString()); Assert.Null(fs.Declaration.Variables[2].ArgumentList); Assert.NotNull(fs.Declaration.Variables[2].Initializer); Assert.NotEqual(default, fs.Declaration.Variables[2].Initializer.EqualsToken); Assert.NotNull(fs.Declaration.Variables[2].Initializer.Value); Assert.Equal("z", fs.Declaration.Variables[2].Initializer.Value.ToString()); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassFixedField() { var text = "class a { fixed b c[10]; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.FieldDeclaration, cs.Members[0].Kind()); var fs = (FieldDeclarationSyntax)cs.Members[0]; Assert.Equal(0, fs.AttributeLists.Count); Assert.Equal(1, fs.Modifiers.Count); Assert.Equal(SyntaxKind.FixedKeyword, fs.Modifiers[0].Kind()); Assert.NotNull(fs.Declaration.Type); Assert.Equal("b", fs.Declaration.Type.ToString()); Assert.Equal(1, fs.Declaration.Variables.Count); Assert.NotEqual(default, fs.Declaration.Variables[0].Identifier); Assert.Equal("c", fs.Declaration.Variables[0].Identifier.ToString()); Assert.NotNull(fs.Declaration.Variables[0].ArgumentList); Assert.NotEqual(default, fs.Declaration.Variables[0].ArgumentList.OpenBracketToken); Assert.NotEqual(default, fs.Declaration.Variables[0].ArgumentList.CloseBracketToken); Assert.Equal(1, fs.Declaration.Variables[0].ArgumentList.Arguments.Count); Assert.Equal("10", fs.Declaration.Variables[0].ArgumentList.Arguments[0].ToString()); Assert.Null(fs.Declaration.Variables[0].Initializer); Assert.NotEqual(default, fs.SemicolonToken); Assert.False(fs.SemicolonToken.IsMissing); } [Fact] public void TestClassProperty() { var text = "class a { b c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassPropertyWithRefReturn() { var text = "class a { ref b c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("ref b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestClassPropertyWithRefReadonlyReturn() { var text = "class a { ref readonly b c { get; set; } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("ref readonly b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassPropertyWithBuiltInTypes() { TestClassPropertyWithBuiltInType(SyntaxKind.BoolKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.SByteKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.IntKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.UIntKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.ShortKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.UShortKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.LongKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.ULongKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.FloatKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.DoubleKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.DecimalKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.StringKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.CharKeyword); TestClassPropertyWithBuiltInType(SyntaxKind.ObjectKeyword); } private void TestClassPropertyWithBuiltInType(SyntaxKind type) { var typeText = SyntaxFacts.GetText(type); var text = "class a { " + typeText + " c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal(typeText, ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassPropertyWithBodies() { var text = "class a { b c { get { } set { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(ps.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[0].SemicolonToken.Kind()); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.NotNull(ps.AccessorList.Accessors[1].Body); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[1].SemicolonToken.Kind()); } [Fact] public void TestClassAutoPropertyWithInitializer() { var text = "class a { b c { get; set; } = d; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (ClassDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotNull(ps.Initializer); Assert.NotNull(ps.Initializer.Value); Assert.Equal("d", ps.Initializer.Value.ToString()); } [Fact] public void InitializerOnNonAutoProp() { var text = "class C { int P { set {} } = 0; }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(0, file.Errors().Length); Assert.Equal(1, file.Members.Count); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (ClassDeclarationSyntax)file.Members[0]; Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.Errors().Length); } [Fact] public void TestClassPropertyOrEventWithValue() { TestClassPropertyWithValue(SyntaxKind.GetAccessorDeclaration, SyntaxKind.GetKeyword, SyntaxKind.IdentifierToken); TestClassPropertyWithValue(SyntaxKind.SetAccessorDeclaration, SyntaxKind.SetKeyword, SyntaxKind.IdentifierToken); TestClassEventWithValue(SyntaxKind.AddAccessorDeclaration, SyntaxKind.AddKeyword, SyntaxKind.IdentifierToken); TestClassEventWithValue(SyntaxKind.RemoveAccessorDeclaration, SyntaxKind.RemoveKeyword, SyntaxKind.IdentifierToken); } private void TestClassPropertyWithValue(SyntaxKind accessorKind, SyntaxKind accessorKeyword, SyntaxKind tokenKind) { bool isEvent = accessorKeyword == SyntaxKind.AddKeyword || accessorKeyword == SyntaxKind.RemoveKeyword; var text = "class a { " + (isEvent ? "event" : string.Empty) + " b c { " + SyntaxFacts.GetText(accessorKeyword) + " { x = value; } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(isEvent ? SyntaxKind.EventDeclaration : SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(1, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.Equal(accessorKind, ps.AccessorList.Accessors[0].Kind()); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(accessorKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[0].SemicolonToken.Kind()); var body = ps.AccessorList.Accessors[0].Body; Assert.NotNull(body); Assert.Equal(1, body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, body.Statements[0].Kind()); var es = (ExpressionStatementSyntax)body.Statements[0]; Assert.NotNull(es.Expression); Assert.Equal(SyntaxKind.SimpleAssignmentExpression, es.Expression.Kind()); var bx = (AssignmentExpressionSyntax)es.Expression; Assert.Equal(SyntaxKind.IdentifierName, bx.Right.Kind()); Assert.Equal(tokenKind, ((IdentifierNameSyntax)bx.Right).Identifier.Kind()); } private void TestClassEventWithValue(SyntaxKind accessorKind, SyntaxKind accessorKeyword, SyntaxKind tokenKind) { var text = "class a { event b c { " + SyntaxFacts.GetText(accessorKeyword) + " { x = value; } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventDeclaration, cs.Members[0].Kind()); var es = (EventDeclarationSyntax)cs.Members[0]; Assert.Equal(0, es.AttributeLists.Count); Assert.Equal(0, es.Modifiers.Count); Assert.NotNull(es.Type); Assert.Equal("b", es.Type.ToString()); Assert.NotEqual(default, es.Identifier); Assert.Equal("c", es.Identifier.ToString()); Assert.NotEqual(default, es.AccessorList.OpenBraceToken); Assert.NotEqual(default, es.AccessorList.CloseBraceToken); Assert.Equal(1, es.AccessorList.Accessors.Count); Assert.Equal(0, es.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[0].Modifiers.Count); Assert.Equal(accessorKind, es.AccessorList.Accessors[0].Kind()); Assert.NotEqual(default, es.AccessorList.Accessors[0].Keyword); Assert.Equal(accessorKeyword, es.AccessorList.Accessors[0].Keyword.Kind()); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[0].SemicolonToken.Kind()); var body = es.AccessorList.Accessors[0].Body; Assert.NotNull(body); Assert.Equal(1, body.Statements.Count); Assert.Equal(SyntaxKind.ExpressionStatement, body.Statements[0].Kind()); var xs = (ExpressionStatementSyntax)body.Statements[0]; Assert.NotNull(xs.Expression); Assert.Equal(SyntaxKind.SimpleAssignmentExpression, xs.Expression.Kind()); var bx = (AssignmentExpressionSyntax)xs.Expression; Assert.Equal(SyntaxKind.IdentifierName, bx.Right.Kind()); Assert.Equal(tokenKind, ((IdentifierNameSyntax)bx.Right).Identifier.Kind()); } private void TestClassPropertyWithModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " b c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(1, ps.Modifiers.Count); Assert.Equal(mod, ps.Modifiers[0].Kind()); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassPropertyWithModifiers() { TestClassPropertyWithModifier(SyntaxKind.PublicKeyword); TestClassPropertyWithModifier(SyntaxKind.PrivateKeyword); TestClassPropertyWithModifier(SyntaxKind.ProtectedKeyword); TestClassPropertyWithModifier(SyntaxKind.InternalKeyword); TestClassPropertyWithModifier(SyntaxKind.StaticKeyword); TestClassPropertyWithModifier(SyntaxKind.AbstractKeyword); TestClassPropertyWithModifier(SyntaxKind.VirtualKeyword); TestClassPropertyWithModifier(SyntaxKind.OverrideKeyword); TestClassPropertyWithModifier(SyntaxKind.NewKeyword); TestClassPropertyWithModifier(SyntaxKind.SealedKeyword); } private void TestClassPropertyWithAccessorModifier(SyntaxKind mod) { var text = "class a { b c { " + SyntaxFacts.GetText(mod) + " get { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(1, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(1, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.Equal(mod, ps.AccessorList.Accessors[0].Modifiers[0].Kind()); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(ps.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[0].SemicolonToken.Kind()); } [Fact] public void TestClassPropertyWithAccessorModifiers() { TestClassPropertyWithModifier(SyntaxKind.PublicKeyword); TestClassPropertyWithModifier(SyntaxKind.PrivateKeyword); TestClassPropertyWithModifier(SyntaxKind.ProtectedKeyword); TestClassPropertyWithModifier(SyntaxKind.InternalKeyword); TestClassPropertyWithModifier(SyntaxKind.AbstractKeyword); TestClassPropertyWithModifier(SyntaxKind.VirtualKeyword); TestClassPropertyWithModifier(SyntaxKind.OverrideKeyword); TestClassPropertyWithModifier(SyntaxKind.NewKeyword); TestClassPropertyWithModifier(SyntaxKind.SealedKeyword); } [Fact] public void TestClassPropertyExplicit() { var text = "class a { b I.c { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.NotNull(ps.ExplicitInterfaceSpecifier); Assert.Equal("I", ps.ExplicitInterfaceSpecifier.Name.ToString()); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassEventProperty() { var text = "class a { event b c { add { } remove { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventDeclaration, cs.Members[0].Kind()); var es = (EventDeclarationSyntax)cs.Members[0]; Assert.Equal(0, es.AttributeLists.Count); Assert.Equal(0, es.Modifiers.Count); Assert.NotEqual(default, es.EventKeyword); Assert.NotNull(es.Type); Assert.Equal("b", es.Type.ToString()); Assert.NotEqual(default, es.Identifier); Assert.Equal("c", es.Identifier.ToString()); Assert.NotEqual(default, es.AccessorList.OpenBraceToken); Assert.NotEqual(default, es.AccessorList.CloseBraceToken); Assert.Equal(2, es.AccessorList.Accessors.Count); Assert.Equal(0, es.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.AddKeyword, es.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[0].SemicolonToken.Kind()); Assert.Equal(0, es.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.RemoveKeyword, es.AccessorList.Accessors[1].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[1].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[1].SemicolonToken.Kind()); } private void TestClassEventPropertyWithModifier(SyntaxKind mod) { var text = "class a { " + SyntaxFacts.GetText(mod) + " event b c { add { } remove { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventDeclaration, cs.Members[0].Kind()); var es = (EventDeclarationSyntax)cs.Members[0]; Assert.Equal(0, es.AttributeLists.Count); Assert.Equal(1, es.Modifiers.Count); Assert.Equal(mod, es.Modifiers[0].Kind()); Assert.NotEqual(default, es.EventKeyword); Assert.NotNull(es.Type); Assert.Equal("b", es.Type.ToString()); Assert.NotEqual(default, es.Identifier); Assert.Equal("c", es.Identifier.ToString()); Assert.NotEqual(default, es.AccessorList.OpenBraceToken); Assert.NotEqual(default, es.AccessorList.CloseBraceToken); Assert.Equal(2, es.AccessorList.Accessors.Count); Assert.Equal(0, es.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.AddKeyword, es.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[0].SemicolonToken.Kind()); Assert.Equal(0, es.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.RemoveKeyword, es.AccessorList.Accessors[1].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[1].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[1].SemicolonToken.Kind()); } [Fact] public void TestClassEventPropertyWithModifiers() { TestClassEventPropertyWithModifier(SyntaxKind.PublicKeyword); TestClassEventPropertyWithModifier(SyntaxKind.PrivateKeyword); TestClassEventPropertyWithModifier(SyntaxKind.ProtectedKeyword); TestClassEventPropertyWithModifier(SyntaxKind.InternalKeyword); TestClassEventPropertyWithModifier(SyntaxKind.StaticKeyword); TestClassEventPropertyWithModifier(SyntaxKind.AbstractKeyword); TestClassEventPropertyWithModifier(SyntaxKind.VirtualKeyword); TestClassEventPropertyWithModifier(SyntaxKind.OverrideKeyword); } private void TestClassEventPropertyWithAccessorModifier(SyntaxKind mod) { var text = "class a { event b c { " + SyntaxFacts.GetText(mod) + " add { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.PropertyDeclaration, cs.Members[0].Kind()); var ps = (PropertyDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(1, ps.Modifiers.Count); Assert.Equal(SyntaxKind.EventKeyword, ps.Modifiers[0].Kind()); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.Identifier); Assert.Equal("c", ps.Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(1, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(1, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.Equal(mod, ps.AccessorList.Accessors[0].Modifiers[0].Kind()); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.AddKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(ps.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, ps.AccessorList.Accessors[0].SemicolonToken.Kind()); } [Fact] public void TestClassEventPropertyWithAccessorModifiers() { TestClassEventPropertyWithModifier(SyntaxKind.PublicKeyword); TestClassEventPropertyWithModifier(SyntaxKind.PrivateKeyword); TestClassEventPropertyWithModifier(SyntaxKind.ProtectedKeyword); TestClassEventPropertyWithModifier(SyntaxKind.InternalKeyword); TestClassEventPropertyWithModifier(SyntaxKind.AbstractKeyword); TestClassEventPropertyWithModifier(SyntaxKind.VirtualKeyword); TestClassEventPropertyWithModifier(SyntaxKind.OverrideKeyword); TestClassEventPropertyWithModifier(SyntaxKind.NewKeyword); TestClassEventPropertyWithModifier(SyntaxKind.SealedKeyword); } [Fact] public void TestClassEventPropertyExplicit() { var text = "class a { event b I.c { add { } remove { } } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.EventDeclaration, cs.Members[0].Kind()); var es = (EventDeclarationSyntax)cs.Members[0]; Assert.Equal(0, es.AttributeLists.Count); Assert.Equal(0, es.Modifiers.Count); Assert.NotEqual(default, es.EventKeyword); Assert.NotNull(es.Type); Assert.Equal("b", es.Type.ToString()); Assert.NotEqual(default, es.Identifier); Assert.NotNull(es.ExplicitInterfaceSpecifier); Assert.Equal("I", es.ExplicitInterfaceSpecifier.Name.ToString()); Assert.Equal("c", es.Identifier.ToString()); Assert.NotEqual(default, es.AccessorList.OpenBraceToken); Assert.NotEqual(default, es.AccessorList.CloseBraceToken); Assert.Equal(2, es.AccessorList.Accessors.Count); Assert.Equal(0, es.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.AddKeyword, es.AccessorList.Accessors[0].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[0].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[0].SemicolonToken.Kind()); Assert.Equal(0, es.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, es.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, es.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.RemoveKeyword, es.AccessorList.Accessors[1].Keyword.Kind()); Assert.NotNull(es.AccessorList.Accessors[1].Body); Assert.Equal(SyntaxKind.None, es.AccessorList.Accessors[1].SemicolonToken.Kind()); } [Fact] public void TestClassIndexer() { var text = "class a { b this[c d] { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.ThisKeyword); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassIndexerWithRefReturn() { var text = "class a { ref b this[c d] { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("ref b", ps.Type.ToString()); Assert.NotEqual(default, ps.ThisKeyword); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [CompilerTrait(CompilerFeature.ReadOnlyReferences)] [Fact] public void TestClassIndexerWithRefReadonlyReturn() { var text = "class a { ref readonly b this[c d] { get; set; } }"; var file = this.ParseFile(text, TestOptions.Regular); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("ref readonly b", ps.Type.ToString()); Assert.NotEqual(default, ps.ThisKeyword); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassIndexerWithMultipleParameters() { var text = "class a { b this[c d, e f] { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotEqual(default, ps.ThisKeyword); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(2, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ps.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[1].Type); Assert.Equal("e", ps.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ps.ParameterList.Parameters[1].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } [Fact] public void TestClassIndexerExplicit() { var text = "class a { b I.this[c d] { get; set; } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.IndexerDeclaration, cs.Members[0].Kind()); var ps = (IndexerDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.Type); Assert.Equal("b", ps.Type.ToString()); Assert.NotNull(ps.ExplicitInterfaceSpecifier); Assert.Equal("I", ps.ExplicitInterfaceSpecifier.Name.ToString()); Assert.Equal(".", ps.ExplicitInterfaceSpecifier.DotToken.ToString()); Assert.Equal("this", ps.ThisKeyword.ToString()); Assert.NotNull(ps.ParameterList); // used with indexer property Assert.NotEqual(default, ps.ParameterList.OpenBracketToken); Assert.Equal(SyntaxKind.OpenBracketToken, ps.ParameterList.OpenBracketToken.Kind()); Assert.NotEqual(default, ps.ParameterList.CloseBracketToken); Assert.Equal(SyntaxKind.CloseBracketToken, ps.ParameterList.CloseBracketToken.Kind()); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.NotEqual(default, ps.AccessorList.OpenBraceToken); Assert.NotEqual(default, ps.AccessorList.CloseBraceToken); Assert.Equal(2, ps.AccessorList.Accessors.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[0].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[0].Keyword); Assert.Equal(SyntaxKind.GetKeyword, ps.AccessorList.Accessors[0].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[0].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[0].SemicolonToken); Assert.Equal(0, ps.AccessorList.Accessors[1].AttributeLists.Count); Assert.Equal(0, ps.AccessorList.Accessors[1].Modifiers.Count); Assert.NotEqual(default, ps.AccessorList.Accessors[1].Keyword); Assert.Equal(SyntaxKind.SetKeyword, ps.AccessorList.Accessors[1].Keyword.Kind()); Assert.Null(ps.AccessorList.Accessors[1].Body); Assert.NotEqual(default, ps.AccessorList.Accessors[1].SemicolonToken); } private void TestClassBinaryOperatorMethod(SyntaxKind op1) { var text = "class a { b operator " + SyntaxFacts.GetText(op1) + " (c d, e f) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.OperatorDeclaration, cs.Members[0].Kind()); var ps = (OperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.ReturnType); Assert.Equal("b", ps.ReturnType.ToString()); Assert.NotEqual(default, ps.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ps.OperatorKeyword.Kind()); Assert.NotEqual(default, ps.OperatorToken); Assert.Equal(op1, ps.OperatorToken.Kind()); Assert.NotEqual(default, ps.ParameterList.OpenParenToken); Assert.NotEqual(default, ps.ParameterList.CloseParenToken); Assert.NotNull(ps.Body); Assert.Equal(2, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ps.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[1].Type); Assert.Equal("e", ps.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ps.ParameterList.Parameters[1].Identifier.ToString()); } [Fact] public void TestClassBinaryOperatorMethods() { TestClassBinaryOperatorMethod(SyntaxKind.PlusToken); TestClassBinaryOperatorMethod(SyntaxKind.MinusToken); TestClassBinaryOperatorMethod(SyntaxKind.AsteriskToken); TestClassBinaryOperatorMethod(SyntaxKind.SlashToken); TestClassBinaryOperatorMethod(SyntaxKind.PercentToken); TestClassBinaryOperatorMethod(SyntaxKind.CaretToken); TestClassBinaryOperatorMethod(SyntaxKind.AmpersandToken); TestClassBinaryOperatorMethod(SyntaxKind.BarToken); // TestClassBinaryOperatorMethod(SyntaxKind.AmpersandAmpersandToken); // TestClassBinaryOperatorMethod(SyntaxKind.BarBarToken); TestClassBinaryOperatorMethod(SyntaxKind.LessThanToken); TestClassBinaryOperatorMethod(SyntaxKind.LessThanEqualsToken); TestClassBinaryOperatorMethod(SyntaxKind.LessThanLessThanToken); TestClassBinaryOperatorMethod(SyntaxKind.GreaterThanToken); TestClassBinaryOperatorMethod(SyntaxKind.GreaterThanEqualsToken); TestClassBinaryOperatorMethod(SyntaxKind.EqualsEqualsToken); TestClassBinaryOperatorMethod(SyntaxKind.ExclamationEqualsToken); } [Fact] public void TestClassRightShiftOperatorMethod() { var text = "class a { b operator >> (c d, e f) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.OperatorDeclaration, cs.Members[0].Kind()); var ps = (OperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.ReturnType); Assert.Equal("b", ps.ReturnType.ToString()); Assert.NotEqual(default, ps.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ps.OperatorKeyword.Kind()); Assert.NotEqual(default, ps.OperatorToken); Assert.Equal(SyntaxKind.GreaterThanGreaterThanToken, ps.OperatorToken.Kind()); Assert.NotEqual(default, ps.ParameterList.OpenParenToken); Assert.NotEqual(default, ps.ParameterList.CloseParenToken); Assert.NotNull(ps.Body); Assert.Equal(2, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); Assert.Equal(0, ps.ParameterList.Parameters[1].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[1].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[1].Type); Assert.Equal("e", ps.ParameterList.Parameters[1].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[1].Identifier); Assert.Equal("f", ps.ParameterList.Parameters[1].Identifier.ToString()); } private void TestClassUnaryOperatorMethod(SyntaxKind op1) { var text = "class a { b operator " + SyntaxFacts.GetText(op1) + " (c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.OperatorDeclaration, cs.Members[0].Kind()); var ps = (OperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ps.AttributeLists.Count); Assert.Equal(0, ps.Modifiers.Count); Assert.NotNull(ps.ReturnType); Assert.Equal("b", ps.ReturnType.ToString()); Assert.NotEqual(default, ps.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ps.OperatorKeyword.Kind()); Assert.NotEqual(default, ps.OperatorToken); Assert.Equal(op1, ps.OperatorToken.Kind()); Assert.NotEqual(default, ps.ParameterList.OpenParenToken); Assert.NotEqual(default, ps.ParameterList.CloseParenToken); Assert.NotNull(ps.Body); Assert.Equal(1, ps.ParameterList.Parameters.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ps.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ps.ParameterList.Parameters[0].Type); Assert.Equal("c", ps.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ps.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ps.ParameterList.Parameters[0].Identifier.ToString()); } [Fact] public void TestClassUnaryOperatorMethods() { TestClassUnaryOperatorMethod(SyntaxKind.PlusToken); TestClassUnaryOperatorMethod(SyntaxKind.MinusToken); TestClassUnaryOperatorMethod(SyntaxKind.TildeToken); TestClassUnaryOperatorMethod(SyntaxKind.ExclamationToken); TestClassUnaryOperatorMethod(SyntaxKind.PlusPlusToken); TestClassUnaryOperatorMethod(SyntaxKind.MinusMinusToken); TestClassUnaryOperatorMethod(SyntaxKind.TrueKeyword); TestClassUnaryOperatorMethod(SyntaxKind.FalseKeyword); } [Fact] public void TestClassImplicitConversionOperatorMethod() { var text = "class a { implicit operator b (c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ConversionOperatorDeclaration, cs.Members[0].Kind()); var ms = (ConversionOperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotEqual(default, ms.ImplicitOrExplicitKeyword); Assert.Equal(SyntaxKind.ImplicitKeyword, ms.ImplicitOrExplicitKeyword.Kind()); Assert.NotEqual(default, ms.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ms.OperatorKeyword.Kind()); Assert.NotNull(ms.Type); Assert.Equal("b", ms.Type.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); } [Fact] public void TestClassExplicitConversionOperatorMethod() { var text = "class a { explicit operator b (c d) { } }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(text, file.ToString()); Assert.Equal(0, file.Errors().Length); Assert.Equal(SyntaxKind.ClassDeclaration, file.Members[0].Kind()); var cs = (TypeDeclarationSyntax)file.Members[0]; Assert.Equal(0, cs.AttributeLists.Count); Assert.Equal(0, cs.Modifiers.Count); Assert.NotEqual(default, cs.Keyword); Assert.Equal(SyntaxKind.ClassKeyword, cs.Keyword.Kind()); Assert.NotEqual(default, cs.Identifier); Assert.Equal("a", cs.Identifier.ToString()); Assert.Null(cs.BaseList); Assert.Equal(0, cs.ConstraintClauses.Count); Assert.NotEqual(default, cs.OpenBraceToken); Assert.NotEqual(default, cs.CloseBraceToken); Assert.Equal(1, cs.Members.Count); Assert.Equal(SyntaxKind.ConversionOperatorDeclaration, cs.Members[0].Kind()); var ms = (ConversionOperatorDeclarationSyntax)cs.Members[0]; Assert.Equal(0, ms.AttributeLists.Count); Assert.Equal(0, ms.Modifiers.Count); Assert.NotEqual(default, ms.ImplicitOrExplicitKeyword); Assert.Equal(SyntaxKind.ExplicitKeyword, ms.ImplicitOrExplicitKeyword.Kind()); Assert.NotEqual(default, ms.OperatorKeyword); Assert.Equal(SyntaxKind.OperatorKeyword, ms.OperatorKeyword.Kind()); Assert.NotNull(ms.Type); Assert.Equal("b", ms.Type.ToString()); Assert.NotEqual(default, ms.ParameterList.OpenParenToken); Assert.NotEqual(default, ms.ParameterList.CloseParenToken); Assert.Equal(1, ms.ParameterList.Parameters.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].AttributeLists.Count); Assert.Equal(0, ms.ParameterList.Parameters[0].Modifiers.Count); Assert.NotNull(ms.ParameterList.Parameters[0].Type); Assert.Equal("c", ms.ParameterList.Parameters[0].Type.ToString()); Assert.NotEqual(default, ms.ParameterList.Parameters[0].Identifier); Assert.Equal("d", ms.ParameterList.Parameters[0].Identifier.ToString()); } [Fact] public void TestNamespaceDeclarationsBadNames() { var text = "namespace A::B { }"; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(0, file.Errors().Length); Assert.Equal(text, file.ToString()); var ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.Equal(0, ns.Errors().Length); Assert.Equal(SyntaxKind.AliasQualifiedName, ns.Name.Kind()); text = "namespace A<B> { }"; file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(0, file.Errors().Length); Assert.Equal(text, file.ToString()); ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.Equal(0, ns.Errors().Length); Assert.Equal(SyntaxKind.GenericName, ns.Name.Kind()); text = "namespace A<,> { }"; file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(0, file.Errors().Length); Assert.Equal(text, file.ToString()); ns = (NamespaceDeclarationSyntax)file.Members[0]; Assert.Equal(0, ns.Errors().Length); Assert.Equal(SyntaxKind.GenericName, ns.Name.Kind()); } [Fact] public void TestNamespaceDeclarationsBadNames1() { var text = @"namespace A::B { }"; CreateCompilation(text).VerifyDiagnostics( // (1,11): error CS7000: Unexpected use of an aliased name // namespace A::B { } Diagnostic(ErrorCode.ERR_UnexpectedAliasedName, "A::B").WithLocation(1, 11)); } [Fact] public void TestNamespaceDeclarationsBadNames2() { var text = @"namespace A<B> { }"; CreateCompilation(text).VerifyDiagnostics( // (1,11): error CS7002: Unexpected use of a generic name // namespace A<B> { } Diagnostic(ErrorCode.ERR_UnexpectedGenericName, "A<B>").WithLocation(1, 11)); } [Fact] public void TestNamespaceDeclarationsBadNames3() { var text = @"namespace A<,> { }"; CreateCompilation(text).VerifyDiagnostics( // (1,11): error CS7002: Unexpected use of a generic name // namespace A<,> { } Diagnostic(ErrorCode.ERR_UnexpectedGenericName, "A<,>").WithLocation(1, 11)); } [WorkItem(537690, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537690")] [Fact] public void TestMissingSemicolonAfterListInitializer() { var text = @"using System; using System.Linq; class Program { static void Main() { var r = new List<int>() { 3, 3 } var s = 2; } } "; var file = this.ParseFile(text); Assert.Equal(1, file.Errors().Length); Assert.Equal((int)ErrorCode.ERR_SemicolonExpected, file.Errors()[0].Code); } [Fact] public void TestPartialPartial() { var text = @" partial class PartialPartial { int i = 1; partial partial void PM(); partial partial void PM() { i = 0; } static int Main() { PartialPartial t = new PartialPartial(); t.PM(); return t.i; } } "; // These errors aren't great. Ideally we can improve things in the future. CreateCompilation(text).VerifyDiagnostics( // (5,13): error CS1525: Invalid expression term 'partial' // partial partial void PM(); Diagnostic(ErrorCode.ERR_InvalidExprTerm, "partial").WithArguments("partial").WithLocation(5, 13), // (5,13): error CS1002: ; expected // partial partial void PM(); Diagnostic(ErrorCode.ERR_SemicolonExpected, "partial").WithLocation(5, 13), // (6,13): error CS1525: Invalid expression term 'partial' // partial partial void PM() Diagnostic(ErrorCode.ERR_InvalidExprTerm, "partial").WithArguments("partial").WithLocation(6, 13), // (6,13): error CS1002: ; expected // partial partial void PM() Diagnostic(ErrorCode.ERR_SemicolonExpected, "partial").WithLocation(6, 13), // (6,13): error CS0102: The type 'PartialPartial' already contains a definition for '' // partial partial void PM() Diagnostic(ErrorCode.ERR_DuplicateNameInClass, "").WithArguments("PartialPartial", "").WithLocation(6, 13), // (5,5): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // partial partial void PM(); Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(5, 5), // (6,5): error CS0246: The type or namespace name 'partial' could not be found (are you missing a using directive or an assembly reference?) // partial partial void PM() Diagnostic(ErrorCode.ERR_SingleTypeNameNotFound, "partial").WithArguments("partial").WithLocation(6, 5)); } [Fact] public void TestPartialEnum() { var text = @"partial enum E{}"; CreateCompilationWithMscorlib45(text).VerifyDiagnostics( // (1,1): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'struct', 'interface', or 'void' // partial enum E{} Diagnostic(ErrorCode.ERR_PartialMisplaced, "partial").WithLocation(1, 1), // (1,14): error CS0267: The 'partial' modifier can only appear immediately before 'class', 'struct', 'interface', or 'void' // partial enum E{} Diagnostic(ErrorCode.ERR_PartialMisplaced, "E").WithLocation(1, 14)); } [WorkItem(539120, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/539120")] [Fact] public void TestEscapedConstructor() { var text = @" class @class { public @class() { } } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [WorkItem(536956, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/536956")] [Fact] public void TestAnonymousMethodWithDefaultParameter() { var text = @" delegate void F(int x); class C { void M() { F f = delegate (int x = 0) { }; } } "; var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(0, file.Errors().Length); CreateCompilation(text).VerifyDiagnostics( // (5,28): error CS1065: Default values are not valid in this context. // F f = delegate (int x = 0) { }; Diagnostic(ErrorCode.ERR_DefaultValueNotAllowed, "=").WithLocation(5, 28)); } [WorkItem(537865, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537865")] [Fact] public void RegressIfDevTrueUnicode() { var text = @" class P { static void Main() { #if tru\u0065 System.Console.WriteLine(""Good, backwards compatible""); #else System.Console.WriteLine(""Bad, breaking change""); #endif } } "; TestConditionalCompilation(text, desiredText: "Good", undesiredText: "Bad"); } [WorkItem(537815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537815")] [Fact] public void RegressLongDirectiveIdentifierDefn() { var text = @" //130 chars (max is 128) #define A234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 class P { static void Main() { //first 128 chars of defined value #if A2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678 System.Console.WriteLine(""Good, backwards compatible""); #else System.Console.WriteLine(""Bad, breaking change""); #endif } } "; TestConditionalCompilation(text, desiredText: "Good", undesiredText: "Bad"); } [WorkItem(537815, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/537815")] [Fact] public void RegressLongDirectiveIdentifierUse() { var text = @" //128 chars (max) #define A2345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678 class P { static void Main() { //defined value + two chars (larger than max) #if A234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890123456789012345678901234567890 System.Console.WriteLine(""Good, backwards compatible""); #else System.Console.WriteLine(""Bad, breaking change""); #endif } } "; TestConditionalCompilation(text, desiredText: "Good", undesiredText: "Bad"); } //Expects a single class, containing a single method, containing a single statement. //Presumably, the statement depends on a conditional compilation directive. private void TestConditionalCompilation(string text, string desiredText, string undesiredText) { var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Members.Count); Assert.Equal(0, file.Errors().Length); Assert.Equal(text, file.ToFullString()); var @class = (TypeDeclarationSyntax)file.Members[0]; var mainMethod = (MethodDeclarationSyntax)@class.Members[0]; Assert.NotNull(mainMethod.Body); Assert.Equal(1, mainMethod.Body.Statements.Count); var statement = mainMethod.Body.Statements[0]; var stmtText = statement.ToString(); //make sure we compiled out the right statement Assert.Contains(desiredText, stmtText, StringComparison.Ordinal); Assert.DoesNotContain(undesiredText, stmtText, StringComparison.Ordinal); } private void TestError(string text, ErrorCode error) { var file = this.ParseFile(text); Assert.NotNull(file); Assert.Equal(1, file.Errors().Length); Assert.Equal(error, (ErrorCode)file.Errors()[0].Code); } [Fact] public void TestBadlyPlacedParams() { var text1 = @" class C { void M(params int[] i, int j) {} }"; var text2 = @" class C { void M(__arglist, int j) {} }"; CreateCompilation(text1).VerifyDiagnostics( // (4,11): error CS0231: A params parameter must be the last parameter in a formal parameter list // void M(params int[] i, int j) {} Diagnostic(ErrorCode.ERR_ParamsLast, "params int[] i").WithLocation(4, 11)); CreateCompilation(text2).VerifyDiagnostics( // (4,11): error CS0257: An __arglist parameter must be the last parameter in a formal parameter list // void M(__arglist, int j) {} Diagnostic(ErrorCode.ERR_VarargsLast, "__arglist").WithLocation(4, 11)); } [Fact] public void ValidFixedBufferTypes() { var text = @" unsafe struct s { public fixed bool _Type1[10]; internal fixed int _Type3[10]; private fixed short _Type4[10]; unsafe fixed long _Type5[10]; new fixed char _Type6[10]; } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void ValidFixedBufferTypesMultipleDeclarationsOnSameLine() { var text = @" unsafe struct s { public fixed bool _Type1[10], _Type2[10], _Type3[20]; } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void ValidFixedBufferTypesWithCountFromConstantOrLiteral() { var text = @" unsafe struct s { public const int abc = 10; public fixed bool _Type1[abc]; public fixed bool _Type2[20]; } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void ValidFixedBufferTypesAllValidTypes() { var text = @" unsafe struct s { public fixed bool _Type1[10]; public fixed byte _Type12[10]; public fixed int _Type2[10]; public fixed short _Type3[10]; public fixed long _Type4[10]; public fixed char _Type5[10]; public fixed sbyte _Type6[10]; public fixed ushort _Type7[10]; public fixed uint _Type8[10]; public fixed ulong _Type9[10]; public fixed float _Type10[10]; public fixed double _Type11[10]; } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void CS0071_01() { UsingTree(@" public interface I2 { } public interface I1 { event System.Action I2.P10; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I2"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I1"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.EventDeclaration); { N(SyntaxKind.EventKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Action"); } } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I2"); } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "P10"); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void CS0071_02() { UsingTree(@" public interface I2 { } public interface I1 { event System.Action I2. P10; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I2"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I1"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.EventDeclaration); { N(SyntaxKind.EventKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Action"); } } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I2"); } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "P10"); N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void CS0071_03() { UsingTree(@" public interface I2 { } public interface I1 { event System.Action I2. P10 } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I2"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I1"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.EventDeclaration); { N(SyntaxKind.EventKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Action"); } } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I2"); } N(SyntaxKind.DotToken); } M(SyntaxKind.IdentifierToken); M(SyntaxKind.AccessorList); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "P10"); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void CS0071_04() { UsingTree(@" public interface I2 { } public interface I1 { event System.Action I2.P10 } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I2"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.InterfaceDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.InterfaceKeyword); N(SyntaxKind.IdentifierToken, "I1"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.EventDeclaration); { N(SyntaxKind.EventKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "System"); } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Action"); } } N(SyntaxKind.ExplicitInterfaceSpecifier); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "I2"); } N(SyntaxKind.DotToken); } N(SyntaxKind.IdentifierToken, "P10"); M(SyntaxKind.AccessorList); { M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] [WorkItem(4826, "https://github.com/dotnet/roslyn/pull/4826")] public void NonAccessorAfterIncompleteProperty() { UsingTree(@" class C { int A { get { return this. public int B; } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.GetAccessorDeclaration); { N(SyntaxKind.GetKeyword); N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ReturnStatement); { N(SyntaxKind.ReturnKeyword); N(SyntaxKind.SimpleMemberAccessExpression); { N(SyntaxKind.ThisExpression); { N(SyntaxKind.ThisKeyword); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } M(SyntaxKind.SemicolonToken); } M(SyntaxKind.CloseBraceToken); } } M(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.FieldDeclaration); { N(SyntaxKind.PublicKeyword); N(SyntaxKind.VariableDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.VariableDeclarator); { N(SyntaxKind.IdentifierToken, "B"); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TupleArgument01() { var text = @" class C1 { static (T, T) Test1<T>(int a, (byte, byte) arg0) { return default((T, T)); } static (T, T) Test2<T>(ref (byte, byte) arg0) { return default((T, T)); } } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] public void TupleArgument02() { var text = @" class C1 { static (T, T) Test3<T>((byte, byte) arg0) { return default((T, T)); } (T, T) Test3<T>((byte a, byte b)[] arg0) { return default((T, T)); } } "; var file = this.ParseFile(text); Assert.Equal(0, file.Errors().Length); } [Fact] [WorkItem(13578, "https://github.com/dotnet/roslyn/issues/13578")] [CompilerTrait(CompilerFeature.ExpressionBody)] public void ExpressionBodiedCtorDtorProp() { UsingTree(@" class C { C() : base() => M(); C() => M(); ~C() => M(); int P { set => M(); } } "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ConstructorDeclaration); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.BaseConstructorInitializer); { N(SyntaxKind.ColonToken); N(SyntaxKind.BaseKeyword); N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.ConstructorDeclaration); { N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.DestructorDeclaration); { N(SyntaxKind.TildeToken); N(SyntaxKind.IdentifierToken); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.PropertyDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } N(SyntaxKind.IdentifierToken); N(SyntaxKind.AccessorList); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.SetAccessorDeclaration); { N(SyntaxKind.SetKeyword); N(SyntaxKind.ArrowExpressionClause); { N(SyntaxKind.EqualsGreaterThanToken); N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } } [Fact] public void ParseOutVar() { var tree = UsingTree(@" class C { void Goo() { M(out var x); } }", options: TestOptions.Regular.WithTuplesFeature()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.OpenBraceToken); N(SyntaxKind.MethodDeclaration); { N(SyntaxKind.PredefinedType); { N(SyntaxKind.VoidKeyword); } N(SyntaxKind.IdentifierToken, "Goo"); N(SyntaxKind.ParameterList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.CloseParenToken); } N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.ExpressionStatement); { N(SyntaxKind.InvocationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "M"); } N(SyntaxKind.ArgumentList); { N(SyntaxKind.OpenParenToken); N(SyntaxKind.Argument); { N(SyntaxKind.OutKeyword); N(SyntaxKind.DeclarationExpression); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "var"); } N(SyntaxKind.SingleVariableDesignation); { N(SyntaxKind.IdentifierToken, "x"); } } } N(SyntaxKind.CloseParenToken); } } N(SyntaxKind.SemicolonToken); } N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TestPartiallyWrittenConstraintClauseInBaseList1() { var tree = UsingTree(@" class C<T> : where "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "where"); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TestPartiallyWrittenConstraintClauseInBaseList2() { var tree = UsingTree(@" class C<T> : where T "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "where"); } } M(SyntaxKind.CommaToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TestPartiallyWrittenConstraintClauseInBaseList3() { var tree = UsingTree(@" class C<T> : where T : "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); M(SyntaxKind.SimpleBaseType); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); M(SyntaxKind.TypeConstraint); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void TestPartiallyWrittenConstraintClauseInBaseList4() { var tree = UsingTree(@" class C<T> : where T : X "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); M(SyntaxKind.SimpleBaseType); { M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.TypeConstraint); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Properties_Ref_Get() { var code = @" class Program { public int P { ref get => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,13): error CS0106: The modifier 'ref' is not valid for this item // ref get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("ref").WithLocation(6, 13)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Properties_Ref_Get_SecondModifier() { var code = @" class Program { public int P { abstract ref get => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,22): error CS0106: The modifier 'abstract' is not valid for this item // abstract ref get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("abstract").WithLocation(6, 22), // (6,22): error CS0106: The modifier 'ref' is not valid for this item // abstract ref get => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "get").WithArguments("ref").WithLocation(6, 22)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Properties_Ref_Set() { var code = @" class Program { public int P { ref set => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,13): error CS0106: The modifier 'ref' is not valid for this item // ref set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("ref").WithLocation(6, 13)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Properties_Ref_Set_SecondModifier() { var code = @" class Program { public int P { abstract ref set => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,22): error CS0106: The modifier 'abstract' is not valid for this item // abstract ref set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("abstract").WithLocation(6, 22), // (6,22): error CS0106: The modifier 'ref' is not valid for this item // abstract ref set => throw null; Diagnostic(ErrorCode.ERR_BadMemberFlag, "set").WithArguments("ref").WithLocation(6, 22)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Events_Ref() { var code = @" public class Program { event System.EventHandler E { ref add => throw null; ref remove => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,9): error CS1609: Modifiers cannot be placed on event accessor declarations // ref add => throw null; Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "ref").WithLocation(6, 9), // (7,9): error CS1609: Modifiers cannot be placed on event accessor declarations // ref remove => throw null; Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "ref").WithLocation(7, 9)); } [Fact] [WorkItem(23833, "https://github.com/dotnet/roslyn/issues/23833")] public void ProduceErrorsOnRef_Events_Ref_SecondModifier() { var code = @" public class Program { event System.EventHandler E { abstract ref add => throw null; abstract ref remove => throw null; } }"; CreateCompilation(code).VerifyDiagnostics( // (6,9): error CS1609: Modifiers cannot be placed on event accessor declarations // abstract ref add => throw null; Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "abstract").WithLocation(6, 9), // (7,9): error CS1609: Modifiers cannot be placed on event accessor declarations // abstract ref remove => throw null; Diagnostic(ErrorCode.ERR_NoModifiersOnAccessor, "abstract").WithLocation(7, 9)); } [Fact] public void NullableClassConstraint_01() { var tree = UsingNode(@" class C<T> where T : class {} "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_02() { var tree = UsingNode(@" class C<T> where T : struct {} "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_03() { var tree = UsingNode(@" class C<T> where T : class? {} "); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.QuestionToken); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_04() { var tree = UsingNode(@" class C<T> where T : struct? {} ", TestOptions.Regular, // (2,28): error CS1073: Unexpected token '?' // class C<T> where T : struct? {} Diagnostic(ErrorCode.ERR_UnexpectedToken, "?").WithArguments("?").WithLocation(2, 28) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); N(SyntaxKind.QuestionToken); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_05() { var tree = UsingNode(@" class C<T> where T : class? {} ", TestOptions.Regular7_3); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.QuestionToken); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void NullableClassConstraint_06() { var tree = UsingNode(@" class C<T> where T : struct? {} ", TestOptions.Regular7_3, // (2,28): error CS1073: Unexpected token '?' // class C<T> where T : struct? {} Diagnostic(ErrorCode.ERR_UnexpectedToken, "?").WithArguments("?").WithLocation(2, 28) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); N(SyntaxKind.QuestionToken); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(30102, "https://github.com/dotnet/roslyn/issues/30102")] public void IncompleteGenericInBaseList1() { var tree = UsingNode(@" class B : A<int { } ", TestOptions.Regular7_3, // (2,16): error CS1003: Syntax error, '>' expected // class B : A<int Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(">", "{").WithLocation(2, 16)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } M(SyntaxKind.GreaterThanToken); } } } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(35236, "https://github.com/dotnet/roslyn/issues/35236")] public void TestNamespaceWithDotDot1() { var text = @"namespace a..b { }"; var tree = UsingNode( text, TestOptions.Regular7_3, // (1,13): error CS1001: Identifier expected // namespace a..b { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 13)); // verify that we can roundtrip Assert.Equal(text, tree.ToFullString()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(30102, "https://github.com/dotnet/roslyn/issues/30102")] public void IncompleteGenericInBaseList2() { var tree = UsingNode(@" class B<X, Y> : A<int where X : Y { } ", TestOptions.Regular7_3, // (2,22): error CS1003: Syntax error, '>' expected // class B<X, Y> : A<int Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(">", "").WithLocation(2, 22)); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "B"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "Y"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.GenericName); { N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.TypeArgumentList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.PredefinedType); { N(SyntaxKind.IntKeyword); } M(SyntaxKind.GreaterThanToken); } } } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "X"); } N(SyntaxKind.ColonToken); N(SyntaxKind.TypeConstraint); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "Y"); } } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(30102, "https://github.com/dotnet/roslyn/issues/30102")] public void TestExtraneousColonInBaseList() { var tree = UsingNode(@" class A : B : C { } ", TestOptions.Regular7_3, // (2,13): error CS1514: { expected // class A : B : C Diagnostic(ErrorCode.ERR_LbraceExpected, ":").WithLocation(2, 13), // (2,13): error CS1513: } expected // class A : B : C Diagnostic(ErrorCode.ERR_RbraceExpected, ":").WithLocation(2, 13), // (2,13): error CS1022: Type or namespace definition, or end-of-file expected // class A : B : C Diagnostic(ErrorCode.ERR_EOFExpected, ":").WithLocation(2, 13), // (2,15): error CS0116: A namespace cannot directly contain members such as fields or methods // class A : B : C Diagnostic(ErrorCode.ERR_NamespaceUnexpected, "C").WithLocation(2, 15), // (3,1): error CS8652: The feature 'top-level statements' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // { Diagnostic(ErrorCode.ERR_FeatureInPreview, @"{ }").WithArguments("top-level statements").WithLocation(3, 1), // (3,1): error CS8803: Top-level statements must precede namespace and type declarations. // { Diagnostic(ErrorCode.ERR_TopLevelStatementAfterNamespaceOrType, @"{ }").WithLocation(3, 1) ); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "A"); N(SyntaxKind.BaseList); { N(SyntaxKind.ColonToken); N(SyntaxKind.SimpleBaseType); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "B"); } } } M(SyntaxKind.OpenBraceToken); M(SyntaxKind.CloseBraceToken); } N(SyntaxKind.IncompleteMember); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "C"); } } N(SyntaxKind.GlobalStatement); { N(SyntaxKind.Block); { N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(35236, "https://github.com/dotnet/roslyn/issues/35236")] public void TestNamespaceWithDotDot2() { var text = @"namespace a ..b { }"; var tree = UsingNode( text, TestOptions.Regular7_3, // (2,22): error CS1001: Identifier expected // ..b { } Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(2, 22)); // verify that we can roundtrip Assert.Equal(text, tree.ToFullString()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(35236, "https://github.com/dotnet/roslyn/issues/35236")] public void TestNamespaceWithDotDot3() { var text = @"namespace a.. b { }"; var tree = UsingNode( text, TestOptions.Regular7_3, // (1,13): error CS1001: Identifier expected // namespace a.. Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(1, 13)); // verify that we can roundtrip Assert.Equal(text, tree.ToFullString()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact, WorkItem(35236, "https://github.com/dotnet/roslyn/issues/35236")] public void TestNamespaceWithDotDot4() { var text = @"namespace a .. b { }"; var tree = UsingNode( text, TestOptions.Regular7_3, // (2,22): error CS1001: Identifier expected // .. Diagnostic(ErrorCode.ERR_IdentifierExpected, ".").WithLocation(2, 22)); // verify that we can roundtrip Assert.Equal(text, tree.ToFullString()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.NamespaceDeclaration); { N(SyntaxKind.NamespaceKeyword); N(SyntaxKind.QualifiedName); { N(SyntaxKind.QualifiedName); { N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "a"); } N(SyntaxKind.DotToken); M(SyntaxKind.IdentifierName); { M(SyntaxKind.IdentifierToken); } } N(SyntaxKind.DotToken); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "b"); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Theory] [CombinatorialData] public void DefaultConstraint_01(bool useCSharp8) { UsingNode( @"class C<T> where T : default { }", useCSharp8 ? TestOptions.Regular8 : TestOptions.RegularPreview, useCSharp8 ? new[] { // (1,22): error CS8652: The feature 'default type parameter constraints' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // class C<T> where T : default { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "default").WithArguments("default type parameter constraints").WithLocation(1, 22) } : Array.Empty<DiagnosticDescription>()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DefaultConstraint_02() { UsingNode( @"class C<T, U> where T : default where U : default { }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Theory] [CombinatorialData] public void DefaultConstraint_03(bool useCSharp8) { UsingNode( @"class C<T, U> where T : struct, default where U : default, class { }", useCSharp8 ? TestOptions.Regular8 : TestOptions.RegularPreview, useCSharp8 ? new[] { // (2,23): error CS8652: The feature 'default type parameter constraints' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // where T : struct, default Diagnostic(ErrorCode.ERR_FeatureInPreview, "default").WithArguments("default type parameter constraints").WithLocation(2, 23), // (3,15): error CS8652: The feature 'default type parameter constraints' is currently in Preview and *unsupported*. To use Preview features, use the 'preview' language version. // where U : default, class { } Diagnostic(ErrorCode.ERR_FeatureInPreview, "default").WithArguments("default type parameter constraints").WithLocation(3, 15) } : Array.Empty<DiagnosticDescription>()); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } N(SyntaxKind.CommaToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } [Fact] public void DefaultConstraint_04() { UsingNode( @"class C<T, U> where T : struct default where U : default class { }"); N(SyntaxKind.CompilationUnit); { N(SyntaxKind.ClassDeclaration); { N(SyntaxKind.ClassKeyword); N(SyntaxKind.IdentifierToken, "C"); N(SyntaxKind.TypeParameterList); { N(SyntaxKind.LessThanToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.CommaToken); N(SyntaxKind.TypeParameter); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.GreaterThanToken); } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "T"); } N(SyntaxKind.ColonToken); N(SyntaxKind.StructConstraint); { N(SyntaxKind.StructKeyword); } M(SyntaxKind.CommaToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } } N(SyntaxKind.TypeParameterConstraintClause); { N(SyntaxKind.WhereKeyword); N(SyntaxKind.IdentifierName); { N(SyntaxKind.IdentifierToken, "U"); } N(SyntaxKind.ColonToken); N(SyntaxKind.DefaultConstraint); { N(SyntaxKind.DefaultKeyword); } M(SyntaxKind.CommaToken); N(SyntaxKind.ClassConstraint); { N(SyntaxKind.ClassKeyword); } } N(SyntaxKind.OpenBraceToken); N(SyntaxKind.CloseBraceToken); } N(SyntaxKind.EndOfFileToken); } EOF(); } } }
45.34488
201
0.57587
[ "MIT" ]
Jay-Madden/roslyn
src/Compilers/CSharp/Test/Syntax/Parsing/DeclarationParsingTests.cs
354,735
C#
/************************************************************************************ Copyright : Copyright (c) Facebook Technologies, LLC and its affiliates. All rights reserved. Licensed under the Oculus SDK License Version 3.4.1 (the "License"); you may not use the Oculus SDK except in compliance with the License, which is provided at the time of installation or download, or which otherwise accompanies this software in either electronic or hard copy form. You may obtain a copy of the License at https://developer.oculus.com/licenses/sdk-3.4.1 Unless required by applicable law or agreed to in writing, the Oculus SDK 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. ************************************************************************************/ //#define BUILDSESSION #if USING_XR_MANAGEMENT && USING_XR_SDK_OCULUS #define USING_XR_SDK #endif using System; using System.Collections; using System.Collections.Generic; using System.IO; using System.Xml; using System.Diagnostics; using System.Threading; using UnityEditor; using UnityEngine; using UnityEngine.Rendering; using UnityEditor.Build; using UnityEditor.Build.Reporting; #if UNITY_ANDROID using UnityEditor.Android; #endif [InitializeOnLoad] public class OVRGradleGeneration : IPreprocessBuildWithReport, IPostprocessBuildWithReport #if UNITY_ANDROID , IPostGenerateGradleAndroidProject #endif { public OVRADBTool adbTool; public Process adbProcess; public int callbackOrder { get { return 99999; } } static private System.DateTime buildStartTime; static private System.Guid buildGuid; #if UNITY_ANDROID private const string prefName = "OVRAutoIncrementVersionCode_Enabled"; private const string menuItemAutoIncVersion = "Oculus/Tools/Auto Increment Version Code"; static bool autoIncrementVersion = false; #endif static OVRGradleGeneration() { EditorApplication.delayCall += OnDelayCall; } static void OnDelayCall() { #if UNITY_ANDROID autoIncrementVersion = PlayerPrefs.GetInt(prefName, 0) != 0; Menu.SetChecked(menuItemAutoIncVersion, autoIncrementVersion); #endif } #if UNITY_ANDROID [MenuItem(menuItemAutoIncVersion)] static void ToggleUtilities() { autoIncrementVersion = !autoIncrementVersion; Menu.SetChecked(menuItemAutoIncVersion, autoIncrementVersion); int newValue = (autoIncrementVersion) ? 1 : 0; PlayerPrefs.SetInt(prefName, newValue); PlayerPrefs.Save(); UnityEngine.Debug.Log("Auto Increment Version Code: " + autoIncrementVersion); } #endif public void OnPreprocessBuild(BuildReport report) { #if UNITY_ANDROID && !(USING_XR_SDK && UNITY_2019_3_OR_NEWER) // Generate error when Vulkan is selected as the perferred graphics API, which is not currently supported in Unity XR if (!PlayerSettings.GetUseDefaultGraphicsAPIs(BuildTarget.Android)) { GraphicsDeviceType[] apis = PlayerSettings.GetGraphicsAPIs(BuildTarget.Android); if (apis.Length >= 1 && apis[0] == GraphicsDeviceType.Vulkan) { throw new BuildFailedException("The Vulkan Graphics API does not support XR in your configuration. To use Vulkan, you must use Unity 2019.3 or newer, and the XR Plugin Management."); } } #endif buildStartTime = System.DateTime.Now; buildGuid = System.Guid.NewGuid(); if (!report.summary.outputPath.Contains("OVRGradleTempExport")) { OVRPlugin.SetDeveloperMode(OVRPlugin.Bool.True); OVRPlugin.AddCustomMetadata("build_type", "standard"); } OVRPlugin.AddCustomMetadata("build_guid", buildGuid.ToString()); OVRPlugin.AddCustomMetadata("target_platform", report.summary.platform.ToString()); #if !UNITY_2019_3_OR_NEWER OVRPlugin.AddCustomMetadata("scripting_runtime_version", UnityEditor.PlayerSettings.scriptingRuntimeVersion.ToString()); #endif if (report.summary.platform == UnityEditor.BuildTarget.StandaloneWindows || report.summary.platform == UnityEditor.BuildTarget.StandaloneWindows64) { OVRPlugin.AddCustomMetadata("target_oculus_platform", "rift"); } #if BUILDSESSION StreamWriter writer = new StreamWriter("build_session", false); UnityEngine.Debug.LogFormat("Build Session: {0}", buildGuid.ToString()); writer.WriteLine(buildGuid.ToString()); writer.Close(); #endif } public void OnPostGenerateGradleAndroidProject(string path) { UnityEngine.Debug.Log("OVRGradleGeneration triggered."); var targetOculusPlatform = new List<string>(); if (OVRDeviceSelector.isTargetDeviceGearVrOrGo) { targetOculusPlatform.Add("geargo"); } if (OVRDeviceSelector.isTargetDeviceQuest) { targetOculusPlatform.Add("quest"); } OVRPlugin.AddCustomMetadata("target_oculus_platform", String.Join("_", targetOculusPlatform.ToArray())); UnityEngine.Debug.LogFormat(" GearVR or Go = {0} Quest = {1}", OVRDeviceSelector.isTargetDeviceGearVrOrGo, OVRDeviceSelector.isTargetDeviceQuest); #if UNITY_2019_3_OR_NEWER string gradleBuildPath = Path.Combine(path, "../launcher/build.gradle"); #else string gradleBuildPath = Path.Combine(path, "build.gradle"); #endif //Enable v2signing for Quest only bool v2SigningEnabled = OVRDeviceSelector.isTargetDeviceQuest && !OVRDeviceSelector.isTargetDeviceGearVrOrGo; if (File.Exists(gradleBuildPath)) { try { string gradle = File.ReadAllText(gradleBuildPath); int v2Signingindex = gradle.IndexOf("v2SigningEnabled false"); if (v2Signingindex != -1) { //v2 Signing flag found, ensure the correct value is set based on platform. if (v2SigningEnabled) { gradle = gradle.Replace("v2SigningEnabled false", "v2SigningEnabled true"); System.IO.File.WriteAllText(gradleBuildPath, gradle); } } else { //v2 Signing flag missing, add it right after the key store password and set the value based on platform. int keyPassIndex = gradle.IndexOf("keyPassword"); if (keyPassIndex != -1) { int v2Index = gradle.IndexOf("\n", keyPassIndex) + 1; if(v2Index != -1) { gradle = gradle.Insert(v2Index, "v2SigningEnabled " + (v2SigningEnabled ? "true" : "false") + "\n"); System.IO.File.WriteAllText(gradleBuildPath, gradle); } } } } catch (System.Exception e) { UnityEngine.Debug.LogWarningFormat("Unable to overwrite build.gradle, error {0}", e.Message); } } else { UnityEngine.Debug.LogWarning("Unable to locate build.gradle"); } PatchAndroidManifest(path); } public void PatchAndroidManifest(string path) { string manifestFolder = Path.Combine(path, "src/main"); string file = manifestFolder + "/AndroidManifest.xml"; bool patchedSecurityConfig = false; // If Enable NSC Config, copy XML file into gradle project OVRProjectConfig projectConfig = OVRProjectConfig.GetProjectConfig(); if (projectConfig != null) { if (projectConfig.enableNSCConfig) { // If no custom xml security path is specified, look for the default location in the integrations package. string securityConfigFile = projectConfig.securityXmlPath; if (string.IsNullOrEmpty(securityConfigFile)) { securityConfigFile = GetOculusProjectNetworkSecConfigPath(); } else { Uri configUri = new Uri(Path.GetFullPath(securityConfigFile)); Uri projectUri = new Uri(Application.dataPath); Uri relativeUri = projectUri.MakeRelativeUri(configUri); securityConfigFile = relativeUri.ToString(); } string xmlDirectory = Path.Combine(path, "src/main/res/xml"); try { if (!Directory.Exists(xmlDirectory)) { Directory.CreateDirectory(xmlDirectory); } File.Copy(securityConfigFile, Path.Combine(xmlDirectory, "network_sec_config.xml"), true); patchedSecurityConfig = true; } catch (Exception e) { UnityEngine.Debug.LogError(e.Message); } } } OVRManifestPreprocessor.PatchAndroidManifest(file, enableSecurity: patchedSecurityConfig); } private static string GetOculusProjectNetworkSecConfigPath() { var so = ScriptableObject.CreateInstance(typeof(OVRPluginUpdaterStub)); var script = MonoScript.FromScriptableObject(so); string assetPath = AssetDatabase.GetAssetPath(script); string editorDir = Directory.GetParent(assetPath).FullName; string configAssetPath = Path.GetFullPath(Path.Combine(editorDir, "network_sec_config.xml")); Uri configUri = new Uri(configAssetPath); Uri projectUri = new Uri(Application.dataPath); Uri relativeUri = projectUri.MakeRelativeUri(configUri); return relativeUri.ToString(); } public void OnPostprocessBuild(BuildReport report) { #if UNITY_ANDROID if(autoIncrementVersion) { if((report.summary.options & BuildOptions.Development) == 0) { PlayerSettings.Android.bundleVersionCode++; UnityEngine.Debug.Log("Incrementing version code to " + PlayerSettings.Android.bundleVersionCode); } } bool isExporting = true; foreach (var step in report.steps) { if (step.name.Contains("Compile scripts") || step.name.Contains("Building scenes") || step.name.Contains("Writing asset files") || step.name.Contains("Preparing APK resources") || step.name.Contains("Creating Android manifest") || step.name.Contains("Processing plugins") || step.name.Contains("Exporting project") || step.name.Contains("Building Gradle project")) { OVRPlugin.SendEvent("build_step_" + step.name.ToLower().Replace(' ', '_'), step.duration.TotalSeconds.ToString(), "ovrbuild"); #if BUILDSESSION UnityEngine.Debug.LogFormat("build_step_" + step.name.ToLower().Replace(' ', '_') + ": {0}", step.duration.TotalSeconds.ToString()); #endif if(step.name.Contains("Building Gradle project")) { isExporting = false; } } } OVRPlugin.AddCustomMetadata("build_step_count", report.steps.Length.ToString()); if (report.summary.outputPath.Contains("apk")) // Exclude Gradle Project Output { var fileInfo = new System.IO.FileInfo(report.summary.outputPath); OVRPlugin.AddCustomMetadata("build_output_size", fileInfo.Length.ToString()); } #endif if (!report.summary.outputPath.Contains("OVRGradleTempExport")) { OVRPlugin.SendEvent("build_complete", (System.DateTime.Now - buildStartTime).TotalSeconds.ToString(), "ovrbuild"); #if BUILDSESSION UnityEngine.Debug.LogFormat("build_complete: {0}", (System.DateTime.Now - buildStartTime).TotalSeconds.ToString()); #endif } #if UNITY_ANDROID if (!isExporting) { // Get the hosts path to Android SDK if (adbTool == null) { adbTool = new OVRADBTool(OVRConfig.Instance.GetAndroidSDKPath(false)); } if (adbTool.isReady) { // Check to see if there are any ADB devices connected before continuing. List<string> devices = adbTool.GetDevices(); if(devices.Count == 0) { return; } // Clear current logs on device Process adbClearProcess; adbClearProcess = adbTool.RunCommandAsync(new string[] { "logcat --clear" }, null); // Add a timeout if we cannot get a response from adb logcat --clear in time. Stopwatch timeout = new Stopwatch(); timeout.Start(); while (!adbClearProcess.WaitForExit(100)) { if (timeout.ElapsedMilliseconds > 2000) { adbClearProcess.Kill(); return; } } // Check if existing ADB process is still running, kill if needed if (adbProcess != null && !adbProcess.HasExited) { adbProcess.Kill(); } // Begin thread to time upload and install var thread = new Thread(delegate () { TimeDeploy(); }); thread.Start(); } } #endif } #if UNITY_ANDROID public bool WaitForProcess; public bool TransferStarted; public DateTime UploadStart; public DateTime UploadEnd; public DateTime InstallEnd; public void TimeDeploy() { if (adbTool != null) { TransferStarted = false; DataReceivedEventHandler outputRecieved = new DataReceivedEventHandler( (s, e) => { if (e.Data != null && e.Data.Length != 0 && !e.Data.Contains("\u001b")) { if (e.Data.Contains("free_cache")) { // Device recieved install command and is starting upload UploadStart = System.DateTime.Now; TransferStarted = true; } else if (e.Data.Contains("Running dexopt")) { // Upload has finished and Package Manager is starting install UploadEnd = System.DateTime.Now; } else if (e.Data.Contains("dex2oat took")) { // Package Manager finished install InstallEnd = System.DateTime.Now; WaitForProcess = false; } else if (e.Data.Contains("W PackageManager")) { // Warning from Package Manager is a failure in the install process WaitForProcess = false; } } } ); WaitForProcess = true; adbProcess = adbTool.RunCommandAsync(new string[] { "logcat" }, outputRecieved); Stopwatch transferTimeout = new Stopwatch(); transferTimeout.Start(); while (adbProcess != null && !adbProcess.WaitForExit(100)) { if (!WaitForProcess) { adbProcess.Kill(); float UploadTime = (float)(UploadEnd - UploadStart).TotalMilliseconds / 1000f; float InstallTime = (float)(InstallEnd - UploadEnd).TotalMilliseconds / 1000f; if (UploadTime > 0f) { OVRPlugin.SendEvent("deploy_task", UploadTime.ToString(), "ovrbuild"); } if (InstallTime > 0f) { OVRPlugin.SendEvent("install_task", InstallTime.ToString(), "ovrbuild"); } } if (!TransferStarted && transferTimeout.ElapsedMilliseconds > 5000) { adbProcess.Kill(); } } } } #endif }
31.377574
186
0.709525
[ "MIT" ]
IanPhilips/UnityOculusAndroidVRBrowser
UnityProject/Assets/Oculus/VR/Editor/OVRGradleGeneration.cs
13,712
C#
using Microsoft.Win32; namespace BatteryMax { public enum WindowsTheme { Light, Dark } public class ThemeHelper { private const string RegistryKeyPath = @"Software\Microsoft\Windows\CurrentVersion\Themes\Personalize"; private const string RegistryValueName = "SystemUsesLightTheme"; public static WindowsTheme GetWindowsTheme() { using RegistryKey key = Registry.CurrentUser.OpenSubKey(RegistryKeyPath); var registryValueObject = key?.GetValue(RegistryValueName); if (registryValueObject == null) { Log.Write("SystemUsesLightTheme is null. Assuming default light theme"); return WindowsTheme.Light; } var registryValue = (int)registryValueObject; return registryValue > 0 ? WindowsTheme.Light : WindowsTheme.Dark; } } }
27.764706
111
0.618644
[ "Apache-2.0" ]
rotvel/BatteryMax
Source/BatteryMax/ThemeHelper.cs
946
C#
using System; using System.Collections.Generic; using System.IO; using System.IO.Compression; using System.Linq; using System.Text; using System.Threading.Tasks; using Complete.IO; using Complete.IO.Zlib; namespace RiotArchive.File { /// <summary> /// Read-only file stream. This class is NOT thread safe. /// </summary> public class ArchivedFileFileStream : Stream { readonly string archiveFile; readonly int dataOffset; readonly int dataLength; readonly DecompressionMode decompressionMode; bool initialized; Stream stream; Stream zlibStream; static readonly uint ZlibCompressionMethodMask; static ArchivedFileFileStream() { ZlibCompressionMethodMask = Convert.ToUInt32("00001111", 2); } public ArchivedFileFileStream(string archiveFile, int dataOffset, int dataLength, DecompressionMode decompressionMode) { this.archiveFile = archiveFile; this.dataOffset = dataOffset; this.dataLength = dataLength; this.decompressionMode = decompressionMode; } public void Open() { if (initialized) return; initialized = true; var fileStream = new FileStream(this.archiveFile + ".dat", FileMode.Open, FileAccess.Read); stream = new SubStream(fileStream, dataOffset, dataLength); var decompress = false; switch (decompressionMode) { case DecompressionMode.DontDecompress: decompress = false; break; case DecompressionMode.Decompress: decompress = true; break; case DecompressionMode.Auto: var zlibHeader = new byte[2]; var bytesRead = stream.Read(zlibHeader, 0, 2); if (bytesRead != 2) throw new InvalidDataException(); // reset the stream position after checking header stream.Seek(0, SeekOrigin.Begin); // See http://tools.ietf.org/html/rfc1950 for zlib file format var compressionMethod = zlibHeader[0] & ZlibCompressionMethodMask; var compressionInfo = zlibHeader[0] >> 4; if (BitConverter.IsLittleEndian) Array.Reverse(zlibHeader); var hasZlibHeader = compressionMethod == 8 && compressionInfo <= 7 && BitConverter.ToUInt16(zlibHeader, 0) % 31 == 0; decompress = hasZlibHeader; break; default: throw new ArgumentOutOfRangeException("mode"); } if (decompress) zlibStream = new ZlibStream(stream, CompressionMode.Decompress); } public override void Flush() { throw new NotSupportedException(); } public override long Seek(long offset, SeekOrigin origin) { if (offset == 0 && origin == SeekOrigin.Begin) { ResetStreams(); Open(); return 0; } throw new NotSupportedException(); } public override void SetLength(long value) { throw new NotSupportedException(); } public override int Read(byte[] buffer, int offset, int count) { if (zlibStream != null) return zlibStream.Read(buffer, offset, count); return stream.Read(buffer, offset, count); } public override void Write(byte[] buffer, int offset, int count) { throw new NotSupportedException(); } public override bool CanRead { get { return true; } } public override bool CanSeek { get { return false; } } public override bool CanWrite { get { return false; } } public override long Length { get { if (stream != null && zlibStream == null) return stream.Length; throw new NotSupportedException(); } } public override long Position { get { throw new NotSupportedException(); } set { throw new NotSupportedException(); } } protected override void Dispose(bool disposing) { ResetStreams(); base.Dispose(disposing); } void ResetStreams() { if (stream != null) { stream.Dispose(); stream = null; } if (zlibStream != null) { zlibStream.Dispose(); zlibStream = null; } if (initialized) initialized = false; } } }
29.715976
137
0.527081
[ "MIT" ]
hinaria/riot-archive2
riot-archive2/File/ArchivedFileFileStream.cs
5,024
C#
using System.IO; using System.Runtime.Serialization; using GameEstate.Red.Formats.Red.CR2W.Reflection; using FastMember; using static GameEstate.Red.Formats.Red.Records.Enums; namespace GameEstate.Red.Formats.Red.Types { [DataContract(Namespace = "")] [REDMeta] public class CBehTreeCarryingItemData : CVariable { [Ordinal(1)] [RED("carriedItem")] public CHandle<CEntity> CarriedItem { get; set;} public CBehTreeCarryingItemData(CR2WFile cr2w, CVariable parent, string name) : base(cr2w, parent, name){ } public static CVariable Create(CR2WFile cr2w, CVariable parent, string name) => new CBehTreeCarryingItemData(cr2w, parent, name); public override void Read(BinaryReader file, uint size) => base.Read(file, size); public override void Write(BinaryWriter file) => base.Write(file); } }
33.4
132
0.741317
[ "MIT" ]
bclnet/GameEstate
src/Estates/Red/GameEstate.Red.Format/Red/W3/RTTIConvert/CBehTreeCarryingItemData.cs
835
C#
using System; namespace BankingApplication.Domain.Transactions { public class TransactionState { public TransactionState(Guid transactionId, Guid accountId, string description, TransactionType type, decimal amount, DateTimeOffset occurredMoment) { TransactionId = transactionId; AccountId = accountId; Description = description ?? throw new ArgumentNullException(nameof(description)); Type = type; Amount = amount; OccurredMoment = occurredMoment; } public Guid TransactionId { get; } public Guid AccountId { get; } public string Description { get; } public TransactionType Type { get; } public decimal Amount { get; } public DateTimeOffset OccurredMoment { get; } } }
33.12
156
0.64372
[ "MIT" ]
xKloc/Memoir
samples/BankingApplication/Domain/Transactions/TransactionState.cs
830
C#
using System; using System.Text; using System.Collections.Generic; using Unity.Collections; using UnityEngine.InputSystem.Layouts; using UnityEngine.InputSystem.Utilities; ////TODO: allow stuff like "/gamepad/**/<button>" ////TODO: add support for | (e.g. "<Gamepad>|<Joystick>/{PrimaryMotion}" ////TODO: handle arrays ////TODO: add method to extract control path ////REVIEW: change "*/{PrimaryAction}" to "*/**/{PrimaryAction}" so that the hierarchy crawling becomes explicit? ////REVIEW: rename to `InputPath`? namespace UnityEngine.InputSystem { /// <summary> /// Functions for working with control path specs (like "/gamepad/*stick"). /// </summary> /// <remarks> /// Control paths are a mini-language similar to regular expressions. They are used throughout /// the input system as string "addresses" of input controls. At runtime, they can be matched /// against the devices and controls present in the system to retrieve the actual endpoints to /// receive input from. /// /// Like on a file system, a path is made up of components that are each separated by a /// forward slash (<c>/</c>). Each such component in turn is made up of a set of fields that are /// individually optional. However, one of the fields must be present (e.g. at least a name or /// a wildcard). /// /// <example> /// Field structure of each path component /// <code> /// &lt;Layout&gt;{Usage}#(DisplayName)Name /// </code> /// </example> /// /// * <c>Layout</c>: The name of the layout that the control must be based on (either directly or indirectly). /// * <c>Usage</c>: The usage that the control or device has to have, i.e. must be found in <see /// cref="InputControl.usages"/> This field can be repeated several times to require /// multiple usages (e.g. <c>"{LeftHand}{Vertical}"</c>). /// * <c>DisplayName</c>: The name that <see cref="InputControl.displayName"/> of the control or device /// must match. /// * <c>Name</c>: The name that <see cref="InputControl.name"/> or one of the entries in /// <see cref="InputControl.aliases"/> must match. Alternatively, this can be a /// wildcard (<c>*</c>) to match any name. /// /// Note that all matching is case-insensitive. /// /// <example> /// Various examples of control paths /// <code> /// // Matches all gamepads (also gamepads *based* on the Gamepad layout): /// "&lt;Gamepad&gt;" /// /// // Matches the "Submit" control on all devices: /// "*/{Submit}" /// /// // Matches the key that prints the "a" character on the current keyboard layout: /// "&lt;Keyboard&gt;/#(a)" /// /// // Matches the X axis of the left stick on a gamepad. /// "&lt;Gamepad&gt;/leftStick/x" /// /// // Matches the orientation control of the right-hand XR controller: /// "&lt;XRController&gt;{RightHand}/orientation" /// /// // Matches all buttons on a gamepad. /// "&lt;Gamepad&gt;/&lt;Button&gt;" /// </code> /// </example> /// /// The structure of the API of this class is similar in spirit to <c>System.IO.Path</c>, i.e. it offers /// a range of static methods that perform various operations on path strings. /// /// To query controls on devices present in the system using control paths, use /// <see cref="InputSystem.FindControls"/>. Also, control paths can be used with /// <see cref="InputControl.this[string]"/> on every control. This makes it possible /// to do things like: /// /// <example> /// Find key that prints "t" on current keyboard: /// <code> /// Keyboard.current["#(t)"] /// </code> /// </example> /// </remarks> /// <seealso cref="InputControl.path"/> /// <seealso cref="InputSystem.FindControls"/> public static class InputControlPath { public const string Wildcard = "*"; public const string DoubleWildcard = "**"; public const char Separator = '/'; public static string Combine(InputControl parent, string path) { if (parent == null) { if (string.IsNullOrEmpty(path)) return string.Empty; if (path[0] != Separator) return Separator + path; return path; } if (string.IsNullOrEmpty(path)) return parent.path; return $"{parent.path}/{path}"; } /// <summary> /// Options for customizing the behavior of <see cref="ToHumanReadableString"/>. /// </summary> [Flags] public enum HumanReadableStringOptions { /// <summary> /// The default behavior. /// </summary> None = 0, /// <summary> /// Do not mention the device of the control. For example, instead of "A [Gamepad]", /// return just "A". /// </summary> OmitDevice = 1 << 1, /// <summary> /// When available, use short display names instead of long ones. For example, instead of "Left Button", /// return "LMB". /// </summary> UseShortNames = 1 << 2, } ////TODO: factor out the part that looks up an InputControlLayout.ControlItem from a given path //// and make that available as a stand-alone API ////TODO: add option to customize path separation character /// <summary> /// Create a human readable string from the given control path. /// </summary> /// <param name="path">A control path such as "&lt;XRController>{LeftHand}/position".</param> /// <param name="options">Customize the resulting string.</param> /// <param name="control">An optional control. If supplied and the control or one of its children /// matches the given <paramref name="path"/>, display names will be based on the matching control /// rather than on static information available from <see cref="InputControlLayout"/>s.</param> /// <returns>A string such as "Left Stick/X [Gamepad]".</returns> /// <remarks> /// This function is most useful for turning binding paths (see <see cref="InputBinding.path"/>) /// into strings that can be displayed in UIs (such as rebinding screens). It is used by /// the Unity editor itself to display binding paths in the UI. /// /// The method uses display names (see <see cref="InputControlAttribute.displayName"/>, /// <see cref="InputControlLayoutAttribute.displayName"/>, and <see cref="InputControlLayout.ControlItem.displayName"/>) /// where possible. For example, "&lt;XInputController&gt;/buttonSouth" will be returned as /// "A [Xbox Controller]" as the display name of <see cref="XInput.XInputController"/> is "XBox Controller" /// and the display name of its "buttonSouth" control is "A". /// /// Note that these lookups depend on the currently registered control layouts (see <see /// cref="InputControlLayout"/>) and different strings may thus be returned for the same control /// path depending on the layouts registered with the system. /// /// <example> /// <code> /// InputControlPath.ToHumanReadableString("*/{PrimaryAction"); // -> "PrimaryAction [Any]" /// InputControlPath.ToHumanReadableString("&lt;Gamepad&gt;/buttonSouth"); // -> "Button South [Gamepad]" /// InputControlPath.ToHumanReadableString("&lt;XInputController&gt;/buttonSouth"); // -> "A [Xbox Controller]" /// InputControlPath.ToHumanReadableString("&lt;Gamepad&gt;/leftStick/x"); // -> "Left Stick/X [Gamepad]" /// </code> /// </example> /// </remarks> /// <seealso cref="InputBinding.path"/> /// <seealso cref="InputBinding.ToDisplayString(InputBinding.DisplayStringOptions,InputControl)"/> /// <seealso cref="InputActionRebindingExtensions.GetBindingDisplayString(InputAction,int,InputBinding.DisplayStringOptions)"/> public static string ToHumanReadableString(string path, HumanReadableStringOptions options = HumanReadableStringOptions.None, InputControl control = null) { return ToHumanReadableString(path, out _, out _, options, control); } /// <summary> /// Create a human readable string from the given control path. /// </summary> /// <param name="path">A control path such as "&lt;XRController>{LeftHand}/position".</param> /// <param name="deviceLayoutName">Receives the name of the device layout that the control path was resolved to. /// This is useful </param> /// <param name="controlPath">Receives the path to the referenced control on the device or <c>null</c> if not applicable. /// For example, with a <paramref name="path"/> of <c>"&lt;Gamepad&gt;/dpad/up"</c>, the resulting control path /// will be <c>"dpad/up"</c>. This is useful when trying to look up additional resources (such as images) based on the /// control that is being referenced.</param> /// <param name="options">Customize the resulting string.</param> /// <param name="control">An optional control. If supplied and the control or one of its children /// matches the given <paramref name="path"/>, display names will be based on the matching control /// rather than on static information available from <see cref="InputControlLayout"/>s.</param> /// <returns>A string such as "Left Stick/X [Gamepad]".</returns> /// <remarks> /// This function is most useful for turning binding paths (see <see cref="InputBinding.path"/>) /// into strings that can be displayed in UIs (such as rebinding screens). It is used by /// the Unity editor itself to display binding paths in the UI. /// /// The method uses display names (see <see cref="InputControlAttribute.displayName"/>, /// <see cref="InputControlLayoutAttribute.displayName"/>, and <see cref="InputControlLayout.ControlItem.displayName"/>) /// where possible. For example, "&lt;XInputController&gt;/buttonSouth" will be returned as /// "A [Xbox Controller]" as the display name of <see cref="XInput.XInputController"/> is "XBox Controller" /// and the display name of its "buttonSouth" control is "A". /// /// Note that these lookups depend on the currently registered control layouts (see <see /// cref="InputControlLayout"/>) and different strings may thus be returned for the same control /// path depending on the layouts registered with the system. /// /// <example> /// <code> /// InputControlPath.ToHumanReadableString("*/{PrimaryAction"); // -> "PrimaryAction [Any]" /// InputControlPath.ToHumanReadableString("&lt;Gamepad&gt;/buttonSouth"); // -> "Button South [Gamepad]" /// InputControlPath.ToHumanReadableString("&lt;XInputController&gt;/buttonSouth"); // -> "A [Xbox Controller]" /// InputControlPath.ToHumanReadableString("&lt;Gamepad&gt;/leftStick/x"); // -> "Left Stick/X [Gamepad]" /// </code> /// </example> /// </remarks> /// <seealso cref="InputBinding.path"/> /// <seealso cref="InputBinding.ToDisplayString(InputBinding.DisplayStringOptions,InputControl)"/> /// <seealso cref="InputActionRebindingExtensions.GetBindingDisplayString(InputAction,int,InputBinding.DisplayStringOptions)"/> public static string ToHumanReadableString(string path, out string deviceLayoutName, out string controlPath, HumanReadableStringOptions options = HumanReadableStringOptions.None, InputControl control = null) { deviceLayoutName = null; controlPath = null; if (string.IsNullOrEmpty(path)) return string.Empty; // If we have a control, see if the path matches something in its hierarchy. If so, // don't both parsing the path and just use the matched control for creating a display // string. if (control != null) { var childControl = TryFindControl(control, path); var matchedControl = childControl ?? (Matches(path, control) ? control : null); if (matchedControl != null) { var text = (options & HumanReadableStringOptions.UseShortNames) != 0 && !string.IsNullOrEmpty(matchedControl.shortDisplayName) ? matchedControl.shortDisplayName : matchedControl.displayName; if ((options & HumanReadableStringOptions.OmitDevice) == 0) text = $"{text} [{matchedControl.device.displayName}]"; deviceLayoutName = matchedControl.device.layout; if (!(matchedControl is InputDevice)) controlPath = matchedControl.path.Substring(matchedControl.device.path.Length + 1); return text; } } var buffer = new StringBuilder(); var parser = new PathParser(path); // For display names of controls and devices, we need to look at InputControlLayouts. // If none is in place here, we establish a temporary layout cache while we go through // the path. If one is in place already, we reuse what's already there. using (InputControlLayout.CacheRef()) { // First level is taken to be device. if (parser.MoveToNextComponent()) { // Keep track of which control layout we're on (if any) as we're crawling // down the path. var device = parser.current.ToHumanReadableString(null, null, out var currentLayoutName, out var _, options); deviceLayoutName = currentLayoutName; // Any additional levels (if present) are taken to form a control path on the device. var isFirstControlLevel = true; while (parser.MoveToNextComponent()) { if (!isFirstControlLevel) buffer.Append('/'); buffer.Append(parser.current.ToHumanReadableString( currentLayoutName, controlPath, out currentLayoutName, out controlPath, options)); isFirstControlLevel = false; } if ((options & HumanReadableStringOptions.OmitDevice) == 0 && !string.IsNullOrEmpty(device)) { buffer.Append(" ["); buffer.Append(device); buffer.Append(']'); } } // If we didn't manage to figure out a display name, default to displaying // the path as is. if (buffer.Length == 0) return path; return buffer.ToString(); } } public static string[] TryGetDeviceUsages(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); var parser = new PathParser(path); if (!parser.MoveToNextComponent()) return null; if (parser.current.usages != null && parser.current.usages.Length > 0) { return Array.ConvertAll(parser.current.usages, i => { return i.ToString(); }); } return null; } /// <summary> /// From the given control path, try to determine the device layout being used. /// </summary> /// <remarks> /// This function will only use information available in the path itself or /// in layouts referenced by the path. It will not look at actual devices /// in the system. This is to make the behavior predictable and not dependent /// on whether you currently have the right device connected or not. /// </remarks> /// <param name="path">A control path (like "/&lt;gamepad&gt;/leftStick")</param> /// <returns>The name of the device layout used by the given control path or null /// if the path does not specify a device layout or does so in a way that is not /// supported by the function.</returns> /// <exception cref="ArgumentNullException"><paramref name="path"/> is null</exception> /// <example> /// <code> /// InputControlPath.TryGetDeviceLayout("/&lt;gamepad&gt;/leftStick"); // Returns "gamepad". /// InputControlPath.TryGetDeviceLayout("/*/leftStick"); // Returns "*". /// InputControlPath.TryGetDeviceLayout("/gamepad/leftStick"); // Returns null. "gamepad" is a device name here. /// </code> /// </example> public static string TryGetDeviceLayout(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); var parser = new PathParser(path); if (!parser.MoveToNextComponent()) return null; if (parser.current.layout.length > 0) return parser.current.layout.ToString(); if (parser.current.isWildcard) return Wildcard; return null; } ////TODO: return Substring and use path parser; should get rid of allocations // From the given control path, try to determine the control layout being used. // NOTE: Allocates! public static string TryGetControlLayout(string path) { if (path == null) throw new ArgumentNullException(nameof(path)); var pathLength = path.Length; var indexOfLastSlash = path.LastIndexOf('/'); if (indexOfLastSlash == -1 || indexOfLastSlash == 0) { // If there's no '/' at all in the path, it surely does not mention // a control. Same if the '/' is the first thing in the path. return null; } // Simplest case where control layout is mentioned explicitly with '<..>'. // Note this will only catch if the control is *only* referenced by layout and not by anything else // in addition (like usage or name). if (pathLength > indexOfLastSlash + 2 && path[indexOfLastSlash + 1] == '<' && path[pathLength - 1] == '>') { var layoutNameStart = indexOfLastSlash + 2; var layoutNameLength = pathLength - layoutNameStart - 1; return path.Substring(layoutNameStart, layoutNameLength); } // Have to actually look at the path in detail. var parser = new PathParser(path); if (!parser.MoveToNextComponent()) return null; if (parser.current.isWildcard) throw new NotImplementedException(); if (parser.current.layout.length == 0) return null; var deviceLayoutName = parser.current.layout.ToString(); if (!parser.MoveToNextComponent()) return null; // No control component. if (parser.current.isWildcard) return Wildcard; return FindControlLayoutRecursive(ref parser, deviceLayoutName); } private static string FindControlLayoutRecursive(ref PathParser parser, string layoutName) { using (InputControlLayout.CacheRef()) { // Load layout. var layout = InputControlLayout.cache.FindOrLoadLayout(new InternedString(layoutName), throwIfNotFound: false); if (layout == null) return null; // Search for control layout. May have to jump to other layouts // and search in them. return FindControlLayoutRecursive(ref parser, layout); } } private static string FindControlLayoutRecursive(ref PathParser parser, InputControlLayout layout) { string currentResult = null; var controlCount = layout.controls.Count; for (var i = 0; i < controlCount; ++i) { ////TODO: shortcut the search if we have a match and there's no wildcards to consider // Skip control layout if it doesn't match. if (!ControlLayoutMatchesPathComponent(ref layout.m_Controls[i], ref parser)) continue; var controlLayoutName = layout.m_Controls[i].layout; // If there's more in the path, try to dive into children by jumping to the // control's layout. if (!parser.isAtEnd) { var childPathParser = parser; if (childPathParser.MoveToNextComponent()) { var childControlLayoutName = FindControlLayoutRecursive(ref childPathParser, controlLayoutName); if (childControlLayoutName != null) { if (currentResult != null && childControlLayoutName != currentResult) return null; currentResult = childControlLayoutName; } } } else if (currentResult != null && controlLayoutName != currentResult) return null; else currentResult = controlLayoutName.ToString(); } return currentResult; } private static bool ControlLayoutMatchesPathComponent(ref InputControlLayout.ControlItem controlItem, ref PathParser parser) { // Match layout. var layout = parser.current.layout; if (layout.length > 0) { if (!StringMatches(layout, controlItem.layout)) return false; } // Match usage. if (parser.current.usages != null) { // All of usages should match to the one of usage in the control for (int usageIndex = 0; usageIndex < parser.current.usages.Length; ++usageIndex) { var usage = parser.current.usages[usageIndex]; if (usage.length > 0) { var usageCount = controlItem.usages.Count; var anyUsageMatches = false; for (var i = 0; i < usageCount; ++i) { if (StringMatches(usage, controlItem.usages[i])) { anyUsageMatches = true; break; } } if (!anyUsageMatches) return false; } } } // Match name. var name = parser.current.name; if (name.length > 0) { if (!StringMatches(name, controlItem.name)) return false; } return true; } // Match two name strings allowing for wildcards. // 'str' may contain wildcards. 'matchTo' may not. private static bool StringMatches(Substring str, InternedString matchTo) { var strLength = str.length; var matchToLength = matchTo.length; // Can't compare lengths here because str may contain wildcards and // thus be shorter than matchTo and still match. var matchToLowerCase = matchTo.ToLower(); // We manually walk the string here so that we can deal with "normal" // comparisons as well as with wildcards. var posInMatchTo = 0; var posInStr = 0; while (posInStr < strLength && posInMatchTo < matchToLength) { var nextChar = str[posInStr]; if (nextChar == '*') { ////TODO: make sure we don't end up with ** here if (posInStr == strLength - 1) return true; // Wildcard at end of string so rest is matched. ++posInStr; nextChar = char.ToLower(str[posInStr]); while (posInMatchTo < matchToLength && matchToLowerCase[posInMatchTo] != nextChar) ++posInMatchTo; if (posInMatchTo == matchToLength) return false; // Matched all the way to end of matchTo but there's more in str after the wildcard. } else if (char.ToLower(nextChar) != matchToLowerCase[posInMatchTo]) { return false; } ++posInMatchTo; ++posInStr; } return posInMatchTo == matchToLength && posInStr == strLength; // Check if we have consumed all input. Prevent prefix-only match. } public static InputControl TryFindControl(InputControl control, string path, int indexInPath = 0) { return TryFindControl<InputControl>(control, path, indexInPath); } public static InputControl[] TryFindControls(InputControl control, string path, int indexInPath = 0) { var matches = new InputControlList<InputControl>(Allocator.Temp); try { TryFindControls(control, path, indexInPath, ref matches); return matches.ToArray(); } finally { matches.Dispose(); } } public static int TryFindControls(InputControl control, string path, ref InputControlList<InputControl> matches, int indexInPath = 0) { return TryFindControls(control, path, indexInPath, ref matches); } /// <summary> /// Return the first child control that matches the given path. /// </summary> /// <param name="control">Control root at which to start the search.</param> /// <param name="path">Path of the control to find. Can be <c>null</c> or empty, in which case <c>null</c> /// is returned.</param> /// <param name="indexInPath">Index in <paramref name="path"/> at which to start parsing. Defaults to /// 0, i.e. parsing starts at the first character in the path.</param> /// <returns>The first (direct or indirect) child control of <paramref name="control"/> that matches /// <paramref name="path"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="control"/> is <c>null</c>.</exception> /// <remarks> /// Does not allocate. /// /// Note that if multiple child controls match the given path, which one is returned depends on the /// ordering of controls. The result should be considered indeterministic in this case. /// /// <example> /// <code> /// // Find X control of left stick on current gamepad. /// InputControlPath.TryFindControl(Gamepad.current, "leftStick/x"); /// /// // Find control with PrimaryAction usage on current mouse. /// InputControlPath.TryFindControl(Mouse.current, "{PrimaryAction}"); /// </code> /// </example> /// </remarks> /// <seealso cref="InputControl.this[string]"/> public static TControl TryFindControl<TControl>(InputControl control, string path, int indexInPath = 0) where TControl : InputControl { if (control == null) throw new ArgumentNullException(nameof(control)); if (string.IsNullOrEmpty(path)) return null; if (indexInPath == 0 && path[0] == '/') ++indexInPath; var none = new InputControlList<TControl>(); return MatchControlsRecursive(control, path, indexInPath, ref none, matchMultiple: false); } /// <summary> /// Perform a search for controls starting with the given control as root and matching /// the given path from the given position. Puts all matching controls on the list and /// returns the number of controls that have been matched. /// </summary> /// <param name="control">Control at which the given path is rooted.</param> /// <param name="path"></param> /// <param name="indexInPath"></param> /// <param name="matches"></param> /// <typeparam name="TControl"></typeparam> /// <returns></returns> /// <exception cref="ArgumentNullException"></exception> /// <remarks> /// Matching is case-insensitive. /// /// Does not allocate managed memory. /// </remarks> public static int TryFindControls<TControl>(InputControl control, string path, int indexInPath, ref InputControlList<TControl> matches) where TControl : InputControl { if (control == null) throw new ArgumentNullException(nameof(control)); if (path == null) throw new ArgumentNullException(nameof(path)); if (indexInPath == 0 && path[0] == '/') ++indexInPath; var countBefore = matches.Count; MatchControlsRecursive(control, path, indexInPath, ref matches, matchMultiple: true); return matches.Count - countBefore; } ////REVIEW: what's the difference between TryFindChild and TryFindControl?? public static InputControl TryFindChild(InputControl control, string path, int indexInPath = 0) { return TryFindChild<InputControl>(control, path, indexInPath); } public static TControl TryFindChild<TControl>(InputControl control, string path, int indexInPath = 0) where TControl : InputControl { if (control == null) throw new ArgumentNullException(nameof(control)); if (path == null) throw new ArgumentNullException(nameof(path)); var children = control.children; var childCount = children.Count; for (var i = 0; i < childCount; ++i) { var child = children[i]; var match = TryFindControl<TControl>(child, path, indexInPath); if (match != null) return match; } return null; } ////REVIEW: probably would be good to have a Matches(string,string) version public static bool Matches(string expected, InputControl control) { if (string.IsNullOrEmpty(expected)) throw new ArgumentNullException(nameof(expected)); if (control == null) throw new ArgumentNullException(nameof(control)); var parser = new PathParser(expected); return MatchesRecursive(ref parser, control); } /// <summary> /// Check whether the given path matches <paramref name="control"/> or any of its parents. /// </summary> /// <param name="expected">A control path.</param> /// <param name="control">An input control.</param> /// <returns>True if the given path matches at least a partial path to <paramref name="control"/>.</returns> /// <exception cref="ArgumentNullException"><paramref name="expected"/> is <c>null</c> or empty -or- /// <paramref name="control"/> is <c>null</c>.</exception> /// <remarks> /// <example> /// <code> /// // True as the path matches the Keyboard device itself, i.e. the parent of /// // Keyboard.aKey. /// InputControlPath.MatchesPrefix("&lt;Keyboard&gt;", Keyboard.current.aKey); /// /// // False as the path matches none of the controls leading to Keyboard.aKey. /// InputControlPath.MatchesPrefix("&lt;Gamepad&gt;", Keyboard.current.aKey); /// /// // True as the path matches Keyboard.aKey itself. /// InputControlPath.MatchesPrefix("&lt;Keyboard&gt;/a", Keyboard.current.aKey); /// </code> /// </example> /// </remarks> public static bool MatchesPrefix(string expected, InputControl control) { if (string.IsNullOrEmpty(expected)) throw new ArgumentNullException(nameof(expected)); if (control == null) throw new ArgumentNullException(nameof(control)); ////REVIEW: this can probably be done more efficiently for (var current = control; current != null; current = current.parent) { var parser = new PathParser(expected); if (MatchesRecursive(ref parser, current) && parser.isAtEnd) return true; } return false; } private static bool MatchesRecursive(ref PathParser parser, InputControl currentControl) { // Recurse into parent before looking at the current control. This // will advance the parser to where our control is in the path. var parent = currentControl.parent; if (parent != null && !MatchesRecursive(ref parser, parent)) return false; // Fail if there's no more path left. if (!parser.MoveToNextComponent()) return false; // Match current path component against current control. return parser.current.Matches(currentControl); } ////TODO: refactor this to use the new PathParser /// <summary> /// Recursively match path elements in <paramref name="path"/>. /// </summary> /// <param name="control">Current control we're at.</param> /// <param name="path">Control path we are matching against.</param> /// <param name="indexInPath">Index of current component in <paramref name="path"/>.</param> /// <param name="matches"></param> /// <param name="matchMultiple"></param> /// <typeparam name="TControl"></typeparam> /// <returns></returns> private static TControl MatchControlsRecursive<TControl>(InputControl control, string path, int indexInPath, ref InputControlList<TControl> matches, bool matchMultiple) where TControl : InputControl { var pathLength = path.Length; // Try to get a match. A path spec has three components: // "<layout>{usage}name" // All are optional but at least one component must be present. // Names can be aliases, too. // We don't tap InputControl.path strings of controls so as to not create a // bunch of string objects while feeling our way down the hierarchy. var controlIsMatch = true; // Match by layout. if (path[indexInPath] == '<') { ++indexInPath; controlIsMatch = MatchPathComponent(control.layout, path, ref indexInPath, PathComponentType.Layout); // If the layout isn't a match, walk up the base layout // chain and match each base layout. if (!controlIsMatch) { var baseLayout = control.m_Layout; while (InputControlLayout.s_Layouts.baseLayoutTable.TryGetValue(baseLayout, out baseLayout)) { controlIsMatch = MatchPathComponent(baseLayout, path, ref indexInPath, PathComponentType.Layout); if (controlIsMatch) break; } } } // Match by usage. while (indexInPath < pathLength && path[indexInPath] == '{' && controlIsMatch) { ++indexInPath; for (var i = 0; i < control.usages.Count; ++i) { controlIsMatch = MatchPathComponent(control.usages[i], path, ref indexInPath, PathComponentType.Usage); if (controlIsMatch) break; } } // Match by display name. if (indexInPath < pathLength - 1 && controlIsMatch && path[indexInPath] == '#' && path[indexInPath + 1] == '(') { indexInPath += 2; controlIsMatch = MatchPathComponent(control.displayName, path, ref indexInPath, PathComponentType.DisplayName); } // Match by name. if (indexInPath < pathLength && controlIsMatch && path[indexInPath] != '/') { // Normal name match. controlIsMatch = MatchPathComponent(control.name, path, ref indexInPath, PathComponentType.Name); // Alternative match by alias. if (!controlIsMatch) { for (var i = 0; i < control.aliases.Count && !controlIsMatch; ++i) { controlIsMatch = MatchPathComponent(control.aliases[i], path, ref indexInPath, PathComponentType.Name); } } } // If we have a match, return it or, if there's children, recurse into them. if (controlIsMatch) { // If we ended up on a wildcard, we've successfully matched it. if (indexInPath < pathLength && path[indexInPath] == '*') ++indexInPath; // If we've reached the end of the path, we have a match. if (indexInPath == pathLength) { // Check type. if (!(control is TControl match)) return null; if (matchMultiple) matches.Add(match); return match; } // If we've reached a separator, dive into our children. if (path[indexInPath] == '/') { ++indexInPath; // Silently accept trailing slashes. if (indexInPath == pathLength) { // Check type. if (!(control is TControl match)) return null; if (matchMultiple) matches.Add(match); return match; } // See if we want to match children by usage or by name. TControl lastMatch; if (path[indexInPath] == '{') { ////TODO: support scavenging a subhierarchy for usages if (!ReferenceEquals(control.device, control)) throw new NotImplementedException( "Matching usages inside subcontrols instead of at device root"); // Usages are kind of like entry points that can route to anywhere else // on a device's control hierarchy and then we keep going from that re-routed // point. lastMatch = MatchByUsageAtDeviceRootRecursive(control.device, path, indexInPath, ref matches, matchMultiple); } else { // Go through children and see what we can match. lastMatch = MatchChildrenRecursive(control, path, indexInPath, ref matches, matchMultiple); } return lastMatch; } } return null; } private static TControl MatchByUsageAtDeviceRootRecursive<TControl>(InputDevice device, string path, int indexInPath, ref InputControlList<TControl> matches, bool matchMultiple) where TControl : InputControl { var usages = device.m_UsagesForEachControl; if (usages == null) return null; var usageCount = device.m_UsageToControl.Length; var startIndex = indexInPath + 1; var pathCanMatchMultiple = PathComponentCanYieldMultipleMatches(path, indexInPath); var pathLength = path.Length; Debug.Assert(path[indexInPath] == '{'); ++indexInPath; if (indexInPath == pathLength) throw new ArgumentException($"Invalid path spec '{path}'; trailing '{{'", nameof(path)); TControl lastMatch = null; for (var i = 0; i < usageCount; ++i) { var usage = usages[i]; Debug.Assert(!string.IsNullOrEmpty(usage), "Usage entry is empty"); // Match usage against path. var usageIsMatch = MatchPathComponent(usage, path, ref indexInPath, PathComponentType.Usage); // If it isn't a match, go to next usage. if (!usageIsMatch) { indexInPath = startIndex; continue; } var controlMatchedByUsage = device.m_UsageToControl[i]; // If there's more to go in the path, dive into the children of the control. if (indexInPath < pathLength && path[indexInPath] == '/') { lastMatch = MatchChildrenRecursive(controlMatchedByUsage, path, indexInPath + 1, ref matches, matchMultiple); // We can stop going through usages if we matched something and the // path component covering usage does not contain wildcards. if (lastMatch != null && !pathCanMatchMultiple) break; // We can stop going through usages if we have a match and are only // looking for a single one. if (lastMatch != null && !matchMultiple) break; } else { lastMatch = controlMatchedByUsage as TControl; if (lastMatch != null) { if (matchMultiple) matches.Add(lastMatch); else { // Only looking for single match and we have one. break; } } } } return lastMatch; } private static TControl MatchChildrenRecursive<TControl>(InputControl control, string path, int indexInPath, ref InputControlList<TControl> matches, bool matchMultiple) where TControl : InputControl { var children = control.children; var childCount = children.Count; TControl lastMatch = null; var pathCanMatchMultiple = PathComponentCanYieldMultipleMatches(path, indexInPath); for (var i = 0; i < childCount; ++i) { var child = children[i]; var childMatch = MatchControlsRecursive(child, path, indexInPath, ref matches, matchMultiple); if (childMatch == null) continue; // If the child matched something an there's no wildcards in the child // portion of the path, we can stop searching. if (!pathCanMatchMultiple) return childMatch; // If we are only looking for the first match and a child matched, // we can also stop. if (!matchMultiple) return childMatch; // Otherwise we have to go hunting through the hierarchy in case there are // more matches. lastMatch = childMatch; } return lastMatch; } private enum PathComponentType { Name, DisplayName, Usage, Layout } private static bool MatchPathComponent(string component, string path, ref int indexInPath, PathComponentType componentType, int startIndexInComponent = 0) { Debug.Assert(component != null, "Component string is null"); Debug.Assert(path != null, "Path is null"); var componentLength = component.Length; var pathLength = path.Length; var startIndex = indexInPath; // Try to walk the name as far as we can. var indexInComponent = startIndexInComponent; while (indexInPath < pathLength) { // Check if we've reached a terminator in the path. var nextCharInPath = path[indexInPath]; if (nextCharInPath == '\\' && indexInPath + 1 < pathLength) { // Escaped character. Bypass treatment of special characters below. ++indexInPath; nextCharInPath = path[indexInPath]; } else { if (nextCharInPath == '/') break; if ((nextCharInPath == '>' && componentType == PathComponentType.Layout) || (nextCharInPath == '}' && componentType == PathComponentType.Usage) || (nextCharInPath == ')' && componentType == PathComponentType.DisplayName)) { ++indexInPath; break; } ////TODO: allow only single '*' and recognize '**' // If we've reached a '*' in the path, skip character in name. if (nextCharInPath == '*') { // But first let's see if we have something after the wildcard that matches the rest of the component. // This could be when, for example, we hit "T" on matching "leftTrigger" against "*Trigger". We have to stop // gobbling up characters for the wildcard when reaching "Trigger" in the component name. // // NOTE: Just looking at the very next character only is *NOT* enough. We need to match the entire rest of // the path. Otherwise, in the example above, we would stop on seeing the lowercase 't' and then be left // trying to match "tTrigger" against "Trigger". var indexAfterWildcard = indexInPath + 1; if (indexInPath < (pathLength - 1) && indexInComponent < componentLength && MatchPathComponent(component, path, ref indexAfterWildcard, componentType, indexInComponent)) { indexInPath = indexAfterWildcard; return true; } if (indexInComponent < componentLength) ++indexInComponent; else return true; continue; } } // If we've reached the end of the component name, we did so before // we've reached a terminator if (indexInComponent == componentLength) { indexInPath = startIndex; return false; } if (char.ToLower(component[indexInComponent]) == char.ToLower(nextCharInPath)) { ++indexInComponent; ++indexInPath; } else { // Name isn't a match. indexInPath = startIndex; return false; } } if (indexInComponent == componentLength) return true; indexInPath = startIndex; return false; } private static bool PathComponentCanYieldMultipleMatches(string path, int indexInPath) { var indexOfNextSlash = path.IndexOf('/', indexInPath); if (indexOfNextSlash == -1) return path.IndexOf('*', indexInPath) != -1 || path.IndexOf('<', indexInPath) != -1; var length = indexOfNextSlash - indexInPath; return path.IndexOf('*', indexInPath, length) != -1 || path.IndexOf('<', indexInPath, length) != -1; } // Parsed element between two '/../'. internal struct ParsedPathComponent { public Substring layout; public Substring[] usages; public Substring name; public Substring displayName; public bool isWildcard => name == Wildcard; public bool isDoubleWildcard => name == DoubleWildcard; public string ToHumanReadableString(string parentLayoutName, string parentControlPath, out string referencedLayoutName, out string controlPath, HumanReadableStringOptions options) { referencedLayoutName = null; controlPath = null; var result = string.Empty; if (isWildcard) result += "Any"; if (usages != null) { var combinedUsages = string.Empty; for (var i = 0; i < usages.Length; ++i) { if (usages[i].isEmpty) continue; if (combinedUsages != string.Empty) combinedUsages += " & " + ToHumanReadableString(usages[i]); else combinedUsages = ToHumanReadableString(usages[i]); } if (combinedUsages != string.Empty) { if (result != string.Empty) result += ' ' + combinedUsages; else result += combinedUsages; } } if (!layout.isEmpty) { referencedLayoutName = layout.ToString(); // Where possible, use the displayName of the given layout rather than // just the internal layout name. string layoutString; var referencedLayout = InputControlLayout.cache.FindOrLoadLayout(referencedLayoutName, throwIfNotFound: false); if (referencedLayout != null && !string.IsNullOrEmpty(referencedLayout.m_DisplayName)) layoutString = referencedLayout.m_DisplayName; else layoutString = ToHumanReadableString(layout); if (!string.IsNullOrEmpty(result)) result += ' ' + layoutString; else result += layoutString; } if (!name.isEmpty && !isWildcard) { // If we have a layout from a preceding path component, try to find // the control by name on the layout. If we find it, use its display // name rather than the name referenced in the binding. string nameString = null; if (!string.IsNullOrEmpty(parentLayoutName)) { // NOTE: This produces a fully merged layout. We should thus pick up display names // from base layouts automatically wherever applicable. var parentLayout = InputControlLayout.cache.FindOrLoadLayout(new InternedString(parentLayoutName), throwIfNotFound: false); if (parentLayout != null) { var controlName = new InternedString(name.ToString()); var control = parentLayout.FindControlIncludingArrayElements(controlName, out var arrayIndex); if (control != null) { // Synthesize path of control. if (string.IsNullOrEmpty(parentControlPath)) { if (arrayIndex != -1) controlPath = $"{control.Value.name}{arrayIndex}"; else controlPath = control.Value.name; } else { if (arrayIndex != -1) controlPath = $"{parentControlPath}/{control.Value.name}{arrayIndex}"; else controlPath = $"{parentControlPath}/{control.Value.name}"; } var shortDisplayName = (options & HumanReadableStringOptions.UseShortNames) != 0 ? control.Value.shortDisplayName : null; var displayName = !string.IsNullOrEmpty(shortDisplayName) ? shortDisplayName : control.Value.displayName; if (!string.IsNullOrEmpty(displayName)) { if (arrayIndex != -1) nameString = $"{displayName} #{arrayIndex}"; else nameString = displayName; } // If we don't have an explicit <layout> part in the component, // remember the name of the layout referenced by the control name so // that path components further down the line can keep looking up their // display names. if (string.IsNullOrEmpty(referencedLayoutName)) referencedLayoutName = control.Value.layout; } } } if (nameString == null) nameString = ToHumanReadableString(name); if (!string.IsNullOrEmpty(result)) result += ' ' + nameString; else result += nameString; } if (!displayName.isEmpty) { var str = $"\"{ToHumanReadableString(displayName)}\""; if (!string.IsNullOrEmpty(result)) result += ' ' + str; else result += str; } return result; } private static string ToHumanReadableString(Substring substring) { return substring.ToString().Unescape("/*{<", "/*{<"); } /// <summary> /// Whether the given control matches the constraints of this path component. /// </summary> /// <param name="control">Control to match against the path spec.</param> /// <returns></returns> public bool Matches(InputControl control) { // Match layout. if (!layout.isEmpty) { // Check for direct match. var layoutMatches = Substring.Compare(layout, control.layout, StringComparison.InvariantCultureIgnoreCase) == 0; if (!layoutMatches) { // No direct match but base layout may match. var baseLayout = control.m_Layout; while (InputControlLayout.s_Layouts.baseLayoutTable.TryGetValue(baseLayout, out baseLayout) && !layoutMatches) { layoutMatches = Substring.Compare(layout, baseLayout.ToString(), StringComparison.InvariantCultureIgnoreCase) == 0; } } if (!layoutMatches) return false; } // Match usage. if (usages != null) { for (int i = 0; i < usages.Length; ++i) { if (!usages[i].isEmpty) { var controlUsages = control.usages; var haveUsageMatch = false; for (var ci = 0; ci < controlUsages.Count; ++ci) if (Substring.Compare(controlUsages[ci].ToString(), usages[i], StringComparison.InvariantCultureIgnoreCase) == 0) { haveUsageMatch = true; break; } if (!haveUsageMatch) return false; } } } // Match name. if (!name.isEmpty && !isWildcard) { ////FIXME: unlike the matching path we have in MatchControlsRecursive, this does not take aliases into account if (Substring.Compare(control.name, name, StringComparison.InvariantCultureIgnoreCase) != 0) return false; } // Match display name. if (!displayName.isEmpty) { if (Substring.Compare(control.displayName, displayName, StringComparison.InvariantCultureIgnoreCase) != 0) return false; } return true; } } ////TODO: expose PathParser // NOTE: Must not allocate! internal struct PathParser { public string path; public int length; public int leftIndexInPath; public int rightIndexInPath; // Points either to a '/' character or one past the end of the path string. public ParsedPathComponent current; public bool isAtEnd => rightIndexInPath == length; public PathParser(string path) { Debug.Assert(path != null); this.path = path; length = path.Length; leftIndexInPath = 0; rightIndexInPath = 0; current = new ParsedPathComponent(); } // Update parsing state and 'current' to next component in path. // Returns true if the was another component or false if the end of the path was reached. public bool MoveToNextComponent() { // See if we've the end of the path string. if (rightIndexInPath == length) return false; // Make our current right index our new left index and find // a new right index from there. leftIndexInPath = rightIndexInPath; if (path[leftIndexInPath] == '/') { ++leftIndexInPath; rightIndexInPath = leftIndexInPath; if (leftIndexInPath == length) return false; } // Parse <...> layout part, if present. var layout = new Substring(); if (rightIndexInPath < length && path[rightIndexInPath] == '<') layout = ParseComponentPart('>'); // Parse {...} usage part, if present. var usages = new List<Substring>(); while (rightIndexInPath < length && path[rightIndexInPath] == '{') usages.Add(ParseComponentPart('}')); // Parse display name part, if present. var displayName = new Substring(); if (rightIndexInPath < length - 1 && path[rightIndexInPath] == '#' && path[rightIndexInPath + 1] == '(') { ++rightIndexInPath; displayName = ParseComponentPart(')'); } // Parse name part, if present. var name = new Substring(); if (rightIndexInPath < length && path[rightIndexInPath] != '/') name = ParseComponentPart('/'); current = new ParsedPathComponent { layout = layout, usages = usages.ToArray(), name = name, displayName = displayName }; return leftIndexInPath != rightIndexInPath; } private Substring ParseComponentPart(char terminator) { if (terminator != '/') // Name has no corresponding left side terminator. ++rightIndexInPath; var partStartIndex = rightIndexInPath; while (rightIndexInPath < length && path[rightIndexInPath] != terminator) ++rightIndexInPath; var partLength = rightIndexInPath - partStartIndex; if (rightIndexInPath < length && terminator != '/') ++rightIndexInPath; // Skip past terminator. return new Substring(path, partStartIndex, partLength); } } } }
43.932918
162
0.523809
[ "Unlicense" ]
23SAMY23/Meet-and-Greet-MR
Meet & Greet MR (AR)/Library/PackageCache/com.unity.inputsystem@1.0.2/InputSystem/Controls/InputControlPath.cs
63,527
C#
using Microsoft.AspNetCore.Authentication; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using MvcClient.Models; using Newtonsoft.Json.Linq; using System.Diagnostics; using System.Net.Http; using System.Net.Http.Headers; using System.Threading.Tasks; namespace MvcClient.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { return View(); } public async Task<IActionResult> CallApi() { var accessToken = await HttpContext.GetTokenAsync("access_token"); var client = new HttpClient(); client.DefaultRequestHeaders.Authorization = new AuthenticationHeaderValue("Bearer", accessToken); var content = await client.GetStringAsync("http://localhost:5001/identity"); ViewBag.Json = JArray.Parse(content).ToString(); return View("json"); } public IActionResult Logout() { return SignOut("Cookies", "oidc"); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } } }
29.66
112
0.644639
[ "MIT" ]
2ptych/IdentityServer4
src/MvcClient/Controllers/HomeController.cs
1,485
C#
using STEP.AST.Nodes; using STEP.Symbols; namespace STEP.SemanticAnalysis; public class DclVisitor : TypeVisitor { public DclVisitor(ISymbolTable symbolTable) { _symbolTable = symbolTable; } private readonly ISymbolTable _symbolTable; public override void Visit(IdNode n) { _symbolTable.EnterSymbol(n); } }
18.684211
47
0.701408
[ "MIT" ]
KarmaKamikaze/P4_Project
STEP/SemanticAnalysis/DclVisitor.cs
357
C#
// Copyright (c) Aghyad khlefawi. All rights reserved. // Licensed under the MIT License. See LICENSE file in the project root for full license information. using System.Threading.Tasks; namespace Coddee.Services.Configuration { /// <summary> /// Register the <see cref="IConfigurationManager"/> service. /// </summary> [Module(BuiltInModules.ConfigurationManager)] public class ConfigurationManagerModule:IModule { /// <inheritdoc /> public Task Initialize(IContainer container) { container.RegisterInstance<IConfigurationManager, ConfigurationManager>(); return Task.FromResult(true); } } }
29.782609
103
0.680292
[ "MIT" ]
Aghyad-Khlefawi/Coddee
src/Coddee.Windows/Configuration/ConfigurationManagerModule.cs
687
C#
namespace Employees.Data { public class Configuration { public static string ConnectionString => $"Server=.;Database=EmployeesDb;Integrated Security=True"; } }
25.714286
107
0.705556
[ "MIT" ]
BoykoNeov/Entity-Framework-SoftUni-Oct2017
Automapping/Employees.Data/Configuration.cs
182
C#
using Microsoft.EntityFrameworkCore.Storage; namespace EntityFrameworkCore.RelationalProviderStarter.Storage { public class MyRelationalSqlGenerationHelper : RelationalSqlGenerationHelper { } }
25.875
80
0.826087
[ "Apache-2.0" ]
Ashrafnet/EntityFramework.Docs
samples/core/Miscellaneous/Internals/WritingAProvider/EntityFrameworkCore.RelationalProviderStarter/Storage/MyRelationalSqlGenerationHelper.cs
209
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Text.RegularExpressions; using System.Threading.Tasks; namespace _05.SoftUni_Messages { class Program { static void Main(string[] args) { Regex messagePattern = new Regex(@"^\d+(?<massage>[A-Za-z]+)[^a-zA-Z]+$"); string input = Console.ReadLine(); while (input != "Decrypt!") { int validLength = int.Parse(Console.ReadLine()); if (messagePattern.IsMatch(input)) { Match m = messagePattern.Match(input); string message = m.Groups["massage"].Value; if (message.Length == validLength) { string decodedMassage = ADecodedMassage(input, message); Console.WriteLine("{1} = {0}",decodedMassage,message); } } input = Console.ReadLine(); } } static string ADecodedMassage(string input , string massage) { string result = ""; foreach (var symbol in input) { int index = symbol - '0'; if (char.IsDigit(symbol) && index < massage.Length) { result += massage[symbol - '0']; } } return result; } } }
28.884615
86
0.470706
[ "MIT" ]
PavelIvanov96/Programming-Fundamentals-Extended-CSharp
Regular Expressions (RegEx) - Exercises/05. SoftUni Messages/Program.cs
1,504
C#
#define EFL_BETA #pragma warning disable CS1591 using System; using System.Runtime.InteropServices; using System.Collections.Generic; using System.Linq; using System.Threading; using System.ComponentModel; namespace Efl { namespace Canvas { /// <summary>Low-level polygon object</summary> /// <remarks>This is a <b>BETA</b> class. It can be modified or removed in the future. Do not use it for product development.</remarks> [Efl.Canvas.Polygon.NativeMethods] [Efl.Eo.BindingEntity] public class Polygon : Efl.Canvas.Object { /// <summary>Pointer to the native class description.</summary> public override System.IntPtr NativeClass { get { if (((object)this).GetType() == typeof(Polygon)) { return GetEflClassStatic(); } else { return Efl.Eo.ClassRegister.klassFromType[((object)this).GetType()]; } } } [System.Runtime.InteropServices.DllImport(efl.Libs.Evas)] internal static extern System.IntPtr efl_canvas_polygon_class_get(); /// <summary>Initializes a new instance of the <see cref="Polygon"/> class.</summary> /// <param name="parent">Parent instance.</param> public Polygon(Efl.Object parent= null ) : base(efl_canvas_polygon_class_get(), parent) { FinishInstantiation(); } /// <summary>Subclasses should override this constructor if they are expected to be instantiated from native code. /// Do not call this constructor directly.</summary> /// <param name="ch">Tag struct storing the native handle of the object being constructed.</param> protected Polygon(ConstructingHandle ch) : base(ch) { } /// <summary>Initializes a new instance of the <see cref="Polygon"/> class. /// Internal usage: Constructs an instance from a native pointer. This is used when interacting with C code and should not be used directly.</summary> /// <param name="wh">The native pointer to be wrapped.</param> protected Polygon(Efl.Eo.Globals.WrappingHandle wh) : base(wh) { } /// <summary>Initializes a new instance of the <see cref="Polygon"/> class. /// Internal usage: Constructor to forward the wrapper initialization to the root class that interfaces with native code. Should not be used directly.</summary> /// <param name="baseKlass">The pointer to the base native Eo class.</param> /// <param name="parent">The Efl.Object parent of this instance.</param> protected Polygon(IntPtr baseKlass, Efl.Object parent) : base(baseKlass, parent) { } /// <summary>Adds the given point to the given evas polygon object.</summary> /// <param name="pos">A point coordinate.</param> virtual public void AddPoint(Eina.Position2D pos) { Eina.Position2D.NativeStruct _in_pos = pos; Efl.Canvas.Polygon.NativeMethods.efl_canvas_polygon_point_add_ptr.Value.Delegate((IsGeneratedBindingClass ? this.NativeHandle : Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass)),_in_pos); Eina.Error.RaiseIfUnhandledException(); } /// <summary>Removes all of the points from the given evas polygon object.</summary> virtual public void ClearPoints() { Efl.Canvas.Polygon.NativeMethods.efl_canvas_polygon_points_clear_ptr.Value.Delegate((IsGeneratedBindingClass ? this.NativeHandle : Efl.Eo.Globals.efl_super(this.NativeHandle, this.NativeClass))); Eina.Error.RaiseIfUnhandledException(); } private static IntPtr GetEflClassStatic() { return Efl.Canvas.Polygon.efl_canvas_polygon_class_get(); } /// <summary>Wrapper for native methods and virtual method delegates. /// For internal use by generated code only.</summary> public new class NativeMethods : Efl.Canvas.Object.NativeMethods { private static Efl.Eo.NativeModule Module = new Efl.Eo.NativeModule( efl.Libs.Evas); /// <summary>Gets the list of Eo operations to override.</summary> /// <returns>The list of Eo operations to be overload.</returns> public override System.Collections.Generic.List<Efl_Op_Description> GetEoOps(System.Type type) { var descs = new System.Collections.Generic.List<Efl_Op_Description>(); var methods = Efl.Eo.Globals.GetUserMethods(type); if (efl_canvas_polygon_point_add_static_delegate == null) { efl_canvas_polygon_point_add_static_delegate = new efl_canvas_polygon_point_add_delegate(point_add); } if (methods.FirstOrDefault(m => m.Name == "AddPoint") != null) { descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_canvas_polygon_point_add"), func = Marshal.GetFunctionPointerForDelegate(efl_canvas_polygon_point_add_static_delegate) }); } if (efl_canvas_polygon_points_clear_static_delegate == null) { efl_canvas_polygon_points_clear_static_delegate = new efl_canvas_polygon_points_clear_delegate(points_clear); } if (methods.FirstOrDefault(m => m.Name == "ClearPoints") != null) { descs.Add(new Efl_Op_Description() {api_func = Efl.Eo.FunctionInterop.LoadFunctionPointer(Module.Module, "efl_canvas_polygon_points_clear"), func = Marshal.GetFunctionPointerForDelegate(efl_canvas_polygon_points_clear_static_delegate) }); } descs.AddRange(base.GetEoOps(type)); return descs; } /// <summary>Returns the Eo class for the native methods of this class.</summary> /// <returns>The native class pointer.</returns> public override IntPtr GetEflClass() { return Efl.Canvas.Polygon.efl_canvas_polygon_class_get(); } #pragma warning disable CA1707, CS1591, SA1300, SA1600 private delegate void efl_canvas_polygon_point_add_delegate(System.IntPtr obj, System.IntPtr pd, Eina.Position2D.NativeStruct pos); public delegate void efl_canvas_polygon_point_add_api_delegate(System.IntPtr obj, Eina.Position2D.NativeStruct pos); public static Efl.Eo.FunctionWrapper<efl_canvas_polygon_point_add_api_delegate> efl_canvas_polygon_point_add_ptr = new Efl.Eo.FunctionWrapper<efl_canvas_polygon_point_add_api_delegate>(Module, "efl_canvas_polygon_point_add"); private static void point_add(System.IntPtr obj, System.IntPtr pd, Eina.Position2D.NativeStruct pos) { Eina.Log.Debug("function efl_canvas_polygon_point_add was called"); var ws = Efl.Eo.Globals.GetWrapperSupervisor(obj); if (ws != null) { Eina.Position2D _in_pos = pos; try { ((Polygon)ws.Target).AddPoint(_in_pos); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_canvas_polygon_point_add_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj)), pos); } } private static efl_canvas_polygon_point_add_delegate efl_canvas_polygon_point_add_static_delegate; private delegate void efl_canvas_polygon_points_clear_delegate(System.IntPtr obj, System.IntPtr pd); public delegate void efl_canvas_polygon_points_clear_api_delegate(System.IntPtr obj); public static Efl.Eo.FunctionWrapper<efl_canvas_polygon_points_clear_api_delegate> efl_canvas_polygon_points_clear_ptr = new Efl.Eo.FunctionWrapper<efl_canvas_polygon_points_clear_api_delegate>(Module, "efl_canvas_polygon_points_clear"); private static void points_clear(System.IntPtr obj, System.IntPtr pd) { Eina.Log.Debug("function efl_canvas_polygon_points_clear was called"); var ws = Efl.Eo.Globals.GetWrapperSupervisor(obj); if (ws != null) { try { ((Polygon)ws.Target).ClearPoints(); } catch (Exception e) { Eina.Log.Warning($"Callback error: {e.ToString()}"); Eina.Error.Set(Eina.Error.UNHANDLED_EXCEPTION); } } else { efl_canvas_polygon_points_clear_ptr.Value.Delegate(Efl.Eo.Globals.efl_super(obj, Efl.Eo.Globals.efl_class_get(obj))); } } private static efl_canvas_polygon_points_clear_delegate efl_canvas_polygon_points_clear_static_delegate; #pragma warning restore CA1707, CS1591, SA1300, SA1600 } } } } #if EFL_BETA #pragma warning disable CS1591 public static class Efl_CanvasPolygon_ExtensionMethods { } #pragma warning restore CS1591 #endif
43.240566
254
0.660849
[ "Apache-2.0", "MIT" ]
JoogabYun/TizenFX
internals/src/EflSharp/EflSharp/efl/efl_canvas_polygon.eo.cs
9,167
C#
namespace Free.FileFormats.VRML { public enum VRMLReaderError { UnexpectedEndOfStream=1, IllegalCharacterInStream=2, PROTOAlreadyDefined=3, MultipleISStatementForField=4, UnexpectedNodeType=5, UnknownFieldInNode=6, ProtoFound=7, SFBoolInvalid=20, SFColorInvalid=21, SFColorRGBAInvalid=22, SFFloatInvalid=23, SFImageInvalid=24, SFInt32Invalid=25, SFMatrix3fInvalid=26, SFMatrix4fInvalid=27, SFNodeInvalid=28, SFRotationInvalid=29, SFStringInvalid=30, SFTimeInvalid=31, SFVec2fInvalid=32, SFVec3fInvalid=33, SFVec4fInvalid=34, MFBoolInvalid=35, MFColorInvalid=36, MFColorRGBAInvalid=37, MFFloatInvalid=38, MFImageInvalid=39, MFInt32Invalid=40, MFMatrix3fInvalid=41, MFMatrix4fInvalid=42, MFNodeInvalid=43, MFRotationInvalid=44, MFStringInvalid=45, MFTimeInvalid=46, MFVec2fInvalid=47, MFVec3fInvalid=48, MFVec4fInvalid=49, // Warnings (default) USENameNotDefined=101, RouteSourceNameNotDefined=102, RouteTargetNameNotDefined=103, RedundantISStatement=104, ImproperInitializationOfMFNode=105, } }
20.884615
37
0.779006
[ "MIT" ]
JimCordwell/Free.FileFormats.VRML
VRMLParser/Enums/VRMLReaderError.cs
1,088
C#
using UnityEngine; using System.Collections; namespace Sierra.AGPW { public class CameraController : TrackMidoint { private void Awake() { _cam = Camera.main; } protected override void FixedUpdate() { base.FixedUpdate(); transform.position += new Vector3(0,0,_distance); var frustumHeight = 2.0f * Mathf.Abs(transform.position.z) * Mathf.Tan(_cam.fieldOfView * 0.5f * Mathf.Deg2Rad); var frustumWidth = frustumHeight * _cam.aspect; if (frustumWidth - MinDistFromFustrum*2 < GetDistance()) { //Debug.Log("Too Far"); transform.position -= new Vector3(0, 0, ZoomSpeed); } else if (frustumWidth - MaxDistFromFustrum * 2 > GetDistance()) { //Debug.Log("Too Close"); transform.position += new Vector3(0, 0, ZoomSpeed); } _distance = transform.position.z; } public float MinDistFromFustrum = 3; public float MaxDistFromFustrum = 4.5f; public float ZoomSpeed = 0.25f; private Camera _cam; private float _distance = -15f; } }
29.363636
75
0.529412
[ "MIT" ]
ScarletPhoenix5053/10-SECOND-ASCENCION
Assets/Scripts/Camera/CameraController.cs
1,294
C#
using System.Reflection; using System.Resources; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; using System.Windows; // 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("BuildAnApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("BuildAnApp")] [assembly: AssemblyCopyright("Copyright © 2013")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] //In order to begin building localizable applications, set //<UICulture>CultureYouAreCodingWith</UICulture> in your .csproj file //inside a <PropertyGroup>. For example, if you are using US english //in your source files, set the <UICulture> to en-US. Then uncomment //the NeutralResourceLanguage attribute below. Update the "en-US" in //the line below to match the UICulture setting in the project file. //[assembly: NeutralResourcesLanguage("en-US", UltimateResourceFallbackLocation.Satellite)] [assembly: ThemeInfo( ResourceDictionaryLocation.None, //where theme specific resource dictionaries are located //(used if a resource is not found in the page, // or application resource dictionaries) ResourceDictionaryLocation.SourceAssembly //where the generic resource dictionary is located //(used if a resource is not found in the page, // app, or any theme specific resource dictionaries) )] // 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")]
40.732143
97
0.736081
[ "MIT" ]
JianGuoWan/third-edition
WPF/Chapter_2/BuildAnApp/BuildAnApp/Properties/AssemblyInfo.cs
2,284
C#
namespace SQLite.Net.Exceptions { public class NotNullConstraintException : SQLiteConstraintException { public NotNullConstraintException(string message) : base(message) { } } }
26.142857
71
0.797814
[ "MIT" ]
Dominaezzz/sqlite-helper
SQLite.Net/Exceptions/NotNullConstraintException.cs
185
C#
using k8s.Models; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; namespace Synapse.Domain.Models { /// <summary> /// Represents the status of a <see cref="V1WorkflowInstance"/> /// </summary> public class V1WorkflowInstanceStatus { /// <summary> /// Gets the <see cref="V1WorkflowInstance"/>'s status type /// </summary> [JsonProperty("type")] public V1WorkflowActivityStatus Type { get; set; } /// <summary> /// Gets the date and time at which the <see cref="V1WorkflowInstance"/> has been initialized /// </summary> [JsonProperty("initializedAt")] public DateTimeOffset? InitializedAt { get; set; } /// <summary> /// Gets the date and time at which the <see cref="V1WorkflowInstance"/> has been deployed /// </summary> [JsonProperty("deployedAt")] public DateTimeOffset? DeployedAt { get; set; } /// <summary> /// Gets the date and time at which the <see cref="V1WorkflowInstance"/> has started /// </summary> [JsonProperty("startedAt")] public DateTimeOffset? StartedAt { get; set; } /// <summary> /// Gets the date and time at which the <see cref="V1WorkflowInstance"/> has been executed /// </summary> [JsonProperty("executedAt")] public DateTimeOffset? ExecutedAt { get; set; } /// <summary> /// Gets the <see cref="V1WorkflowInstance"/>'s pod <see cref="V1ObjectReference"/> /// </summary> [JsonProperty("pod")] public V1ObjectReference Pod { get; set; } /// <summary> /// Gets <see cref="V1WorkflowInstance"/>'s <see cref="V1CorrelationContext"/> /// </summary> [JsonProperty("correlationContext")] public V1CorrelationContext CorrelationContext { get; set; } = new V1CorrelationContext(); /// <summary> /// Gets a <see cref="List{T}"/> containing the <see cref="V1ExecutionInterruption"/>s that have occured during the <see cref="V1WorkflowInstance"/>'s execution /// </summary> [JsonProperty("interruptions")] public List<V1ExecutionInterruption> Interruptions { get; set; } = new List<V1ExecutionInterruption>(); /// <summary> /// Gets a <see cref="List{T}"/> containing the <see cref="V1WorkflowActivity"/> instances that have occured during the <see cref="V1WorkflowInstance"/>'s execution /// </summary> [JsonProperty("activityLog")] public List<V1WorkflowActivity> ActivityLog { get; set; } = new List<V1WorkflowActivity>(); /// <summary> /// Gets a <see cref="List{T}"/> containing the <see cref="V1Error"/>s that have occured during the <see cref="V1WorkflowInstance"/>'s execution /// </summary> [JsonProperty("errors")] public List<V1Error> Errors { get; set; } /// <summary> /// Gets the <see cref="V1WorkflowInstance"/>'s output /// </summary> [JsonProperty("output")] public JToken Output { get; set; } } }
37.188235
172
0.607719
[ "Apache-2.0" ]
manuelstein/synapse
src/BuildingBlocks/Synapse.Domain/Models/WorkflowInstance/v1/V1WorkflowInstanceStatus.cs
3,163
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.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using System.Linq; using System.Threading; using StarkPlatform.Compiler; using StarkPlatform.Compiler.Stark; using StarkPlatform.Compiler.Stark.Extensions; using StarkPlatform.Compiler.Stark.Extensions.ContextQuery; using StarkPlatform.Compiler.Stark.Symbols; using StarkPlatform.Compiler.Stark.Syntax; using StarkPlatform.Compiler.Stark.Utilities; using StarkPlatform.Compiler.Formatting; using StarkPlatform.Compiler.Shared.Extensions; using StarkPlatform.Compiler.Simplification; namespace StarkPlatform.Compiler.Stark.Simplification { internal partial class CSharpSimplificationService { private class Expander : CSharpSyntaxRewriter { private static readonly SyntaxTrivia s_oneWhitespaceSeparator = SyntaxFactory.SyntaxTrivia(SyntaxKind.WhitespaceTrivia, " "); private static readonly SymbolDisplayFormat s_typeNameFormatWithGenerics = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions: SymbolDisplayGenericsOptions.IncludeTypeParameters, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.ExpandNullable, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); private static readonly SymbolDisplayFormat s_typeNameFormatWithoutGenerics = new SymbolDisplayFormat( globalNamespaceStyle: SymbolDisplayGlobalNamespaceStyle.Included, genericsOptions: SymbolDisplayGenericsOptions.None, memberOptions: SymbolDisplayMemberOptions.IncludeContainingType, localOptions: SymbolDisplayLocalOptions.IncludeType, miscellaneousOptions: SymbolDisplayMiscellaneousOptions.EscapeKeywordIdentifiers | SymbolDisplayMiscellaneousOptions.ExpandNullable, typeQualificationStyle: SymbolDisplayTypeQualificationStyle.NameAndContainingTypesAndNamespaces); private readonly SemanticModel _semanticModel; private readonly Func<SyntaxNode, bool> _expandInsideNode; private readonly CancellationToken _cancellationToken; private readonly SyntaxAnnotation _annotationForReplacedAliasIdentifier; private readonly bool _expandParameter; public Expander( SemanticModel semanticModel, Func<SyntaxNode, bool> expandInsideNode, bool expandParameter, CancellationToken cancellationToken, SyntaxAnnotation annotationForReplacedAliasIdentifier = null) { _semanticModel = semanticModel; _expandInsideNode = expandInsideNode; _expandParameter = expandParameter; _cancellationToken = cancellationToken; _annotationForReplacedAliasIdentifier = annotationForReplacedAliasIdentifier; } public override SyntaxNode Visit(SyntaxNode node) { if (_expandInsideNode == null || _expandInsideNode(node)) { return base.Visit(node); } return node; } private bool IsPassedToDelegateCreationExpression(ArgumentSyntax argument, ITypeSymbol type) { if (type.IsDelegateType() && argument.IsParentKind(SyntaxKind.ArgumentList) && argument.Parent.IsParentKind(SyntaxKind.ObjectCreationExpression)) { var objectCreationExpression = (ObjectCreationExpressionSyntax)argument.Parent.Parent; var objectCreationType = _semanticModel.GetTypeInfo(objectCreationExpression).Type; if (objectCreationType.Equals(type)) { return true; } } return false; } private SpeculationAnalyzer GetSpeculationAnalyzer(ExpressionSyntax expression, ExpressionSyntax newExpression) { return new SpeculationAnalyzer(expression, newExpression, _semanticModel, _cancellationToken); } private bool TryCastTo(ITypeSymbol targetType, ExpressionSyntax expression, ExpressionSyntax newExpression, out ExpressionSyntax newExpressionWithCast) { var speculativeAnalyzer = GetSpeculationAnalyzer(expression, newExpression); var speculativeSemanticModel = speculativeAnalyzer.SpeculativeSemanticModel; var speculatedExpression = speculativeAnalyzer.ReplacedExpression; var result = speculatedExpression.CastIfPossible(targetType, speculatedExpression.SpanStart, speculativeSemanticModel); if (result != speculatedExpression) { newExpressionWithCast = result; return true; } newExpressionWithCast = null; return false; } private bool TryGetLambdaExpressionBodyWithCast(LambdaExpressionSyntax lambdaExpression, LambdaExpressionSyntax newLambdaExpression, out ExpressionSyntax newLambdaExpressionBodyWithCast) { if (newLambdaExpression.Body is ExpressionSyntax) { var body = (ExpressionSyntax)lambdaExpression.Body; var newBody = (ExpressionSyntax)newLambdaExpression.Body; var returnType = (_semanticModel.GetSymbolInfo(lambdaExpression).Symbol as IMethodSymbol)?.ReturnType; if (returnType != null) { return TryCastTo(returnType, body, newBody, out newLambdaExpressionBodyWithCast); } } newLambdaExpressionBodyWithCast = null; return false; } public override SyntaxNode VisitReturnStatement(ReturnStatementSyntax node) { var newNode = base.VisitReturnStatement(node); if (newNode is ReturnStatementSyntax newReturnStatement) { if (newReturnStatement.Expression != null) { var parentLambda = node.FirstAncestorOrSelf<LambdaExpressionSyntax>(); if (parentLambda != null) { var returnType = (_semanticModel.GetSymbolInfo(parentLambda).Symbol as IMethodSymbol)?.ReturnType; if (returnType != null) { if (TryCastTo(returnType, node.Expression, newReturnStatement.Expression, out var newExpressionWithCast)) { newNode = newReturnStatement.WithExpression(newExpressionWithCast); } } } } } return newNode; } public override SyntaxNode VisitParenthesizedLambdaExpression(ParenthesizedLambdaExpressionSyntax node) { var newNode = base.VisitParenthesizedLambdaExpression(node); if (newNode is ParenthesizedLambdaExpressionSyntax parenthesizedLambda) { // First, try to add a cast to the lambda. if (TryGetLambdaExpressionBodyWithCast(node, parenthesizedLambda, out var newLambdaExpressionBodyWithCast)) { parenthesizedLambda = parenthesizedLambda.WithBody(newLambdaExpressionBodyWithCast); } // Next, try to add a types to the lambda parameters if (_expandParameter && parenthesizedLambda.ParameterList != null) { var parameterList = parenthesizedLambda.ParameterList; var parameters = parameterList.Parameters.ToArray(); if (parameters.Length > 0 && parameters.Any(p => p.Type == null)) { var parameterSymbols = node.ParameterList.Parameters .Select(p => _semanticModel.GetDeclaredSymbol(p, _cancellationToken)) .ToArray(); if (parameterSymbols.All(p => p.Type?.ContainsAnonymousType() == false)) { var newParameters = parameterList.Parameters; for (int i = 0; i < parameterSymbols.Length; i++) { var typeSyntax = parameterSymbols[i].Type.GenerateTypeSyntax().WithTrailingTrivia(s_oneWhitespaceSeparator); var newParameter = parameters[i].WithType(typeSyntax).WithAdditionalAnnotations(Simplifier.Annotation); var currentParameter = newParameters[i]; newParameters = newParameters.Replace(currentParameter, newParameter); } var newParameterList = parameterList.WithParameters(newParameters); var newParenthesizedLambda = parenthesizedLambda.WithParameterList(newParameterList); return SimplificationHelpers.CopyAnnotations(from: parenthesizedLambda, to: newParenthesizedLambda); } } } return parenthesizedLambda; } return newNode; } public override SyntaxNode VisitSimpleLambdaExpression(SimpleLambdaExpressionSyntax node) { var newNode = base.VisitSimpleLambdaExpression(node); if (newNode is SimpleLambdaExpressionSyntax simpleLambda) { // First, try to add a cast to the lambda. if (TryGetLambdaExpressionBodyWithCast(node, simpleLambda, out var newLambdaExpressionBodyWithCast)) { simpleLambda = simpleLambda.WithBody(newLambdaExpressionBodyWithCast); } // Next, try to add a type to the lambda parameter if (_expandParameter) { var parameterSymbol = _semanticModel.GetDeclaredSymbol(node.Parameter); if (parameterSymbol?.Type?.ContainsAnonymousType() == false) { var typeSyntax = parameterSymbol.Type.GenerateTypeSyntax().WithTrailingTrivia(s_oneWhitespaceSeparator); var newSimpleLambdaParameter = simpleLambda.Parameter.WithType(typeSyntax).WithoutTrailingTrivia(); var parenthesizedLambda = SyntaxFactory.ParenthesizedLambdaExpression( simpleLambda.AsyncKeyword, SyntaxFactory.ParameterList(SyntaxFactory.SingletonSeparatedList(newSimpleLambdaParameter)) .WithTrailingTrivia(simpleLambda.Parameter.GetTrailingTrivia()) .WithLeadingTrivia(simpleLambda.Parameter.GetLeadingTrivia()), simpleLambda.ArrowToken, simpleLambda.Body).WithAdditionalAnnotations(Simplifier.Annotation); return SimplificationHelpers.CopyAnnotations(from: simpleLambda, to: parenthesizedLambda); } } return simpleLambda; } return newNode; } public override SyntaxNode VisitArgument(ArgumentSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var newArgument = (ArgumentSyntax)base.VisitArgument(node); if (node.NameColon == null && node.Parent is TupleExpressionSyntax tuple && !IsTupleInDeconstruction(tuple)) // The language currently does not allow explicit element names in deconstruction { var inferredName = node.Expression.TryGetInferredMemberName(); if (CanMakeNameExplicitInTuple(tuple, inferredName)) { var identifier = SyntaxFactory.Identifier(inferredName); identifier = TryEscapeIdentifierToken(identifier, node, _semanticModel); newArgument = newArgument .WithoutLeadingTrivia() .WithNameColon(SyntaxFactory.NameColon(SyntaxFactory.IdentifierName(identifier))) .WithAdditionalAnnotations(Simplifier.Annotation) .WithLeadingTrivia(node.GetLeadingTrivia()); } } var argumentType = _semanticModel.GetTypeInfo(node.Expression).ConvertedType; if (argumentType != null && !IsPassedToDelegateCreationExpression(node, argumentType) && node.Expression.Kind() != SyntaxKind.DeclarationExpression && node.RefOrOutKeyword.Kind() == SyntaxKind.None) { if (TryCastTo(argumentType, node.Expression, newArgument.Expression, out var newArgumentExpressionWithCast)) { return newArgument.WithExpression(newArgumentExpressionWithCast); } } return newArgument; } private static bool CanMakeNameExplicitInTuple(TupleExpressionSyntax tuple, string name) { if (name == null || SyntaxFacts.IsReservedTupleElementName(name)) { return false; } bool found = false; foreach (var argument in tuple.Arguments) { string elementName = null; if (argument.NameColon != null) { elementName = argument.NameColon.Name.Identifier.ValueText; } else { elementName = argument.Expression?.TryGetInferredMemberName(); } if (elementName?.Equals(name, StringComparison.Ordinal) == true) { if (found) { // No duplicate names allowed return false; } found = true; } } return true; } public override SyntaxNode VisitAnonymousObjectMemberDeclarator(AnonymousObjectMemberDeclaratorSyntax node) { var newDeclarator = (AnonymousObjectMemberDeclaratorSyntax)base.VisitAnonymousObjectMemberDeclarator(node); if (node.NameEquals == null) { var inferredName = node.Expression.TryGetInferredMemberName(); if (inferredName != null) { // Creating identifier without elastic trivia to avoid unexpected line break var identifier = SyntaxFactory.Identifier(SyntaxTriviaList.Empty, inferredName, SyntaxTriviaList.Empty); identifier = TryEscapeIdentifierToken(identifier, node, _semanticModel); newDeclarator = newDeclarator .WithoutLeadingTrivia() .WithNameEquals(SyntaxFactory.NameEquals(SyntaxFactory.IdentifierName(identifier)) .WithLeadingTrivia(node.GetLeadingTrivia())) .WithAdditionalAnnotations(Simplifier.Annotation); } } return newDeclarator; } public override SyntaxNode VisitBinaryExpression(BinaryExpressionSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); // Special case: We parenthesize to avoid a situation where inlining an // expression can cause code to parse differently. The canonical case is... // // var x = 0; // var y = (1 + 2); // var z = new[] { x < x, x > y }; // // Inlining 'y' in the code above will produce code that parses differently // (i.e. as a generic method invocation). // // var z = new[] { x < x, x > (1 + 2) }; var result = (BinaryExpressionSyntax)base.VisitBinaryExpression(node); if ((node.Kind() == SyntaxKind.GreaterThanExpression || node.Kind() == SyntaxKind.RightShiftExpression) && !node.IsParentKind(SyntaxKind.ParenthesizedExpression)) { return result.Parenthesize(); } return result; } public override SyntaxNode VisitInterpolation(InterpolationSyntax node) { var result = (InterpolationSyntax)base.VisitInterpolation(node); if (result.Expression != null && !result.Expression.IsKind(SyntaxKind.ParenthesizedExpression)) { result = result.WithExpression(result.Expression.Parenthesize()); } return result; } public override SyntaxNode VisitXmlNameAttribute(XmlNameAttributeSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var newNode = (XmlNameAttributeSyntax)base.VisitXmlNameAttribute(node); return node.CopyAnnotationsTo(newNode); } public override SyntaxNode VisitNameMemberCref(NameMemberCrefSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var rewrittenname = (TypeSyntax)this.Visit(node.Name); var parameters = (CrefParameterListSyntax)this.Visit(node.Parameters); if (rewrittenname.Kind() == SyntaxKind.QualifiedName) { return node.CopyAnnotationsTo(SyntaxFactory.QualifiedCref( ((QualifiedNameSyntax)rewrittenname).Left .WithAdditionalAnnotations(Simplifier.Annotation), SyntaxFactory.NameMemberCref(((QualifiedNameSyntax)rewrittenname).Right, parameters) .WithLeadingTrivia(SyntaxTriviaList.Empty)) .WithLeadingTrivia(node.GetLeadingTrivia()) .WithTrailingTrivia(node.GetTrailingTrivia())) .WithAdditionalAnnotations(Simplifier.Annotation); } else if (rewrittenname.Kind() == SyntaxKind.AliasQualifiedName) { return node.CopyAnnotationsTo(SyntaxFactory.TypeCref( rewrittenname).WithLeadingTrivia(node.GetLeadingTrivia()) .WithTrailingTrivia(node.GetTrailingTrivia())) .WithAdditionalAnnotations(Simplifier.Annotation); } return node.Update(rewrittenname, parameters); } public override SyntaxNode VisitGenericName(GenericNameSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var newNode = (SimpleNameSyntax)base.VisitGenericName(node); return VisitSimpleName(newNode, node); } public override SyntaxNode VisitIdentifierName(IdentifierNameSyntax node) { _cancellationToken.ThrowIfCancellationRequested(); var identifier = node.Identifier; var newNode = (SimpleNameSyntax)base.VisitIdentifierName(node); return VisitSimpleName(newNode, node); } private ExpressionSyntax VisitSimpleName(SimpleNameSyntax rewrittenSimpleName, SimpleNameSyntax originalSimpleName) { _cancellationToken.ThrowIfCancellationRequested(); // if this is "var", then do not process further if (originalSimpleName.IsNullWithNoType()) { return rewrittenSimpleName; } var identifier = rewrittenSimpleName.Identifier; ExpressionSyntax newNode = rewrittenSimpleName; var isInsideCref = originalSimpleName.AncestorsAndSelf(ascendOutOfTrivia: true).Any(n => n is CrefSyntax); //// //// 1. if this identifier is an alias, we'll expand it here and replace the node completely. //// if (!SyntaxFacts.IsAliasQualifier(originalSimpleName)) { var aliasInfo = _semanticModel.GetAliasInfo(originalSimpleName, _cancellationToken); if (aliasInfo != null) { var aliasTarget = aliasInfo.Target; if (aliasTarget.IsNamespace() && ((INamespaceSymbol)aliasTarget).IsGlobalNamespace) { return rewrittenSimpleName; } // if the enclosing expression is a typeof expression that already contains open type we cannot // we need to insert an open type as well. var typeOfExpression = originalSimpleName.GetAncestor<TypeOfExpressionSyntax>(); if (typeOfExpression != null && IsTypeOfUnboundGenericType(_semanticModel, typeOfExpression)) { aliasTarget = ((INamedTypeSymbol)aliasTarget).ConstructUnboundGenericType(); } if (aliasTarget is INamedTypeSymbol typeSymbol && typeSymbol.IsTupleType) { // ValueTuple type is not allowed in using alias, so when expanding an alias // of ValueTuple types, always use its underlying type, i.e. `System.ValueTuple<>` instead of `(...)` aliasTarget = typeSymbol.TupleUnderlyingType; } // the expanded form replaces the current identifier name. var replacement = FullyQualifyIdentifierName( aliasTarget, newNode, originalSimpleName, replaceNode: true, isInsideCref: isInsideCref, omitLeftHandSide: false) .WithAdditionalAnnotations(Simplifier.Annotation); // We replace the simple name completely, so we can't continue and rename the token // with a RenameLocationAnnotation. // There's also no way of removing annotations, so we just add a DoNotRenameAnnotation. switch (replacement.Kind()) { case SyntaxKind.AliasQualifiedName: var aliasQualifiedReplacement = (AliasQualifiedNameSyntax)replacement; replacement = replacement.ReplaceNode( aliasQualifiedReplacement.Name, aliasQualifiedReplacement.Name.WithIdentifier( GetNewIdentifier(aliasQualifiedReplacement.Name.Identifier))); var firstReplacementToken = replacement.GetFirstToken(true, false, true, true); var firstOriginalToken = originalSimpleName.GetFirstToken(true, false, true, true); if (TryAddLeadingElasticTriviaIfNecessary(firstReplacementToken, firstOriginalToken, out var tokenWithLeadingWhitespace)) { replacement = replacement.ReplaceToken(firstOriginalToken, tokenWithLeadingWhitespace); } break; case SyntaxKind.QualifiedName: var qualifiedReplacement = (QualifiedNameSyntax)replacement; replacement = replacement.ReplaceNode( qualifiedReplacement.Right, qualifiedReplacement.Right.WithIdentifier( GetNewIdentifier(qualifiedReplacement.Right.Identifier))); break; case SyntaxKind.IdentifierName: var identifierReplacement = (IdentifierNameSyntax)replacement; replacement = replacement.ReplaceToken(identifier, GetNewIdentifier(identifierReplacement.Identifier)); break; default: throw new NotImplementedException(); } replacement = newNode.CopyAnnotationsTo(replacement); replacement = AppendElasticTriviaIfNecessary(replacement, originalSimpleName); return replacement; SyntaxToken GetNewIdentifier(SyntaxToken _identifier) { var newIdentifier = identifier.CopyAnnotationsTo(_identifier); if (_annotationForReplacedAliasIdentifier != null) { newIdentifier = newIdentifier.WithAdditionalAnnotations(_annotationForReplacedAliasIdentifier); } var aliasAnnotationInfo = AliasAnnotation.Create(aliasInfo.Name); return newIdentifier.WithAdditionalAnnotations(aliasAnnotationInfo); } } } var symbol = _semanticModel.GetSymbolInfo(originalSimpleName.Identifier).Symbol; if (symbol == null) { return newNode; } var typeArgumentSymbols = TypeArgumentSymbolsPresentInName(originalSimpleName); var omitLeftSideOfExpression = false; // Check to see if the type Arguments in the resultant Symbol is recursively defined. if (IsTypeArgumentDefinedRecursive(symbol, typeArgumentSymbols, enterContainingSymbol: true)) { if (symbol.ContainingSymbol.Equals(symbol.OriginalDefinition.ContainingSymbol) && symbol.Kind == SymbolKind.Method && ((IMethodSymbol)symbol).IsStatic) { if (IsTypeArgumentDefinedRecursive(symbol, typeArgumentSymbols, enterContainingSymbol: false)) { return newNode; } else { omitLeftSideOfExpression = true; } } else { return newNode; } } //// //// 2. If it's an attribute, make sure the identifier matches the attribute's class name. //// if (originalSimpleName.GetAncestor<AttributeSyntax>() != null) { if (symbol.IsConstructor() && symbol.ContainingType?.IsAttribute() == true) { symbol = symbol.ContainingType; var name = symbol.Name; Debug.Assert(name.StartsWith(originalSimpleName.Identifier.ValueText, StringComparison.Ordinal)); // if the user already used the Attribute suffix in the attribute, we'll maintain it. if (identifier.ValueText == name && name.EndsWith("Attribute", StringComparison.Ordinal)) { identifier = identifier.WithAdditionalAnnotations(SimplificationHelpers.DontSimplifyAnnotation); } identifier = identifier.CopyAnnotationsTo(SyntaxFactory.VerbatimIdentifier(identifier.LeadingTrivia, name, name, identifier.TrailingTrivia)); } } //// //// 3. Always try to escape keyword identifiers //// identifier = TryEscapeIdentifierToken(identifier, originalSimpleName, _semanticModel).WithAdditionalAnnotations(Simplifier.Annotation); if (identifier != rewrittenSimpleName.Identifier) { switch (newNode.Kind()) { case SyntaxKind.IdentifierName: case SyntaxKind.GenericName: newNode = ((SimpleNameSyntax)newNode).WithIdentifier(identifier); break; default: throw new NotImplementedException(); } } var parent = originalSimpleName.Parent; // do not complexify further for location where only simple names are allowed if (parent is MemberDeclarationSyntax || parent is MemberBindingExpressionSyntax || originalSimpleName.GetAncestor<NameEqualsSyntax>() != null || (parent is MemberAccessExpressionSyntax && parent.Kind() != SyntaxKind.SimpleMemberAccessExpression) || ((parent.Kind() == SyntaxKind.SimpleMemberAccessExpression || parent.Kind() == SyntaxKind.NameMemberCref) && originalSimpleName.IsRightSideOfDot()) || (parent.Kind() == SyntaxKind.QualifiedName && originalSimpleName.IsRightSideOfQualifiedName()) || (parent.Kind() == SyntaxKind.AliasQualifiedName) || (parent.Kind() == SyntaxKind.NameColon)) { return TryAddTypeArgumentToIdentifierName(newNode, symbol); } //// //// 4. If this is a standalone identifier or the left side of a qualified name or member access try to fully qualify it //// // we need to treat the constructor as type name, so just get the containing type. if (symbol.IsConstructor() && (parent.Kind() == SyntaxKind.ObjectCreationExpression || parent.Kind() == SyntaxKind.NameMemberCref)) { symbol = symbol.ContainingType; } // if it's a namespace or type name, fully qualify it. if (symbol.Kind == SymbolKind.NamedType || symbol.Kind == SymbolKind.Namespace) { var replacement = FullyQualifyIdentifierName( (INamespaceOrTypeSymbol)symbol, newNode, originalSimpleName, replaceNode: false, isInsideCref: isInsideCref, omitLeftHandSide: omitLeftSideOfExpression) .WithAdditionalAnnotations(Simplifier.Annotation); replacement = AppendElasticTriviaIfNecessary(replacement, originalSimpleName); return replacement; } // if it's a member access, we're fully qualifying the left side and make it a member access. if (symbol.Kind == SymbolKind.Method || symbol.Kind == SymbolKind.Field || symbol.Kind == SymbolKind.Property) { if (symbol.IsStatic || originalSimpleName.IsParentKind(SyntaxKind.NameMemberCref) || _semanticModel.SyntaxTree.IsNameOfContext(originalSimpleName.SpanStart, _semanticModel, _cancellationToken)) { newNode = FullyQualifyIdentifierName( symbol, newNode, originalSimpleName, replaceNode: false, isInsideCref: isInsideCref, omitLeftHandSide: omitLeftSideOfExpression); } else { if (!IsPropertyNameOfObjectInitializer(originalSimpleName)) { ExpressionSyntax left; // Assumption here is, if the enclosing and containing types are different then there is inheritance relationship if (_semanticModel.GetEnclosingNamedType(originalSimpleName.SpanStart, _cancellationToken) != symbol.ContainingType) { left = SyntaxFactory.BaseExpression(); } else { left = SyntaxFactory.ThisExpression(); } var identifiersLeadingTrivia = newNode.GetLeadingTrivia(); newNode = TryAddTypeArgumentToIdentifierName(newNode, symbol); newNode = newNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, (SimpleNameSyntax)newNode.WithLeadingTrivia(null)) .WithLeadingTrivia(identifiersLeadingTrivia)); } } } var result = newNode.WithAdditionalAnnotations(Simplifier.Annotation); result = AppendElasticTriviaIfNecessary(result, originalSimpleName); return result; } private ExpressionSyntax TryReplaceAngleBracesWithCurlyBraces(ExpressionSyntax expression, bool isInsideCref) { if (isInsideCref) { var leftTokens = expression.DescendantTokens(); List<SyntaxToken> candidateTokens = new List<SyntaxToken>(); foreach (var candidateToken in leftTokens) { if (candidateToken.Kind() == SyntaxKind.LessThanToken || candidateToken.Kind() == SyntaxKind.GreaterThanToken) { candidateTokens.Add(candidateToken); continue; } } expression = expression.ReplaceTokens(candidateTokens, computeReplacementToken: ReplaceTokenForCref); } return expression; } private ExpressionSyntax TryAddTypeArgumentToIdentifierName(ExpressionSyntax newNode, ISymbol symbol) { if (newNode.Kind() == SyntaxKind.IdentifierName && symbol.Kind == SymbolKind.Method) { if (((IMethodSymbol)symbol).TypeArguments.Length != 0) { var typeArguments = ((IMethodSymbol)symbol).TypeArguments; if (!typeArguments.Any(t => t.ContainsAnonymousType())) { var genericName = SyntaxFactory.GenericName( ((IdentifierNameSyntax)newNode).Identifier, SyntaxFactory.TypeArgumentList( SyntaxFactory.SeparatedList( typeArguments.Select(p => SyntaxFactory.ParseTypeName(p.ToDisplayParts(s_typeNameFormatWithGenerics).ToDisplayString()))))) .WithLeadingTrivia(newNode.GetLeadingTrivia()) .WithTrailingTrivia(newNode.GetTrailingTrivia()) .WithAdditionalAnnotations(Simplifier.Annotation); genericName = newNode.CopyAnnotationsTo(genericName); return genericName; } } } return newNode; } private IList<ISymbol> TypeArgumentSymbolsPresentInName(SimpleNameSyntax simpleName) { List<ISymbol> typeArgumentSymbols = new List<ISymbol>(); var typeArgumentListSyntax = simpleName.DescendantNodesAndSelf().Where(n => n is TypeArgumentListSyntax); foreach (var typeArgumentList in typeArgumentListSyntax) { var castedTypeArgument = (TypeArgumentListSyntax)typeArgumentList; foreach (var typeArgument in castedTypeArgument.Arguments) { var symbol = _semanticModel.GetSymbolInfo(typeArgument).Symbol; if (symbol != null && !typeArgumentSymbols.Contains(symbol)) { typeArgumentSymbols.Add(symbol); } } } return typeArgumentSymbols; } private bool IsTypeArgumentDefinedRecursive(ISymbol symbol, IList<ISymbol> typeArgumentSymbols, bool enterContainingSymbol) { if (symbol == symbol.OriginalDefinition) { return false; } var typeArgumentsInSymbol = new List<ISymbol>(); TypeArgumentsInAllContainingSymbol(symbol, typeArgumentsInSymbol, enterContainingSymbol, isRecursive: true); var typeArgumentsInOriginalDefinition = new List<ISymbol>(); TypeArgumentsInAllContainingSymbol(symbol.OriginalDefinition, typeArgumentsInOriginalDefinition, enterContainingSymbol, isRecursive: false); if (typeArgumentsInSymbol.Intersect(typeArgumentsInOriginalDefinition).Any(n => !typeArgumentSymbols.Contains(n))) { return true; } return false; } private void TypeArgumentsInAllContainingSymbol(ISymbol symbol, IList<ISymbol> typeArgumentSymbols, bool enterContainingSymbol, bool isRecursive) { if (symbol == null || symbol.IsNamespace()) { // This is the terminating condition return; } if (symbol is INamedTypeSymbol namedTypedSymbol) { if (namedTypedSymbol.TypeArguments.Length != 0) { foreach (var typeArgument in namedTypedSymbol.TypeArguments) { if (!typeArgumentSymbols.Contains(typeArgument)) { typeArgumentSymbols.Add(typeArgument); if (isRecursive) { TypeArgumentsInAllContainingSymbol(typeArgument, typeArgumentSymbols, enterContainingSymbol, isRecursive); } } } } } if (enterContainingSymbol) { TypeArgumentsInAllContainingSymbol(symbol.ContainingSymbol, typeArgumentSymbols, enterContainingSymbol, isRecursive); } } private bool IsPropertyNameOfObjectInitializer(SimpleNameSyntax identifierName) { SyntaxNode currentNode = identifierName; SyntaxNode parent = identifierName; while (parent != null) { if (parent.Kind() == SyntaxKind.ObjectInitializerExpression) { return currentNode.Kind() == SyntaxKind.SimpleAssignmentExpression && object.Equals(((AssignmentExpressionSyntax)currentNode).Left, identifierName); } else if (parent is ExpressionSyntax) { currentNode = parent; parent = parent.Parent; continue; } else { return false; } } return false; } private ExpressionSyntax FullyQualifyIdentifierName( ISymbol symbol, ExpressionSyntax rewrittenNode, ExpressionSyntax originalNode, bool replaceNode, bool isInsideCref, bool omitLeftHandSide) { Debug.Assert(!replaceNode || rewrittenNode.Kind() == SyntaxKind.IdentifierName); //// TODO: use and expand Generate*Syntax(isymbol) to not depend on symbol display any more. //// See GenerateExpressionSyntax(); var result = rewrittenNode; // only if this symbol has a containing type or namespace there is work for us to do. if (replaceNode || symbol.ContainingType != null || symbol.ContainingNamespace != null) { ImmutableArray<SymbolDisplayPart> displayParts; ExpressionSyntax left = null; // we either need to create an AliasQualifiedName if the symbol is directly contained in the global namespace, // otherwise it a QualifiedName. if (!replaceNode && symbol.ContainingType == null && symbol.ContainingNamespace.IsGlobalNamespace) { return rewrittenNode.CopyAnnotationsTo( SyntaxFactory.AliasQualifiedName( SyntaxFactory.IdentifierName(SyntaxFactory.Token(SyntaxKind.GlobalKeyword)), (SimpleNameSyntax)rewrittenNode.WithLeadingTrivia(null)) .WithLeadingTrivia(rewrittenNode.GetLeadingTrivia())); } displayParts = replaceNode ? symbol.ToDisplayParts(s_typeNameFormatWithGenerics) : (symbol.ContainingType ?? (ISymbol)symbol.ContainingNamespace).ToDisplayParts(s_typeNameFormatWithGenerics); rewrittenNode = TryAddTypeArgumentToIdentifierName(rewrittenNode, symbol); // Replaces the '<' token with the '{' token since we are inside crefs rewrittenNode = TryReplaceAngleBracesWithCurlyBraces(rewrittenNode, isInsideCref); result = rewrittenNode; if (!omitLeftHandSide) { left = SyntaxFactory.ParseTypeName(displayParts.ToDisplayString()); // Replaces the '<' token with the '{' token since we are inside crefs left = TryReplaceAngleBracesWithCurlyBraces(left, isInsideCref); if (replaceNode) { return left .WithLeadingTrivia(rewrittenNode.GetLeadingTrivia()) .WithTrailingTrivia(rewrittenNode.GetTrailingTrivia()); } // now create syntax for the combination of left and right syntax, or a simple replacement in case of an identifier var parent = originalNode.Parent; var leadingTrivia = rewrittenNode.GetLeadingTrivia(); rewrittenNode = rewrittenNode.WithLeadingTrivia(null); switch (parent.Kind()) { case SyntaxKind.QualifiedName: var qualifiedParent = (QualifiedNameSyntax)parent; result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.QualifiedName( (NameSyntax)left, (SimpleNameSyntax)rewrittenNode)); break; case SyntaxKind.SimpleMemberAccessExpression: var memberAccessParent = (MemberAccessExpressionSyntax)parent; result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, (SimpleNameSyntax)rewrittenNode)); break; default: Debug.Assert(rewrittenNode is SimpleNameSyntax); if (SyntaxFacts.IsInNamespaceOrTypeContext(originalNode)) { var right = (SimpleNameSyntax)rewrittenNode; result = rewrittenNode.CopyAnnotationsTo(SyntaxFactory.QualifiedName((NameSyntax)left, right.WithAdditionalAnnotations(Simplifier.SpecialTypeAnnotation))); } else if (originalNode.Parent is CrefSyntax) { var right = (SimpleNameSyntax)rewrittenNode; result = rewrittenNode.CopyAnnotationsTo(SyntaxFactory.QualifiedName((NameSyntax)left, right)); } else { result = rewrittenNode.CopyAnnotationsTo( SyntaxFactory.MemberAccessExpression( SyntaxKind.SimpleMemberAccessExpression, left, (SimpleNameSyntax)rewrittenNode)); } break; } result = result.WithLeadingTrivia(leadingTrivia); } } return result; } private SyntaxToken ReplaceTokenForCref(SyntaxToken oldToken, SyntaxToken dummySameToken) { if (oldToken.Kind() == SyntaxKind.LessThanToken) { return SyntaxFactory.Token(oldToken.LeadingTrivia, SyntaxKind.LessThanToken, "{", "{", oldToken.TrailingTrivia); } if (oldToken.Kind() == SyntaxKind.GreaterThanToken) { return SyntaxFactory.Token(oldToken.LeadingTrivia, SyntaxKind.GreaterThanToken, "}", "}", oldToken.TrailingTrivia); } Debug.Assert(false, "This method is used only replacing the '<' and '>' to '{' and '}' respectively"); return default; } private bool IsTypeOfUnboundGenericType(SemanticModel semanticModel, TypeOfExpressionSyntax typeOfExpression) { if (typeOfExpression != null) { var type = semanticModel.GetTypeInfo(typeOfExpression.Type, _cancellationToken).Type as INamedTypeSymbol; // It's possible the immediate type might not be an unbound type, such as typeof(A<>.B). So walk through // parent types too while (type != null) { if (type.IsUnboundGenericType) { return true; } type = type.ContainingType; } } return false; } public override SyntaxNode VisitInvocationExpression(InvocationExpressionSyntax originalNode) { if (this._semanticModel.GetSymbolInfo(originalNode).Symbol.IsLocalFunction()) { return originalNode; } var rewrittenNode = (InvocationExpressionSyntax)base.VisitInvocationExpression(originalNode); if (originalNode.Expression.IsKind(SyntaxKind.SimpleMemberAccessExpression)) { var memberAccess = (MemberAccessExpressionSyntax)originalNode.Expression; var targetSymbol = SimplificationHelpers.GetOriginalSymbolInfo(_semanticModel, memberAccess.Name); if (targetSymbol != null && targetSymbol.IsReducedExtension() && memberAccess.Expression != null) { rewrittenNode = RewriteExtensionMethodInvocation(originalNode, rewrittenNode, ((MemberAccessExpressionSyntax)rewrittenNode.Expression).Expression, (IMethodSymbol)targetSymbol); } } return rewrittenNode; } private InvocationExpressionSyntax RewriteExtensionMethodInvocation( InvocationExpressionSyntax originalNode, InvocationExpressionSyntax rewrittenNode, ExpressionSyntax thisExpression, IMethodSymbol reducedExtensionMethod) { var originalMemberAccess = (MemberAccessExpressionSyntax)originalNode.Expression; if (originalMemberAccess.GetParentConditionalAccessExpression() != null) { // Bail out on extension method invocations in conditional access expression. // Note that this is a temporary workaround for https://github.com/dotnet/roslyn/issues/2593. // Issue https://github.com/dotnet/roslyn/issues/3260 tracks fixing this workaround. return rewrittenNode; } var expression = RewriteExtensionMethodInvocation(rewrittenNode, thisExpression, reducedExtensionMethod, s_typeNameFormatWithoutGenerics); // Let's rebind this and verify the original method is being called properly var binding = _semanticModel.GetSpeculativeSymbolInfo(originalNode.SpanStart, expression, SpeculativeBindingOption.BindAsExpression); if (binding.Symbol != null) { return expression; } // We'll probably need generic type arguments as well return RewriteExtensionMethodInvocation(rewrittenNode, thisExpression, reducedExtensionMethod, s_typeNameFormatWithGenerics); } private InvocationExpressionSyntax RewriteExtensionMethodInvocation( InvocationExpressionSyntax originalNode, ExpressionSyntax thisExpression, IMethodSymbol reducedExtensionMethod, SymbolDisplayFormat symbolDisplayFormat) { var containingType = reducedExtensionMethod.ContainingType.ToDisplayString(symbolDisplayFormat); var newMemberAccess = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseExpression(containingType), ((MemberAccessExpressionSyntax)originalNode.Expression).OperatorToken, ((MemberAccessExpressionSyntax)originalNode.Expression).Name) .WithLeadingTrivia(thisExpression.GetFirstToken().LeadingTrivia); // Copies the annotation for the member access expression newMemberAccess = originalNode.Expression.CopyAnnotationsTo(newMemberAccess).WithAdditionalAnnotations(Simplifier.Annotation); var thisArgument = SyntaxFactory.Argument(thisExpression).WithLeadingTrivia(SyntaxTriviaList.Empty); // Copies the annotation for the left hand side of the member access expression to the first argument in the complexified form thisArgument = ((MemberAccessExpressionSyntax)originalNode.Expression).Expression.CopyAnnotationsTo(thisArgument); var arguments = originalNode.ArgumentList.Arguments.Insert(0, thisArgument); var replacementNode = SyntaxFactory.InvocationExpression( newMemberAccess, originalNode.ArgumentList.WithArguments(arguments)); // This Annotation copy is for the InvocationExpression return originalNode.CopyAnnotationsTo(replacementNode).WithAdditionalAnnotations(Simplifier.Annotation, Formatter.Annotation); } } } }
49.699458
295
0.540741
[ "BSD-2-Clause", "MIT" ]
encrypt0r/stark
src/compiler/StarkPlatform.Compiler.Stark.Workspaces/Simplification/CSharpSimplificationService.Expander.cs
55,069
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.Diagnostics; namespace System.Xml { internal sealed class Base64Decoder : IncrementalReadDecoder { // // Fields // private byte[]? _buffer; private int _startIndex; private int _curIndex; private int _endIndex; private int _bits; private int _bitsFilled; private const string CharsBase64 = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789+/"; private static readonly byte[] s_mapBase64 = ConstructMapBase64(); private const int MaxValidChar = (int)'z'; private const byte Invalid = unchecked((byte)-1); // // IncrementalReadDecoder interface // internal override int DecodedCount { get { return _curIndex - _startIndex; } } internal override bool IsFull { get { return _curIndex == _endIndex; } } internal override int Decode(char[] chars, int startPos, int len) { if (chars == null) { throw new ArgumentNullException(nameof(chars)); } if (len < 0) { throw new ArgumentOutOfRangeException(nameof(len)); } if (startPos < 0) { throw new ArgumentOutOfRangeException(nameof(startPos)); } if (chars.Length - startPos < len) { throw new ArgumentOutOfRangeException(nameof(len)); } if (len == 0) { return 0; } Decode( chars.AsSpan(startPos, len), _buffer.AsSpan(_curIndex, _endIndex - _curIndex), out int charsDecoded, out int bytesDecoded ); _curIndex += bytesDecoded; return charsDecoded; } internal override int Decode(string str, int startPos, int len) { if (str == null) { throw new ArgumentNullException(nameof(str)); } if (len < 0) { throw new ArgumentOutOfRangeException(nameof(len)); } if (startPos < 0) { throw new ArgumentOutOfRangeException(nameof(startPos)); } if (str.Length - startPos < len) { throw new ArgumentOutOfRangeException(nameof(len)); } if (len == 0) { return 0; } Decode( str.AsSpan(startPos, len), _buffer.AsSpan(_curIndex, _endIndex - _curIndex), out int charsDecoded, out int bytesDecoded ); _curIndex += bytesDecoded; return charsDecoded; } internal override void Reset() { _bitsFilled = 0; _bits = 0; } internal override void SetNextOutputBuffer(Array buffer, int index, int count) { Debug.Assert(buffer != null); Debug.Assert(count >= 0); Debug.Assert(index >= 0); Debug.Assert(buffer.Length - index >= count); Debug.Assert((buffer as byte[]) != null); _buffer = (byte[])buffer; _startIndex = index; _curIndex = index; _endIndex = index + count; } // // Private methods // private static byte[] ConstructMapBase64() { byte[] mapBase64 = new byte[MaxValidChar + 1]; for (int i = 0; i < mapBase64.Length; i++) { mapBase64[i] = Invalid; } for (int i = 0; i < CharsBase64.Length; i++) { mapBase64[(int)CharsBase64[i]] = (byte)i; } return mapBase64; } private void Decode( ReadOnlySpan<char> chars, Span<byte> bytes, out int charsDecoded, out int bytesDecoded ) { // walk hex digits pairing them up and shoving the value of each pair into a byte int iByte = 0; int iChar = 0; int b = _bits; int bFilled = _bitsFilled; while ((uint)iChar < (uint)chars.Length) { if ((uint)iByte >= (uint)bytes.Length) { break; // ran out of space in the destination buffer } char ch = chars[iChar]; // end? if (ch == '=') { break; } iChar++; // ignore whitespace if (XmlCharType.IsWhiteSpace(ch)) { continue; } int digit; if (ch > 122 || (digit = s_mapBase64[ch]) == Invalid) { throw new XmlException(SR.Xml_InvalidBase64Value, chars.ToString()); } b = (b << 6) | digit; bFilled += 6; if (bFilled >= 8) { // get top eight valid bits bytes[iByte++] = (byte)((b >> (bFilled - 8)) & 0xFF); bFilled -= 8; if (iByte == bytes.Length) { goto Return; } } } if ((uint)iChar < (uint)chars.Length && chars[iChar] == '=') { bFilled = 0; // ignore padding chars do { iChar++; } while ((uint)iChar < (uint)chars.Length && chars[iChar] == '='); // ignore whitespace after the padding chars while ((uint)iChar < (uint)chars.Length) { if (!XmlCharType.IsWhiteSpace(chars[iChar++])) { throw new XmlException(SR.Xml_InvalidBase64Value, chars.ToString()); } } } Return: _bits = b; _bitsFilled = bFilled; bytesDecoded = iByte; charsDecoded = iChar; } } }
28.571429
93
0.444848
[ "MIT" ]
belav/runtime
src/libraries/System.Private.Xml/src/System/Xml/Base64Decoder.cs
6,600
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.Collections.Generic; using Newtonsoft.Json; using Aliyun.Acs.Core; using Aliyun.Acs.Core.Http; using Aliyun.Acs.Core.Transform; using Aliyun.Acs.Core.Utils; using Aliyun.Acs.dms_enterprise.Transform; using Aliyun.Acs.dms_enterprise.Transform.V20181101; namespace Aliyun.Acs.dms_enterprise.Model.V20181101 { public class ListInstancesRequest : RpcAcsRequest<ListInstancesResponse> { public ListInstancesRequest() : base("dms-enterprise", "2018-11-01", "ListInstances", "dmsenterprise", "openAPI") { if (this.GetType().GetProperty("ProductEndpointMap") != null && this.GetType().GetProperty("ProductEndpointType") != null) { this.GetType().GetProperty("ProductEndpointMap").SetValue(this, Endpoint.endpointMap, null); this.GetType().GetProperty("ProductEndpointType").SetValue(this, Endpoint.endpointRegionalType, null); } } private string searchKey; private long? tid; private string instanceState; private int? pageNumber; private string netType; private string dbType; private string envType; private string instanceSource; private int? pageSize; public string SearchKey { get { return searchKey; } set { searchKey = value; DictionaryUtil.Add(QueryParameters, "SearchKey", value); } } public long? Tid { get { return tid; } set { tid = value; DictionaryUtil.Add(QueryParameters, "Tid", value.ToString()); } } public string InstanceState { get { return instanceState; } set { instanceState = value; DictionaryUtil.Add(QueryParameters, "InstanceState", value); } } public int? PageNumber { get { return pageNumber; } set { pageNumber = value; DictionaryUtil.Add(QueryParameters, "PageNumber", value.ToString()); } } public string NetType { get { return netType; } set { netType = value; DictionaryUtil.Add(QueryParameters, "NetType", value); } } public string DbType { get { return dbType; } set { dbType = value; DictionaryUtil.Add(QueryParameters, "DbType", value); } } public string EnvType { get { return envType; } set { envType = value; DictionaryUtil.Add(QueryParameters, "EnvType", value); } } public string InstanceSource { get { return instanceSource; } set { instanceSource = value; DictionaryUtil.Add(QueryParameters, "InstanceSource", value); } } public int? PageSize { get { return pageSize; } set { pageSize = value; DictionaryUtil.Add(QueryParameters, "PageSize", value.ToString()); } } public override ListInstancesResponse GetResponse(UnmarshallerContext unmarshallerContext) { return ListInstancesResponseUnmarshaller.Unmarshall(unmarshallerContext); } } }
21.505435
134
0.639373
[ "Apache-2.0" ]
bbs168/aliyun-openapi-net-sdk
aliyun-net-sdk-dms-enterprise/Dms_enterprise/Model/V20181101/ListInstancesRequest.cs
3,957
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. using Microsoft.CodeAnalysis.CodeStyle; using Microsoft.CodeAnalysis.CSharp.CodeStyle; using Microsoft.CodeAnalysis.CSharp.Extensions; using Microsoft.CodeAnalysis.CSharp.Syntax; using Microsoft.CodeAnalysis.Diagnostics; using Microsoft.CodeAnalysis.Operations; using Microsoft.CodeAnalysis.RemoveUnusedParametersAndValues; namespace Microsoft.CodeAnalysis.CSharp.RemoveUnusedParametersAndValues { [DiagnosticAnalyzer(LanguageNames.CSharp)] internal sealed class CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer : AbstractRemoveUnusedParametersAndValuesDiagnosticAnalyzer { public CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer() : base(unusedValueExpressionStatementOption: CSharpCodeStyleOptions.UnusedValueExpressionStatement, unusedValueAssignmentOption: CSharpCodeStyleOptions.UnusedValueAssignment, LanguageNames.CSharp) { } protected override bool IsRecordDeclaration(SyntaxNode node) => node is RecordDeclarationSyntax; protected override bool SupportsDiscard(SyntaxTree tree) => tree.Options.LanguageVersion() >= LanguageVersion.CSharp7; protected override bool MethodHasHandlesClause(IMethodSymbol method) => false; protected override bool IsIfConditionalDirective(SyntaxNode node) => node is IfDirectiveTriviaSyntax; protected override CodeStyleOption2<UnusedValuePreference> GetUnusedValueExpressionStatementOption(AnalyzerOptionsProvider provider) => ((CSharpAnalyzerOptionsProvider)provider).UnusedValueExpressionStatement; protected override CodeStyleOption2<UnusedValuePreference> GetUnusedValueAssignmentOption(AnalyzerOptionsProvider provider) => ((CSharpAnalyzerOptionsProvider)provider).UnusedValueAssignment; protected override bool ShouldBailOutFromRemovableAssignmentAnalysis(IOperation unusedSymbolWriteOperation) { // We don't want to recommend removing the write operation if it is within a statement // that is not parented by an explicit block with curly braces. // For example, assignment to 'x' in 'if (...) x = 1;' // Replacing 'x = 1' with an empty statement ';' is not useful, and user is most likely // going to remove the entire if statement in this case. However, we don't // want to suggest removing the entire if statement as that might lead to change of semantics. // So, we conservatively bail out from removable assignment analysis for such cases. var statementAncestor = unusedSymbolWriteOperation.Syntax.FirstAncestorOrSelf<StatementSyntax>()?.Parent; switch (statementAncestor) { case BlockSyntax _: case SwitchSectionSyntax _: return false; default: return true; } } // C# does not have an explicit "call" statement syntax for invocations with explicit value discard. protected override bool IsCallStatement(IExpressionStatementOperation expressionStatement) => false; protected override bool IsExpressionOfExpressionBody(IExpressionStatementOperation expressionStatementOperation) => expressionStatementOperation.Parent is IBlockOperation blockOperation && !blockOperation.Syntax.IsKind(SyntaxKind.Block); protected override Location GetDefinitionLocationToFade(IOperation unusedDefinition) { switch (unusedDefinition.Syntax) { case VariableDeclaratorSyntax variableDeclarator: return variableDeclarator.Identifier.GetLocation(); case DeclarationPatternSyntax declarationPattern: return declarationPattern.Designation.GetLocation(); default: // C# syntax node for foreach statement has no syntax node for the loop control variable declaration, // so the operation tree has an IVariableDeclaratorOperation with the syntax mapped to the type node syntax instead of variable declarator syntax. // Check if the unused definition syntax is the foreach statement's type node. if (unusedDefinition.Syntax.Parent is ForEachStatementSyntax forEachStatement && forEachStatement.Type == unusedDefinition.Syntax) { return forEachStatement.Identifier.GetLocation(); } return unusedDefinition.Syntax.GetLocation(); } } } }
50.459184
166
0.696461
[ "MIT" ]
BillWagner/roslyn
src/Analyzers/CSharp/Analyzers/RemoveUnusedParametersAndValues/CSharpRemoveUnusedParametersAndValuesDiagnosticAnalyzer.cs
4,947
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace DS { public class DataSource { public static List<BE.Test> testsList = new List<BE.Test>(); public static List<BE.Tester> testerList = new List<BE.Tester>(); public static List<BE.Trainee> traineeList = new List<BE.Trainee>(); } }
20.555556
70
0.735135
[ "MIT" ]
arielsabag/Project01_2058_3292_dotNet5779
Project01_2058_3292_dotNet5779/DS/DataSource.cs
372
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // La información general de un ensamblado se controla mediante el siguiente // conjunto de atributos. Cambie estos valores de atributo para modificar la información // asociada con un ensamblado. [assembly: AssemblyTitle("WindowsApp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("WindowsApp")] [assembly: AssemblyCopyright("Copyright © 2017")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Si establece ComVisible en false, los tipos de este ensamblado no estarán visibles // para los componentes COM. Si necesita obtener acceso a un tipo de este ensamblado desde // COM, establezca el atributo ComVisible en true en este tipo. [assembly: ComVisible(false)] // El siguiente GUID sirve como id. de typelib si este proyecto se expone a COM. [assembly: Guid("c8269d00-935d-445d-83e6-cd9f5e4141f3")] // La información de versión de un ensamblado consta de los cuatro valores siguientes: // // Versión principal // Versión secundaria // Número de compilación // Revisión // // Puede especificar todos los valores o usar los valores predeterminados de número de compilación y de revisión // mediante el carácter '*', como se muestra a continuación: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
40.891892
113
0.756114
[ "MIT" ]
Roberto95/NURCON
NURCON/WindowsApp/Properties/AssemblyInfo.cs
1,531
C#
// Copyright (c) .NET Foundation and Contributors (https://dotnetfoundation.org/ & https://stride3d.net) and Silicon Studio Corp. (https://www.siliconstudio.co.jp) // Distributed under the MIT license. See the LICENSE.md file in the project root for more information. using System; using Stride.Core; using Stride.Core.Mathematics; using Stride.Particles.DebugDraw; namespace Stride.Particles.Updaters.FieldShapes { [DataContract("FieldShapeCylinder")] public class Cylinder : FieldShape { public override DebugDrawShape GetDebugDrawShape(out Vector3 pos, out Quaternion rot, out Vector3 scl) { pos = Vector3.Zero; rot = Quaternion.Identity; scl = new Vector3(radius * 2, halfHeight * 2, radius * 2); return DebugDrawShape.Cylinder; } [DataMemberIgnore] private Vector3 fieldPosition; [DataMemberIgnore] private Quaternion fieldRotation; [DataMemberIgnore] private Quaternion inverseRotation; [DataMemberIgnore] private Vector3 fieldSize; [DataMemberIgnore] private Vector3 mainAxis; /// <summary> /// The maximum distance from the origin along the Y axis. The height is twice as big. /// </summary> /// <userdoc> /// The maximum distance from the origin along the Y axis. The height is twice as big. /// </userdoc> [DataMember(10)] [Display("Half height")] public float HalfHeight { get { return halfHeight > MathUtil.ZeroTolerance ? halfHeight : 0; } set { halfHeight = value > MathUtil.ZeroTolerance ? value : MathUtil.ZeroTolerance; } } private float halfHeight = 1f; /// <summary> /// The maximum distance from the central axis. /// </summary> /// <userdoc> /// The maximum distance from the central axis. /// </userdoc> [DataMember(20)] [Display("Radius")] public float Radius { get { return radius > MathUtil.ZeroTolerance ? radius : 0; } set { radius = value > MathUtil.ZeroTolerance ? value : MathUtil.ZeroTolerance; } } private float radius = 1f; public override void PreUpdateField(Vector3 position, Quaternion rotation, Vector3 size) { fieldSize = size; fieldPosition = position; fieldRotation = rotation; inverseRotation = new Quaternion(-rotation.X, -rotation.Y, -rotation.Z, rotation.W); mainAxis = new Vector3(0, 1, 0); rotation.Rotate(ref mainAxis); } public override float GetDistanceToCenter( Vector3 particlePosition, Vector3 particleVelocity, out Vector3 alongAxis, out Vector3 aroundAxis, out Vector3 awayAxis) { // Along - following the main axis alongAxis = mainAxis; // Toward - tawards the main axis awayAxis = particlePosition - fieldPosition; awayAxis.Y = 0; // In case of cylinder the away vector should be flat (away from the axis rather than just a point) awayAxis.Normalize(); // Around - around the main axis, following the right hand rule aroundAxis = Vector3.Cross(alongAxis, awayAxis); particlePosition -= fieldPosition; inverseRotation.Rotate(ref particlePosition); particlePosition /= fieldSize; // Start of code for Cylinder if (Math.Abs(particlePosition.Y) >= halfHeight) return 1; particlePosition.Y = 0; particlePosition.X /= radius; particlePosition.Z /= radius; var maxDist = particlePosition.Length(); // End of code for Cylinder return maxDist; } public override bool IsPointInside(Vector3 particlePosition, out Vector3 surfacePoint, out Vector3 surfaceNormal) { particlePosition -= fieldPosition; inverseRotation.Rotate(ref particlePosition); // particlePosition /= fieldSize; var maxDist = MathF.Sqrt(particlePosition.X * particlePosition.X + particlePosition.Z * particlePosition.Z); var fieldX = radius * fieldSize.X; var fieldY = halfHeight * fieldSize.Y; var fieldZ = radius * fieldSize.Z; var roundSurface = particlePosition; roundSurface.Y = 0; roundSurface.X /= fieldX; roundSurface.Z /= fieldZ; roundSurface.Normalize(); roundSurface.X *= fieldX; roundSurface.Z *= fieldZ; var fieldRadius = roundSurface.Length(); var isOutside = (maxDist > fieldRadius) || (Math.Abs(particlePosition.Y) > fieldY); var surfaceY = particlePosition.Y >= 0 ? fieldY : -fieldY; var distR = Math.Abs(maxDist - fieldRadius); var distY = Math.Abs(particlePosition.Y - surfaceY); if (distR <= distY) { surfacePoint = roundSurface; surfaceNormal = surfacePoint; surfaceNormal.X /= fieldX; surfaceNormal.Z /= fieldZ; surfacePoint.Y = particlePosition.Y; } else { // Biggest distance is on the X axis surfacePoint.X = particlePosition.X; surfacePoint.Y = 0; surfacePoint.Z = particlePosition.Z; surfacePoint.Y = surfaceY; surfaceNormal = surfaceY > 0 ? new Vector3(0, 1, 0) : new Vector3(0, -1, 0); } if (isOutside) { surfacePoint.Y = Math.Min(surfacePoint.Y, fieldY); surfacePoint.Y = Math.Max(surfacePoint.Y, -fieldY); if (Math.Abs(surfacePoint.X) > Math.Abs(roundSurface.X)) surfacePoint.X = roundSurface.X; if (Math.Abs(surfacePoint.Z) > Math.Abs(roundSurface.Z)) surfacePoint.Z = roundSurface.Z; } // Fix the surface point and normal to world space surfaceNormal /= fieldSize; fieldRotation.Rotate(ref surfaceNormal); surfaceNormal.Normalize(); fieldRotation.Rotate(ref surfacePoint); // surfacePoint *= fieldSize; surfacePoint += fieldPosition; // Is the point inside the cylinder? return !isOutside; } } }
34.5625
163
0.579265
[ "MIT" ]
Alan-love/xenko
sources/engine/Stride.Particles/Updaters/FieldShapes/Cylinder.cs
6,636
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.RazorPages; using EC_Website.Core.Entities.ForumModel; using EC_Website.Core.Interfaces.Repositories; using EC_Website.Web.Authorization; namespace EC_Website.Web.Pages.Forums.Thread { [Authorize] public class EditPostModel : PageModel { private readonly IForumRepository _forumRepository; private readonly IAuthorizationService _authorization; public EditPostModel(IForumRepository forumRepository, IAuthorizationService authorization) { _forumRepository = forumRepository; _authorization = authorization; } [BindProperty] public Post Post { get; set; } public async Task<IActionResult> OnGetAsync(string postId) { if (postId == null) { return NotFound(); } Post = await _forumRepository.GetByIdAsync<Post>(postId); if (Post == null) { return NotFound(); } ViewData.Add("toolbar", new[] { "Bold", "Italic", "Underline", "StrikeThrough", "FontSize", "FontColor", "|", "Formats", "Alignments", "OrderedList", "UnorderedList", "|", "CreateLink", "Image", "|", "SourceCode" }); var hasPolicyToEdit = await _authorization.AuthorizeAsync(User, Policies.CanManageForums); if (Post.Author.UserName == User.Identity.Name || hasPolicyToEdit.Succeeded) { return Page(); } return LocalRedirect("/Identity/Account/AccessDenied"); } public async Task<IActionResult> OnPostAsync() { if (!ModelState.IsValid) { return Page(); } var post = await _forumRepository.GetByIdAsync<Post>(Post.Id); if (post == null) { return NotFound(); } post.Content = Post.Content; await _forumRepository.UpdateAsync(post); return RedirectToPage("./Index", new { slug = Post.Thread.Slug }); } } }
29.844156
102
0.570061
[ "MIT" ]
suxrobGM/EC_WebSite
src/EC_Website.Web/Pages/Forums/Thread/EditPost.cshtml.cs
2,300
C#
using Locust.ServiceModel; namespace Locust.Modules.Location.Strategies { public partial class StateGetAllRequest : IBaseServiceRequest { } }
17.111111
62
0.766234
[ "MIT" ]
mansoor-omrani/Locust.NET
Modules/Locust.Modules.Location/Service/State/GetAll/Request.cs
154
C#
using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; namespace SpellforceDataEditor.SFCFF.category_forms { public partial class Control44 : SpellforceDataEditor.SFCFF.category_forms.SFControl { public Control44() { InitializeComponent(); column_dict.Add("Weapon type ID", new int[1] { 0 }); column_dict.Add("Text ID", new int[1] { 1 }); column_dict.Add("Unknown", new int[1] { 2 }); } private void tb_effID_TextChanged(object sender, EventArgs e) { set_element_variant(current_element, 0, Utility.TryParseUInt16(tb_effID.Text)); } private void textBox1_TextChanged(object sender, EventArgs e) { set_element_variant(current_element, 1, Utility.TryParseUInt16(textBox1.Text)); } private void textBox2_TextChanged(object sender, EventArgs e) { set_element_variant(current_element, 2, Utility.TryParseUInt8(textBox2.Text)); } public override void show_element() { tb_effID.Text = variant_repr(0); textBox1.Text = variant_repr(1); textBox2.Text = variant_repr(2); } private void textBox1_MouseDown(object sender, MouseEventArgs e) { if (e.Button == MouseButtons.Right) step_into(textBox1, 2016); } public override string get_element_string(int index) { UInt16 elem_id = (UInt16)category[index][0]; string txt = SFCategoryManager.GetTextFromElement(category[index], 1); return elem_id.ToString() + " " + txt; } } }
30.716667
91
0.626696
[ "MIT" ]
leszekd25/spellforce_data_editor
SpellforceDataEditor/SFCFF/category forms/Control44.cs
1,845
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 ParameterSetttingUI.Properties { using System; /// <summary> /// A strongly-typed resource class, for looking up localized strings, etc. /// </summary> // This class was auto-generated by the StronglyTypedResourceBuilder // class via a tool like ResGen or Visual Studio. // To add or remove a member, edit your .ResX file then rerun ResGen // with the /str option, or rebuild your VS project. [global::System.CodeDom.Compiler.GeneratedCodeAttribute("System.Resources.Tools.StronglyTypedResourceBuilder", "16.0.0.0")] [global::System.Diagnostics.DebuggerNonUserCodeAttribute()] [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] internal class Resources { private static global::System.Resources.ResourceManager resourceMan; private static global::System.Globalization.CultureInfo resourceCulture; [global::System.Diagnostics.CodeAnalysis.SuppressMessageAttribute("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")] internal Resources() { } /// <summary> /// Returns the cached ResourceManager instance used by this class. /// </summary> [global::System.ComponentModel.EditorBrowsableAttribute(global::System.ComponentModel.EditorBrowsableState.Advanced)] internal static global::System.Resources.ResourceManager ResourceManager { get { if (object.ReferenceEquals(resourceMan, null)) { global::System.Resources.ResourceManager temp = new global::System.Resources.ResourceManager("ParameterSetttingUI.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; } } } }
43.78125
185
0.615632
[ "MIT" ]
strawberryfg/NAPA-NST-HPE
annotation_tools/mpii_annotator/ThreeDGroundTruthLabeler/ParameterSetttingUI/ParameterSetttingUI/Properties/Resources.Designer.cs
2,804
C#
using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; using AElf.OS.Rpc; using Anemonis.AspNetCore.JsonRpc; namespace AElf.Monitor { [Path("/monitor")] public class AkkaService :IJsonRpcService { [JsonRpcMethod("AkkaState")] public Task<List<MemberInfo>> ClusterState() { return Task.FromResult(AkkaClusterState.MemberInfos.Values.ToList()); } } }
24.333333
81
0.680365
[ "MIT" ]
380086154/AElf
src/AElf.Monitor/AkkaService.cs
440
C#
using System; using System.Collections.Generic; using System.Text; namespace MedicalRecord.Model { public class FullMedicalRecord { public int Year { get; set; } public int RecordId { get; set; } public DateTime ChargeDate { get; set; } public DateTime DischargeDate { get; set; } public string RelativePhoneNumber { get; set; } public string PaymentType { get; set; } public int InpatientDays { get; set; } public int DoctorId { get; set; } public int NurseId { get; set; } public int PatientId { get; set; } public int WardId { get; set; } public string Disease { get; set; } } }
20.676471
55
0.603129
[ "MIT" ]
npovalyaeva/Medical-information-system
MedicalRecord/Model/FullMedicalRecord.cs
705
C#
//********************************************************* // // Copyright (c) Microsoft. All rights reserved. // //********************************************************* using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.Devices.Enumeration; namespace CustomHidDeviceAccess { /// <summary> /// The class will only expose properties from DeviceInformation that are going to be used /// in this sample. Each instance of this class provides information about a single device. /// /// This class is used by the UI to display device specific information so that /// the user can identify which device to use. /// </summary> public class DeviceListEntry { private DeviceInformation device; private String deviceSelector; public String InstanceId { get { return (String)device.Properties[DeviceProperties.DeviceInstanceId]; } } public DeviceInformation DeviceInformation { get { return device; } } public String DeviceSelector { get { return deviceSelector; } } /// <summary> /// The class is mainly used as a DeviceInformation wrapper so that the UI can bind to a list of these. /// </summary> /// <param name="deviceInformation"></param> /// <param name="deviceSelector">The AQS used to find this device</param> public DeviceListEntry(Windows.Devices.Enumeration.DeviceInformation deviceInformation, String deviceSelector) { device = deviceInformation; this.deviceSelector = deviceSelector; } } }
28.553846
118
0.566272
[ "MIT" ]
035/Windows-universal-samples
customhiddeviceaccess/cs/devicelistentry.cs
1,858
C#
using System.Collections; using System.Collections.Generic; using TMPro; using UnityEngine; public class BaseHealthDisplay : MonoBehaviour { [SerializeField] private GameManagerTD gameManager = null; [SerializeField] private TMP_Text livesValue = null; private void Awake() { gameManager.HandleEnemyGoal += HandleGoalReached; } private void OnDestroy() { gameManager.HandleEnemyGoal -= HandleGoalReached; } private void HandleGoalReached(int remainingLives) { livesValue.text = remainingLives.ToString(); } }
21.851852
62
0.7
[ "Apache-2.0" ]
garthbjorn/JTD
Assets/Scripts/Misc/BaseHealthDisplay.cs
590
C#
namespace _07InfernoInfinity.Models.Gems { public class Ruby : Gem { public Ruby(string clarityType) : base(7, 2, 5, clarityType) { } } }
22.571429
72
0.632911
[ "MIT" ]
StackSmack007/OOP-Advanced
Reflection and Attributes - Exercise/07InfernoInfinity/Models/Gems/Ruby.cs
160
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Menu_Toolbar { /// <summary> /// Interaktionslogik für MainWindow.xaml /// </summary> public partial class MainWindow : Window { public MainWindow() { InitializeComponent(); } } }
21.862069
45
0.716088
[ "MIT" ]
ablersch/software-developer-ihk-modul-3
Beispiele/15_Menu_Toolbar/MainWindow.xaml.cs
637
C#
using MasterDevs.ChromeDevTools; using Newtonsoft.Json; using System; using System.Collections.Generic; namespace MasterDevs.ChromeDevTools.Protocol.iOS.Worker { [Command(ProtocolName.Worker.Enable)] [SupportedBy("iOS")] public class EnableCommand: ICommand<EnableCommandResponse> { } }
20.928571
60
0.805461
[ "MIT" ]
Digitalbil/ChromeDevTools
source/ChromeDevTools/Protocol/iOS/Worker/EnableCommand.cs
293
C#
using System; using CitizenFX.Core.Native; namespace CitizenFX.Core { public sealed class VehicleWheel { #region Fields Vehicle _owner; #endregion internal VehicleWheel(Vehicle owner, int index) { _owner = owner; Index = index; } public int Index { get; private set; } public Vehicle Vehicle { get { return _owner; } } public void Burst() { API.SetVehicleTyreBurst(_owner.Handle, Index, true, 1000f); } public void Fix() { API.SetVehicleTyreFixed(_owner.Handle, Index); } } }
14.777778
62
0.672932
[ "MIT" ]
0x965/fivem
code/client/clrcore/External/VehicleWheel.cs
532
C#
namespace PhoneManagementSystem.Models { using System; using System.ComponentModel.DataAnnotations.Schema; using System.Text; public class Service { public int Id { get; set; } //TYPE public string Type { get; set; } //LABEL public string Label { get; set; } //SDATE public DateTime? StartDate { get; set; } //EDATE public DateTime? EndDate { get; set; } //AMOUNT public decimal? Amount { get; set; } //USAGE can be int, time, decimal public string Usage { get; set; } //MONTH public DateTime? Month { get; set; } //INCLMIN public TimeSpan? IncludedMin { get; set; } //USEDMIN public TimeSpan? UsedMin { get; set; } public int InvoiceDataId { get; set; } public virtual InvoiceData InvoiceData { get; set; } public override string ToString() { var sb = new StringBuilder(); sb.AppendFormat("{0} ---- {1}\n{2} ---- {3}\n{4}\n{5}\n{6}\n{7}----{8}", this.Type, this.Label, this.StartDate, this.EndDate, this.Amount, this.Usage, this.Month, this.IncludedMin, this.UsedMin); return sb.ToString(); } } }
26.471698
84
0.498931
[ "MIT" ]
andrei-bozhilov/Phone-Management-System
PhoneManagementSystem.Models/Service.cs
1,405
C#
using System.Runtime.InteropServices; namespace DecryptESD.IO { [StructLayout(LayoutKind.Explicit, Size = 24)] public struct ResourceHeader { [FieldOffset(0)] public ulong SizeInWimWithFlags; [FieldOffset(7)] public ResourceHeaderFlags Flags; [FieldOffset(8)] public long OffsetInWim; [FieldOffset(16)] public ulong OriginalSize; public ulong SizeInWim => SizeInWimWithFlags & 0xFFFFFFFFFFFFFF; } }
21.363636
70
0.685106
[ "BSD-3-Clause" ]
evilpro/DecryptESD
DecryptESD/IO/ResourceHeader.cs
472
C#
/* * Copyright (c) Contributors, http://opensimulator.org/ * See CONTRIBUTORS.TXT for a full list of copyright holders. * * Redistribution and use in source and binary forms, with or without * modification, are permitted provided that the following conditions are met: * * Redistributions of source code must retain the above copyright * notice, this list of conditions and the following disclaimer. * * Redistributions in binary form must reproduce the above copyright * notice, this list of conditions and the following disclaimer in the * documentation and/or other materials provided with the distribution. * * Neither the name of the OpenSimulator Project nor the * names of its contributors may be used to endorse or promote products * derived from this software without specific prior written permission. * * THIS SOFTWARE IS PROVIDED BY THE DEVELOPERS ``AS IS'' AND ANY * EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE * DISCLAIMED. IN NO EVENT SHALL THE CONTRIBUTORS BE LIABLE FOR ANY * DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES * (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; * LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND * ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS * SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. */ using System; using System.Reflection; using OpenMetaverse; using OpenMetaverse.StructuredData; using log4net; using OpenSim.Services.Interfaces; using OpenSim.Framework.Servers.HttpServer; using OpenSim.Framework; namespace OpenSim.Server.Handlers { public class UserProfilesHandlers { public UserProfilesHandlers () { } } public class JsonRpcProfileHandlers { static readonly ILog m_log = LogManager.GetLogger( MethodBase.GetCurrentMethod().DeclaringType); public IUserProfilesService Service { get; private set; } public JsonRpcProfileHandlers(IUserProfilesService service) { Service = service; } #region Classifieds /// <summary> /// Request avatar's classified ads. /// </summary> /// <returns> /// An array containing all the calassified uuid and it's name created by the creator id /// </returns> /// <param name='json'> /// Our parameters are in the OSDMap json["params"] /// </param> /// <param name='response'> /// If set to <c>true</c> response. /// </param> public bool AvatarClassifiedsRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat ("Classified Request"); return false; } OSDMap request = (OSDMap)json["params"]; UUID creatorId = new UUID(request["creatorId"].AsString()); OSDArray data = (OSDArray) Service.AvatarClassifiedsRequest(creatorId); response.Result = data; return true; } public bool ClassifiedUpdate(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "Error parsing classified update request"; m_log.DebugFormat ("Classified Update Request"); return false; } string result = string.Empty; UserClassifiedAdd ad = new UserClassifiedAdd(); object Ad = (object)ad; OSD.DeserializeMembers(ref Ad, (OSDMap)json["params"]); if(Service.ClassifiedUpdate(ad, ref result)) { response.Result = OSD.SerializeMembers(ad); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } public bool ClassifiedDelete(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat ("Classified Delete Request"); return false; } OSDMap request = (OSDMap)json["params"]; UUID classifiedId = new UUID(request["classifiedId"].AsString()); if (Service.ClassifiedDelete(classifiedId)) return true; response.Error.Code = ErrorCode.InternalError; response.Error.Message = "data error removing record"; return false; } public bool ClassifiedInfoRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("Classified Info Request"); return false; } string result = string.Empty; UserClassifiedAdd ad = new UserClassifiedAdd(); object Ad = (object)ad; OSD.DeserializeMembers(ref Ad, (OSDMap)json["params"]); if(Service.ClassifiedInfoRequest(ref ad, ref result)) { response.Result = OSD.SerializeMembers(ad); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } #endregion Classifieds #region Picks public bool AvatarPicksRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat ("Avatar Picks Request"); return false; } OSDMap request = (OSDMap)json["params"]; UUID creatorId = new UUID(request["creatorId"].AsString()); OSDArray data = (OSDArray) Service.AvatarPicksRequest(creatorId); response.Result = data; return true; } public bool PickInfoRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("Avatar Picks Info Request"); return false; } string result = string.Empty; UserProfilePick pick = new UserProfilePick(); object Pick = (object)pick; OSD.DeserializeMembers(ref Pick, (OSDMap)json["params"]); if(Service.PickInfoRequest(ref pick, ref result)) { response.Result = OSD.SerializeMembers(pick); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } public bool PicksUpdate(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("Avatar Picks Update Request"); return false; } string result = string.Empty; UserProfilePick pick = new UserProfilePick(); object Pick = (object)pick; OSD.DeserializeMembers(ref Pick, (OSDMap)json["params"]); if(Service.PicksUpdate(ref pick, ref result)) { response.Result = OSD.SerializeMembers(pick); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = "unable to update pick"; return false; } public bool PicksDelete(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat ("Avatar Picks Delete Request"); return false; } OSDMap request = (OSDMap)json["params"]; UUID pickId = new UUID(request["pickId"].AsString()); if(Service.PicksDelete(pickId)) return true; response.Error.Code = ErrorCode.InternalError; response.Error.Message = "data error removing record"; return false; } #endregion Picks #region Notes public bool AvatarNotesRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "Params missing"; m_log.DebugFormat ("Avatar Notes Request"); return false; } UserProfileNotes note = new UserProfileNotes(); object Note = (object)note; OSD.DeserializeMembers(ref Note, (OSDMap)json["params"]); if(Service.AvatarNotesRequest(ref note)) { response.Result = OSD.SerializeMembers(note); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = "Error reading notes"; return false; } public bool NotesUpdate(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "No parameters"; m_log.DebugFormat ("Avatar Notes Update Request"); return false; } string result = string.Empty; UserProfileNotes note = new UserProfileNotes(); object Notes = (object) note; OSD.DeserializeMembers(ref Notes, (OSDMap)json["params"]); if(Service.NotesUpdate(ref note, ref result)) { response.Result = OSD.SerializeMembers(note); return true; } return true; } #endregion Notes #region Profile Properties public bool AvatarPropertiesRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("Avatar Properties Request"); return false; } string result = string.Empty; UserProfileProperties props = new UserProfileProperties(); object Props = (object)props; OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); if(Service.AvatarPropertiesRequest(ref props, ref result)) { response.Result = OSD.SerializeMembers(props); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } public bool AvatarPropertiesUpdate(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("Avatar Properties Update Request"); return false; } string result = string.Empty; UserProfileProperties props = new UserProfileProperties(); object Props = (object)props; OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); if(Service.AvatarPropertiesUpdate(ref props, ref result)) { response.Result = OSD.SerializeMembers(props); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } #endregion Profile Properties #region Interests public bool AvatarInterestsUpdate(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("Avatar Interests Update Request"); return false; } string result = string.Empty; UserProfileProperties props = new UserProfileProperties(); object Props = (object)props; OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); if(Service.AvatarInterestsUpdate(props, ref result)) { response.Result = OSD.SerializeMembers(props); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } #endregion Interests #region User Preferences public bool UserPreferencesRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat ("User Preferences Request"); return false; } string result = string.Empty; UserPreferences prefs = new UserPreferences(); object Prefs = (object)prefs; OSD.DeserializeMembers(ref Prefs, (OSDMap)json["params"]); if(Service.UserPreferencesRequest(ref prefs, ref result)) { response.Result = OSD.SerializeMembers(prefs); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); // m_log.InfoFormat("[PROFILES]: User preferences request error - {0}", response.Error.Message); return false; } public bool UserPreferenecesUpdate(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("User Preferences Update Request"); return false; } string result = string.Empty; UserPreferences prefs = new UserPreferences(); object Prefs = (object)prefs; OSD.DeserializeMembers(ref Prefs, (OSDMap)json["params"]); if(Service.UserPreferencesUpdate(ref prefs, ref result)) { response.Result = OSD.SerializeMembers(prefs); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); m_log.InfoFormat("[PROFILES]: User preferences update error - {0}", response.Error.Message); return false; } #endregion User Preferences #region Utility public bool AvatarImageAssetsRequest(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; m_log.DebugFormat ("Avatar Image Assets Request"); return false; } OSDMap request = (OSDMap)json["params"]; UUID avatarId = new UUID(request["avatarId"].AsString()); OSDArray data = (OSDArray) Service.AvatarImageAssetsRequest(avatarId); response.Result = data; return true; } #endregion Utiltiy #region UserData public bool RequestUserAppData(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("User Application Service URL Request: No Parameters!"); return false; } string result = string.Empty; UserAppData props = new UserAppData(); object Props = (object)props; OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); if(Service.RequestUserAppData(ref props, ref result)) { OSDMap res = new OSDMap(); res["result"] = OSD.FromString("success"); res["token"] = OSD.FromString (result); response.Result = res; return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } public bool UpdateUserAppData(OSDMap json, ref JsonRpcResponse response) { if(!json.ContainsKey("params")) { response.Error.Code = ErrorCode.ParseError; response.Error.Message = "no parameters supplied"; m_log.DebugFormat ("User App Data Update Request"); return false; } string result = string.Empty; UserAppData props = new UserAppData(); object Props = (object)props; OSD.DeserializeMembers(ref Props, (OSDMap)json["params"]); if(Service.SetUserAppData(props, ref result)) { response.Result = OSD.SerializeMembers(props); return true; } response.Error.Code = ErrorCode.InternalError; response.Error.Message = string.Format("{0}", result); return false; } #endregion UserData } }
37.951362
107
0.553186
[ "BSD-3-Clause" ]
BlueWall/opensim
OpenSim/Server/Handlers/Profiles/UserProfilesHandlers.cs
19,507
C#
/* * This software is derived from samples provided by Amazon Web Services. * The original copyright notice for this sample code follows. ************************************************************************** * This software code is made available "AS IS" without warranties of any * kind. You may copy, display, modify and redistribute the software * code either by itself or as incorporated into your code; provided that * you do not remove any proprietary notices. Your use of this software * code is at your own risk and you waive any claim against Amazon * Web Services LLC or its affiliates with respect to your use of * this software code. * * @copyright 2007 Amazon Web Services LLC or its affiliates. * All rights reserved. * ************************************************************************* * Extensions to this code base are Copyright (c) 2007 by M. David Peterson * The code contained in this file is licensed under a Creative Commons (Attribution 3.0) license * Please see http://creativecommons.org/licenses/by/3.0/us/ for specific detail. */ using System.IO; using System.Collections; using Nuxleus.Extension.Aws; using Nuxleus.Extension.Aws.Sdb; class BasicSample { static void handleException (SdbException ex) { System.Console.WriteLine("Failure: {0}: {1} ({2})", ex.ErrorCode, ex.Message, ex.RequestId); } static void printAttributes (Item item) { System.Console.WriteLine(); System.Console.WriteLine("Attributes for '{0}':", item.Name); try { GetAttributesResponse getAttributesResponse = item.GetAttributes(); foreach (Attribute attribute in getAttributesResponse.Attributes()) { System.Console.WriteLine("{0} => {1}.", attribute.Name, attribute.Value); } } catch (SdbException ex) { handleException(ex); } } public static void Main (string[] args) { string awsAccessKey = System.Environment.GetEnvironmentVariable("SDB_ACCESS_KEY"); string awsSecretKey = System.Environment.GetEnvironmentVariable("SDB_SECRET_KEY"); string sample_domain = "sample_domain_1"; string sample_item = "sample_item"; // Create a new instance of the SDB class HttpQueryConnection connection = new HttpQueryConnection(awsAccessKey, awsSecretKey, "http://sdb.amazonaws.com"); Sdb sdb = new Sdb(connection); // Step 1: // Create the domain System.Console.WriteLine(); System.Console.WriteLine("Step 1: Creating the domain."); try { sdb.CreateDomain(sample_domain); } catch (SdbException ex) { handleException(ex); } // Get the sample domain Domain domain = sdb.GetDomain(sample_domain); // Get the sample item Item item = domain.GetItem(sample_item); // Step 2: // Create a series of attributes to associate with the sample eid. ArrayList attributes = new ArrayList(); attributes.Add(new Attribute("name", "value")); attributes.Add(new Attribute("name", "2nd_value")); attributes.Add(new Attribute("name", "3rd_value")); attributes.Add(new Attribute("2nd_name", "4th_value")); attributes.Add(new Attribute("2nd_name", "5th_value")); System.Console.WriteLine(); System.Console.WriteLine("Step 2: Creating initial attributes."); try { item.PutAttributes(attributes); } catch (SdbException ex) { handleException(ex); } // Print out the attributes for the item. printAttributes(item); // Step 3: // Delete the { "name", "3rd_value" } attribute. System.Console.WriteLine(); System.Console.WriteLine("Step 3: Deleting the { \"name\", " + "\"3rd_value\" } attribute."); attributes.Clear(); attributes.Add(new Attribute("name", "3rd_value")); try { item.DeleteAttributes(attributes); } catch (SdbException ex) { handleException(ex); } // Print out the attributes for $item. printAttributes(item); // Step 4: // Delete all attributes with name "2nd_name". System.Console.WriteLine(); System.Console.WriteLine("Step 4: Delete attributes with name " + "\"2nd_name\"."); attributes.Clear(); attributes.Add(new Attribute("2nd_name")); try { item.DeleteAttributes(attributes); } catch (SdbException ex) { handleException(ex); } // Print out the attributes for $item. printAttributes(item); // Step 5: // Replace the value of the "name" attribute of the sample // eID with the value "new_value". System.Console.WriteLine(); System.Console.WriteLine("Step 5: Write value \"new_value\" " + "to the \"name\" attribute."); attributes.Clear(); attributes.Add(new Attribute("name", "new_value")); try { item.PutAttributes(attributes); } catch (SdbException ex) { handleException(ex); } // Print out the attributes for the item. printAttributes(item); // Step 6: // Find all of the eIDs which contain the attribute "name" // with the value "new_value". System.Console.WriteLine(); System.Console.WriteLine("Step 6: Find all eID which contain" + "the attribute { \"name\", " + "\"new_value\" }."); try { QueryResponse queryResponse = domain.Query("[\"name\" = \"new_value\"]"); // Print them out. System.Console.WriteLine(); System.Console.WriteLine("Found items:"); foreach (Item curitem in queryResponse.Items()) { System.Console.WriteLine(curitem.Name); } } catch (SdbException ex) { handleException(ex); } // Step 7: // Delete the sample eID. System.Console.WriteLine(); System.Console.WriteLine("Step 7: Delete the sample item."); try { item.DeleteAttributes(); } catch (SdbException ex) { handleException(ex); } // Print out the attributes for $item. printAttributes(item); // Step 8: // Delete the domain System.Console.WriteLine(); System.Console.WriteLine("Step 8: Deleting the domain."); try { sdb.DeleteDomain(sample_domain); } catch (SdbException ex) { handleException(ex); } System.Console.WriteLine(); } }
31.547009
122
0.541181
[ "BSD-3-Clause" ]
3rdandUrban-dev/Nuxleus
linux-distro/package/Apps/Samples/AwsSdb_Test/Program.cs
7,382
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace SharpKit.Qooxdoo.Generator { public static class Settings { public static bool CapitalizeNames { get; set; } } }
17.769231
56
0.714286
[ "MIT" ]
SharpKit/SharpKit-SDK
DefGenerators/Qooxdoo.Generator/Settings.cs
233
C#
using ASBDDS.Shared.Models.Database.DataDb; using System; using System.Collections.Generic; using System.Text; namespace ASBDDS.Shared.Models.Responses { public class DeviceLimitResponse { /// <summary> /// Device manufacturer /// </summary> public string Manufacturer { get; set; } /// <summary> /// Device model /// </summary> public string Model { get; set; } /// <summary> /// Number of devices /// </summary> public int Count { get; set; } public DeviceLimitResponse() { } public DeviceLimitResponse(ProjectDeviceLimit deviceLimit) { Model = deviceLimit.Model; Count = deviceLimit.Count; Manufacturer = deviceLimit.Manufacturer; } } public class ProjectAdminResponse { /// <summary> /// Project ID /// </summary> public Guid Id { get; set; } /// <summary> /// Project name /// </summary> public string Name { get; set; } /// <summary> /// Project default vlan /// </summary> public int DefaultVlan { get; set; } /// <summary> /// Allow custom bootloader /// </summary> public bool AllowCustomBootloaders { get; set; } /// <summary> /// List of devices limits /// </summary> public List<DeviceLimitResponse> DeviceLimits { get; set; } /// <summary> /// Is project disabled /// </summary> public bool Disabled { get; set; } public ProjectAdminResponse() { } public ProjectAdminResponse(Project project) { Id = project.Id; Name = project.Name; DefaultVlan = project.DefaultVlan; AllowCustomBootloaders = project.AllowCustomBootloaders; Disabled = project.Disabled; DeviceLimits = new List<DeviceLimitResponse>(); foreach (var deviceLimit in project.ProjectDeviceLimits) { DeviceLimits.Add(new DeviceLimitResponse(deviceLimit)); } } } }
27.475
71
0.540491
[ "MIT" ]
Insei/ASBDDS.NET
ASBDDS/ASBDDS.Shared/Models/Responses/ProjectAdminResponse.cs
2,200
C#
namespace Lexs4SearchRetrieveWebService { /// <remarks/> [System.CodeDom.Compiler.GeneratedCodeAttribute("WscfGen", "1.0.0.0")] [System.SerializableAttribute()] [System.Diagnostics.DebuggerStepThroughAttribute()] [System.ComponentModel.DesignerCategoryAttribute("code")] [System.Xml.Serialization.XmlTypeAttribute(Namespace="http://lexs.gov/digest/4.0")] public partial class TelephoneCallAssociationType : AssociationType { private EntityType1[] originatorEntityField; private ReferenceType2 originatorTelephoneNumberReferenceField; private EntityType1[] receiverEntityField; private ReferenceType2[] receiverTelephoneNumberReferenceField; private duration callDurationField; /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("OriginatorEntity", IsNullable=true, Order=0)] public EntityType1[] OriginatorEntity { get { return this.originatorEntityField; } set { this.originatorEntityField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(Order=1)] public ReferenceType2 OriginatorTelephoneNumberReference { get { return this.originatorTelephoneNumberReferenceField; } set { this.originatorTelephoneNumberReferenceField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("ReceiverEntity", IsNullable=true, Order=2)] public EntityType1[] ReceiverEntity { get { return this.receiverEntityField; } set { this.receiverEntityField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute("ReceiverTelephoneNumberReference", Order=3)] public ReferenceType2[] ReceiverTelephoneNumberReference { get { return this.receiverTelephoneNumberReferenceField; } set { this.receiverTelephoneNumberReferenceField = value; } } /// <remarks/> [System.Xml.Serialization.XmlElementAttribute(IsNullable=true, Order=4)] public duration CallDuration { get { return this.callDurationField; } set { this.callDurationField = value; } } } }
30.305263
101
0.532824
[ "Apache-2.0" ]
gtri-iead/LEXS-NET-Sample-Implementation-4.0
LEXS Search Retrieve Service Implementation/LexsSearchRetrieveCommon/TelephoneCallAssociationType.cs
2,879
C#
using System; using System.Collections; using System.Threading.Tasks; using UnityEngine; using UnityEngine.SceneManagement; namespace UIFrame { public class LoadSceneManager : SingletonBase<LoadSceneManager> { private AsyncOperation _operation; public float Progress { get { return _operation.progress; } } public async void AllowSwitchScene() { await Task.Delay(TimeSpan.FromSeconds(2)); _operation.allowSceneActivation = true; } public IEnumerator LoadSceneAsync(string name) { _operation = SceneManager.LoadSceneAsync(name); _operation.allowSceneActivation = false; yield return _operation; } } }
24
67
0.638021
[ "MIT" ]
1102736067/ECS
Assets/Scripts/Manager/LoadSceneManager.cs
768
C#
// <copyright file="ApplicationVisibilityHide.Generated.cs" company="Okta, Inc"> // Copyright (c) 2014 - present Okta, Inc. All rights reserved. // Licensed under the Apache 2.0 license. See the LICENSE file in the project root for full license information. // </copyright> // This file was automatically generated. Don't modify it directly. using System; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; using Okta.Sdk.Internal; namespace Okta.Sdk { /// <inheritdoc/> public sealed partial class ApplicationVisibilityHide : Resource, IApplicationVisibilityHide { /// <inheritdoc/> public bool? IOs { get => GetBooleanProperty("iOS"); set => this["iOS"] = value; } /// <inheritdoc/> public bool? Web { get => GetBooleanProperty("web"); set => this["web"] = value; } } }
27.428571
112
0.621875
[ "Apache-2.0" ]
Christian-Oleson/okta-sdk-dotnet
src/Okta.Sdk/Generated/ApplicationVisibilityHide.Generated.cs
960
C#
using System; using System.Xml.Serialization; using Newtonsoft.Json; namespace Essensoft.AspNetCore.Payment.Alipay.Domain { /// <summary> /// Injured Data Structure. /// </summary> [Serializable] public class Injured : AlipayObject { /// <summary> /// 姓名,须与证件上名称一致 /// </summary> [JsonProperty("cert_name")] [XmlElement("cert_name")] public string CertName { get; set; } /// <summary> /// 证件号码 /// </summary> [JsonProperty("cert_no")] [XmlElement("cert_no")] public string CertNo { get; set; } /// <summary> /// 证件类型, 枚举: IDENTITY_CARD:身份证 备注:目前仅支持身份证类型 /// </summary> [JsonProperty("cert_type")] [XmlElement("cert_type")] public string CertType { get; set; } /// <summary> /// 人伤类型,枚举如下: SCENE_SIMPLE:现场简易处理 CLINIC:门诊 IN_HOSPITAL:住院 MAIM:伤残 DEAD:死亡 /// </summary> [JsonProperty("damage_type")] [XmlElement("damage_type")] public string DamageType { get; set; } /// <summary> /// 伤者身份: PASSENGER:乘客 DRIVER:司机 THIRD:三者 /// </summary> [JsonProperty("injured_identity")] [XmlElement("injured_identity")] public string InjuredIdentity { get; set; } /// <summary> /// 医疗定损员 核赔阶段必传 /// </summary> [JsonProperty("medical_assessor")] [XmlElement("medical_assessor")] public Person MedicalAssessor { get; set; } /// <summary> /// 医疗查勘员信息 /// </summary> [JsonProperty("medical_surveyor")] [XmlElement("medical_surveyor")] public Person MedicalSurveyor { get; set; } /// <summary> /// 手机号 /// </summary> [JsonProperty("mobile_no")] [XmlElement("mobile_no")] public string MobileNo { get; set; } } }
27.428571
88
0.542708
[ "MIT" ]
AkonCoder/Payment
src/Essensoft.AspNetCore.Payment.Alipay/Domain/Injured.cs
2,114
C#
using Microsoft.Xna.Framework.Graphics; using StardewModdingAPI; using System.IO; using System.Text.RegularExpressions; namespace GreenhouseGatherers { public static class ModResources { private static IMonitor monitor; internal static Texture2D emptyStatue; internal static Texture2D filledStatue; public static void LoadMonitor(IMonitor iMonitor) { monitor = iMonitor; } public static IMonitor GetMonitor() { return monitor; } public static void LoadAssets(IModHelper helper, string primaryPath) { emptyStatue = helper.Content.Load<Texture2D>(Path.Combine(primaryPath, "Sprites", "empty.png")); filledStatue = helper.Content.Load<Texture2D>(Path.Combine(primaryPath, "Sprites", "filled.png")); } public static string SplitCamelCaseText(string input) { return string.Join(" ", Regex.Split(input, @"(?<!^)(?=[A-Z](?![A-Z]|$))")); } } }
28.722222
110
0.626692
[ "MIT" ]
Floogen/GreenhouseGatherers
GreenhouseGatherers/GreenhouseGatherers/GreenhouseGatherers/ModResources.cs
1,036
C#
using System; using Xamarin.Forms.CustomAttributes; using Xamarin.Forms.Internals; using Xamarin.Forms.Xaml; <<<<<<< HEAD namespace Xamarin.Forms.Controls.Issues ======= namespace Xamarin.Forms.Controls >>>>>>> Update from origin (#11) { #if APP [Preserve(AllMembers = true)] [Issue(IssueTracker.Bugzilla, 60787, "Frames with border radius preset have this radius reset when their background color is changed.", PlatformAffected.Android, issueTestNumber: 1)] public partial class Bugzilla60787 : ContentPage { bool _colourIndicator; public Bugzilla60787() { InitializeComponent(); this.btnChangeColour.Clicked += btnChangeColour_Click; } void btnChangeColour_Click(object sender, EventArgs e) { this.frmDoesChange.BackgroundColor = _colourIndicator ? Color.LightBlue : Color.LightGoldenrodYellow; _colourIndicator = !_colourIndicator; } } #endif <<<<<<< HEAD } ======= } >>>>>>> Update from origin (#11)
23.575
136
0.734889
[ "MIT" ]
jfversluis/Xamarin.Forms
Xamarin.Forms.Controls.Issues/Xamarin.Forms.Controls.Issues.Shared/Bugzilla60787.xaml.cs
945
C#
using System; using System.Collections.Generic; using Whathecode.System.Algorithm; namespace Whathecode.System { /// <summary> /// Interface specifying an interval from a value, to a value. Borders may be included or excluded. /// </summary> public interface IInterval<T> : IInterval<T, T> where T : IComparable<T> { /// <summary> /// Limit a given range to this range. /// When part of the given range lies outside of this range, it isn't included in the resulting range. /// </summary> /// <param name = "range">The range to limit to this range.</param> /// <returns>The given range, which excludes all parts lying outside of this range. Null when empty.</returns> IInterval<T> Clamp( IInterval<T> range ); /// <summary> /// Split the interval into two intervals at the given point, or nearest valid point. /// </summary> /// <param name = "atPoint">The point where to split.</param> /// <param name = "option">Option which specifies in which intervals the split point ends up.</param> /// <param name = "before">The interval in which to store the part before the point, if any, null otherwise.</param> /// <param name = "after">The interval in which to store the part after the point, if any, null otherwise.</param> void Split( T atPoint, SplitOption option, out IInterval<T> before, out IInterval<T> after ); /// <summary> /// Subtract a given interval from the current interval. /// </summary> /// <param name = "subtract">The interval to subtract from this interval.</param> /// <returns>The resulting intervals after subtraction.</returns> List<IInterval<T>> Subtract( IInterval<T> subtract ); /// <summary> /// Returns the intersection of this interval with another. /// </summary> /// <param name = "interval">The interval to get the intersection for.</param> /// <returns>The intersection of this interval with the given other. Null when no intersection.</returns> IInterval<T> Intersection( IInterval<T> interval ); /// <summary> /// Returns an expanded interval of the current interval up to the given value (and including). /// When the value lies within the interval the returned interval is the same. /// </summary> /// <param name = "value">The value up to which to expand the interval.</param> new IInterval<T> ExpandTo( T value ); /// <summary> /// Returns an expanded interval of the current interval up to the given value. /// When the value lies within the interval the returned interval is the same. /// </summary> /// <param name = "value">The value up to which to expand the interval.</param> /// <param name = "include">Include the value to which is expanded in the interval.</param> new IInterval<T> ExpandTo( T value, bool include ); /// <summary> /// Returns an interval offsetted from the current interval by a specified amount. /// </summary> /// <param name="amount">How much to move the interval.</param> new IInterval<T> Move( T amount ); /// <summary> /// Returns a scaled version of the current interval. /// </summary> /// <param name="scale"> /// Percentage to scale the interval up or down. /// Smaller than 1.0 to scale down, larger to scale up. /// </param> /// <param name="aroundPercentage">The percentage inside the interval around which to scale.</param> new IInterval<T> Scale( double scale, double aroundPercentage = 0.5 ); /// <summary> /// Returns a reversed version of the current interval, swapping the start position with the end position. /// </summary> new IInterval<T> Reverse(); } public interface IInterval<T, TSize> where T : IComparable<T> where TSize : IComparable<TSize> { /// <summary> /// The start of the interval. /// </summary> T Start { get; } /// <summary> /// The end of the interval. /// </summary> T End { get; } /// <summary> /// Is the value at the start of the interval included in the interval. /// </summary> bool IsStartIncluded { get; } /// <summary> /// Is the value at the end of the interval included in the interval. /// </summary> bool IsEndIncluded { get; } /// <summary> /// Determines whether the start of the interval lies before or after the end of the interval. true when after, false when before. /// </summary> bool IsReversed { get; } /// <summary> /// Get the value in the center of the interval. Rounded to the nearest correct value. /// </summary> T Center { get; } /// <summary> /// Get the size of the interval. /// </summary> TSize Size { get; } #region Get operations. /// <summary> /// Get the value at a given percentage within (0.0 - 1.0) or outside (&lt; 0.0, &gt; 1.0) of the interval. Rounding to nearest neighbour occurs when needed. /// TODO: Would it be cleaner not to use a double for percentage, but a generic Percentage type? /// </summary> /// <param name = "percentage">The percentage in the range of which to return the value.</param> /// <returns>The value at the given percentage within the interval.</returns> T GetValueAt( double percentage ); /// <summary> /// Get a percentage how far inside (0.0 - 1.0) or outside (&lt; 0.0, &gt; 1.0) the interval a certain value lies. /// For single intervals, '1.0' is returned when inside the interval, '-1.0' otherwise. /// </summary> /// <param name = "position">The position value to get the percentage for.</param> /// <returns>The percentage indicating how far inside (or outside) the interval the given value lies.</returns> double GetPercentageFor( T position ); /// <summary> /// Map a value from this range, to a value in another range linearly. /// </summary> /// <param name = "value">The value to map to another range.</param> /// <param name = "range">The range to which to map the value.</param> /// <returns>The value, mapped to the given range.</returns> T Map( T value, IInterval<T, TSize> range ); /// <summary> /// Map a value from this range, to a value in another range of another type linearly. /// </summary> /// <typeparam name = "TOther">The type of the other range.</typeparam> /// <typeparam name = "TOtherSize">The type used to specify distances in between two values of <typeparamref name="TOther" />.</typeparam> /// <param name = "value">The value to map to another range.</param> /// <param name = "range">The range to which to map the value.</param> /// <returns>The value, mapped to the given range.</returns> TOther Map<TOther, TOtherSize>( T value, IInterval<TOther, TOtherSize> range ) where TOther : IComparable<TOther> where TOtherSize : IComparable<TOtherSize>; /// <summary> /// Does the given value lie in the interval or not. /// </summary> /// <param name = "value">The value to check for.</param> /// <returns>True when the value lies within the interval, false otherwise.</returns> bool LiesInInterval( T value ); /// <summary> /// Does the given interval intersect the other interval. /// </summary> /// <param name = "interval">The interval to check for intersection.</param> /// <returns>True when the intervals intersect, false otherwise.</returns> bool Intersects( IInterval<T, TSize> interval ); /// <summary> /// Limit a given value to this range. When the value is smaller/bigger than the range, snap it to the range border. /// TODO: For now this does not take into account whether the start or end of the range is included. Is this possible? /// </summary> /// <param name = "value">The value to limit.</param> /// <returns>The value limited to the range.</returns> T Clamp( T value ); /// <summary> /// Limit a given range to this range. /// When part of the given range lies outside of this range, it isn't included in the resulting range. /// </summary> /// <param name = "range">The range to limit to this range.</param> /// <returns>The given range, which excludes all parts lying outside of this range. Null when empty.</returns> IInterval<T, TSize> Clamp( IInterval<T, TSize> range ); /// <summary> /// Split the interval into two intervals at the given point, or nearest valid point. /// </summary> /// <param name = "atPoint">The point where to split.</param> /// <param name = "option">Option which specifies in which intervals the split point ends up.</param> /// <param name = "before">The interval in which to store the part before the point, if any, null otherwise.</param> /// <param name = "after">The interval in which to store the part after the point, if any, null otherwise.</param> void Split( T atPoint, SplitOption option, out IInterval<T, TSize> before, out IInterval<T, TSize> after ); /// <summary> /// Subtract a given interval from the current interval. /// </summary> /// <param name = "subtract">The interval to subtract from this interval.</param> /// <returns>The resulting intervals after subtraction.</returns> List<IInterval<T, TSize>> Subtract( IInterval<T, TSize> subtract ); /// <summary> /// Returns the intersection of this interval with another. /// </summary> /// <param name = "interval">The interval to get the intersection for.</param> /// <returns>The intersection of this interval with the given other. Null when no intersection.</returns> IInterval<T, TSize> Intersection( IInterval<T, TSize> interval ); #endregion // Get operations. #region Enumeration /// <summary> /// Get values for each step within the interval. /// </summary> /// <param name="step">The step size between each value.</param> IEnumerable<T> GetValues( TSize step ); /// <summary> /// Get values for each step within the interval, anchored to multiples of a specified anchor value. /// </summary> /// <param name="step">The step size between each value.</param> /// <param name="anchor">The value to which multiples of step are anchored.</param> IEnumerable<T> GetValues( TSize step, T anchor ); /// <summary> /// Execute an action each step in an interval. /// </summary> /// <param name = "step">The size of the steps.</param> /// <param name = "stepAction">The operation to execute.</param> void EveryStepOf( TSize step, Action<T> stepAction ); #endregion // Enumeration #region Modifiers /// <summary> /// Returns an expanded interval of the current interval up to the given value (and including). /// When the value lies within the interval the returned interval is the same. /// </summary> /// <param name = "value">The value up to which to expand the interval.</param> IInterval<T, TSize> ExpandTo( T value ); /// <summary> /// Returns an expanded interval of the current interval up to the given value. /// When the value lies within the interval the returned interval is the same. /// </summary> /// <param name = "value">The value up to which to expand the interval.</param> /// <param name = "include">Include the value to which is expanded in the interval.</param> IInterval<T, TSize> ExpandTo( T value, bool include ); /// <summary> /// Returns an interval offsetted from the current interval by a specified amount. /// </summary> /// <param name="amount">How much to move the interval.</param> IInterval<T, TSize> Move( TSize amount ); /// <summary> /// Returns a scaled version of the current interval. /// </summary> /// <param name="scale"> /// Percentage to scale the interval up or down. /// Smaller than 1.0 to scale down, larger to scale up. /// </param> /// <param name="aroundPercentage">The percentage inside the interval around which to scale.</param> IInterval<T, TSize> Scale( double scale, double aroundPercentage = 0.5 ); /// <summary> /// Returns a scaled version of the current interval, but prevents the interval from exceeding the values specified in a passed limit. /// This is useful to prevent <see cref="ArgumentOutOfRangeException" /> during calculations for certain types. /// </summary> /// <param name="scale"> /// Percentage to scale the interval up or down. /// Smaller than 1.0 to scale down, larger to scale up. /// </param> /// <param name="limit">The limit which the interval snaps to when scaling exceeds it.</param> /// <param name="aroundPercentage">The percentage inside the interval around which to scale.</param> IInterval<T, TSize> Scale( double scale, IInterval<T, TSize> limit, double aroundPercentage = 0.5 ); /// <summary> /// Returns a reversed version of the current interval, swapping the start position with the end position. /// </summary> IInterval<T, TSize> Reverse(); #endregion // Modifiers object Clone(); } }
42.592593
159
0.680949
[ "MIT" ]
Whathecode/.NET-Standard-Library-Extension
src/Whathecode.System/IInterval.cs
12,652
C#
using System; using System.Collections.Generic; using System.Linq; using System.Threading.Tasks; namespace CourseLibrary.API.Models { public class AuthorFullDto { public Guid Id { get; set; } public string FirstName { get; set; } public string LastName { get; set; } public DateTimeOffset DateOfBirth { get; set; } public string MainCategory { get; set; } } }
24.352941
55
0.65942
[ "MIT" ]
Battler45/ImplementingAdvancedRESTfulConcernsAspNetCore3
Finished sample/CourseLibrary/CourseLibrary.API/Models/AuthorFullDto.cs
416
C#
using System.Collections.Generic; using Entities; using Android.App; using Android.Views; using Android.Widget; using Square.Picasso; namespace CustomAdapter { public class GamesAdapter : BaseAdapter<Game> { List<Game> GamesList; Activity Context; int ItemLayoutTemplate; int GameTitle; int GamePlatform; int GamePreview; public GamesAdapter(Activity context, List<Game> list, int itemLayoutTemplate, int gametitle, int gameplatform, int imgpreview) { this.Context = context; this.GamesList = list; this.ItemLayoutTemplate = itemLayoutTemplate; this.GameTitle = gametitle; this.GamePlatform = gameplatform; this.GamePreview= imgpreview; } public override Game this[int position] { get { return GamesList[position]; } } public override int Count { get { return GamesList.Count; } } public override long GetItemId(int position) { return GamesList[position].id; } public override View GetView(int position, View convertView, ViewGroup parent) { var Item = GamesList[position]; View ItemView; if (convertView == null) { ItemView = Context.LayoutInflater.Inflate(ItemLayoutTemplate, null); } else { ItemView = convertView; } ItemView.FindViewById<TextView>(GameTitle).Text = Item.name; ItemView.FindViewById<TextView>(GamePlatform).Text = Item.id.ToString(); if (Item.cover != null) { Picasso.With(Context).Load(string.Format("https://images.igdb.com/igdb/image/upload/t_thumb/{0}.jpg", Item.cover.cloudinary_id)).Into(ItemView.FindViewById<ImageView>(GamePreview)); } else { Picasso.With(Context).Load("https://lh3.googleusercontent.com/XO8m2QiuEU3hHIHcWlS29XxUhnMXj3fU_hU8WbR100-57ypK5A_6RNIXPOdYu-EyNVRS").Into(ItemView.FindViewById<ImageView>(GamePreview)); } return ItemView; } } }
29.833333
201
0.571981
[ "Apache-2.0" ]
graco911/IGDB-API-demo
CustomAdapter/GamesAdapter.cs
2,329
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Migrate { /// <summary> /// Migrate Project REST Resource. /// API Version: 2018-09-01-preview. /// </summary> [AzureNextGenResourceType("azure-nextgen:migrate:MigrateProject")] public partial class MigrateProject : Pulumi.CustomResource { /// <summary> /// Gets or sets the eTag for concurrency control. /// </summary> [Output("eTag")] public Output<string?> ETag { get; private set; } = null!; /// <summary> /// Gets or sets the Azure location in which migrate project is created. /// </summary> [Output("location")] public Output<string?> Location { get; private set; } = null!; /// <summary> /// Gets the name of the migrate project. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// Gets or sets the nested properties. /// </summary> [Output("properties")] public Output<Outputs.MigrateProjectPropertiesResponse> Properties { get; private set; } = null!; /// <summary> /// Gets or sets the tags. /// </summary> [Output("tags")] public Output<Outputs.MigrateProjectResponseTags?> Tags { get; private set; } = null!; /// <summary> /// Handled by resource provider. Type = Microsoft.Migrate/MigrateProject. /// </summary> [Output("type")] public Output<string> Type { get; private set; } = null!; /// <summary> /// Create a MigrateProject resource with the given unique name, arguments, and options. /// </summary> /// /// <param name="name">The unique name of the resource</param> /// <param name="args">The arguments used to populate this resource's properties</param> /// <param name="options">A bag of options that control this resource's behavior</param> public MigrateProject(string name, MigrateProjectArgs args, CustomResourceOptions? options = null) : base("azure-nextgen:migrate:MigrateProject", name, args ?? new MigrateProjectArgs(), MakeResourceOptions(options, "")) { } private MigrateProject(string name, Input<string> id, CustomResourceOptions? options = null) : base("azure-nextgen:migrate:MigrateProject", name, null, MakeResourceOptions(options, id)) { } private static CustomResourceOptions MakeResourceOptions(CustomResourceOptions? options, Input<string>? id) { var defaultOptions = new CustomResourceOptions { Version = Utilities.Version, Aliases = { new Pulumi.Alias { Type = "azure-nextgen:migrate/v20180901preview:MigrateProject"}, }, }; var merged = CustomResourceOptions.Merge(defaultOptions, options); // Override the ID if one was specified for consistency with other language SDKs. merged.Id = id ?? merged.Id; return merged; } /// <summary> /// Get an existing MigrateProject resource's state with the given name, ID, and optional extra /// properties used to qualify the lookup. /// </summary> /// /// <param name="name">The unique name of the resulting resource.</param> /// <param name="id">The unique provider ID of the resource to lookup.</param> /// <param name="options">A bag of options that control this resource's behavior</param> public static MigrateProject Get(string name, Input<string> id, CustomResourceOptions? options = null) { return new MigrateProject(name, id, options); } } public sealed class MigrateProjectArgs : Pulumi.ResourceArgs { /// <summary> /// Gets or sets the eTag for concurrency control. /// </summary> [Input("eTag")] public Input<string>? ETag { get; set; } /// <summary> /// Gets or sets the Azure location in which migrate project is created. /// </summary> [Input("location")] public Input<string>? Location { get; set; } /// <summary> /// Name of the Azure Migrate project. /// </summary> [Input("migrateProjectName")] public Input<string>? MigrateProjectName { get; set; } /// <summary> /// Gets or sets the nested properties. /// </summary> [Input("properties")] public Input<Inputs.MigrateProjectPropertiesArgs>? Properties { get; set; } /// <summary> /// Name of the Azure Resource Group that migrate project is part of. /// </summary> [Input("resourceGroupName", required: true)] public Input<string> ResourceGroupName { get; set; } = null!; /// <summary> /// Gets or sets the tags. /// </summary> [Input("tags")] public Input<Inputs.MigrateProjectTagsArgs>? Tags { get; set; } public MigrateProjectArgs() { } } }
37.696552
132
0.593304
[ "Apache-2.0" ]
pulumi/pulumi-azure-nextgen
sdk/dotnet/Migrate/MigrateProject.cs
5,466
C#
using System; using System.ComponentModel; using System.Reflection; using System.Collections.Generic; using System.Collections; using System.Data; using System.Globalization; using System.Resources; //using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows.Forms; using System.Net.Sockets; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows.Input; using System.Net.NetworkInformation; using Threads = System.Threading; using System.Net; using System.IO; using UniaCore.Peripherals; using NAudio; using NAudio.Wave; using NAudio.Dsp; using NAudio.Wave.SampleProviders; using NAudio.CoreAudioApi; using static UniaCore.Helper; using UniaCore.Components; using GrayLib; using Microsoft.Xna.Framework; using Microsoft.Xna.Framework.Graphics; using Microsoft.Xna.Framework.Input; using Microsoft.Xna.Framework.Audio; using Microsoft.Xna.Framework.Design; using Microsoft.Xna.Framework.Content; using Microsoft.Xna.Framework.Content.Pipeline; using Microsoft.Xna.Framework.Content.Pipeline.Processors; using Microsoft.Xna.Framework.Content.Pipeline.Builder; using Microsoft.Xna.Framework.Content.Pipeline.Graphics; using Microsoft.Xna.Framework.Content.Pipeline.Serialization; using TwoMGFX; namespace UniaCore { public class SpectrumViewer : Viewer { public Spectrum spectrum; Dictionary<string, string> ShaderLib = new Dictionary<string, string>(); Effect e, ray; class MyLogger : ContentBuildLogger { public override void LogMessage(string message, params object[] messageArgs) { } public override void LogImportantMessage(string message, params object[] messageArgs) { } public override void LogWarning(string helpLink, ContentIdentity contentIdentity, string message, params object[] messageArgs) { } } class MyProcessorContext : ContentProcessorContext { public override string BuildConfiguration => string.Empty; public override string IntermediateDirectory => string.Empty; public override string OutputDirectory => string.Empty; public override string OutputFilename => string.Empty; public override OpaqueDataDictionary Parameters => parameters; OpaqueDataDictionary parameters = new OpaqueDataDictionary(); public override ContentBuildLogger Logger => logger; ContentBuildLogger logger = new MyLogger(); public override ContentIdentity SourceIdentity => new ContentIdentity { SourceFilename = "myshader.fx" }; public override TargetPlatform TargetPlatform => TargetPlatform.Windows; public override GraphicsProfile TargetProfile => GraphicsProfile.Reach; public override void AddDependency(string filename) { throw new System.NotImplementedException(); } public override void AddOutputFile(string filename) { throw new System.NotImplementedException(); } public override TOutput BuildAndLoadAsset<TInput, TOutput>(ExternalReference<TInput> sourceAsset, string processorName, OpaqueDataDictionary processorParameters, string importerName) { throw new System.NotImplementedException(); } public override ExternalReference<TOutput> BuildAsset<TInput, TOutput>(ExternalReference<TInput> sourceAsset, string processorName, OpaqueDataDictionary processorParameters, string importerName, string assetName) { throw new System.NotImplementedException(); } public override TOutput Convert<TInput, TOutput>(TInput input, string processorName, OpaqueDataDictionary processorParameters) { throw new System.NotImplementedException(); } } public Effect ProcessEffect(string path) { var ep = new EffectProcessor(); EffectContent ec = new EffectContent(); //var f = File.Create("Resources/bxaa.fx"); ec.Identity = new ContentIdentity() { SourceFilename = path }; var pc = new MyProcessorContext(); try { var c = ep.Process(ec, pc); var e = new Effect(GraphicsDevice, c.GetEffectCode()); e.Name = "primary_shader"; return e; } catch (Exception e) { string err; //if ((err = e.Message.Replace("\\\\", "\\")).Contains(collMaker.effectpath)) { //collMaker.richTextBox2.AppendText(err); //var lc = Regex.Matches(err, @"(?<=\()\d+|\d+(?=\))"); //var l = int.Parse(lc[0].Value); //var c = int.Parse(lc[1].Value); //int start = collMaker.richTextBox1.GetFirstCharIndexFromLine(l); //int firstcharindex = collMaker.richTextBox1.GetFirstCharIndexFromLine(l - 1); //int currentline = collMaker.richTextBox1.GetLineFromCharIndex(firstcharindex); //string currentlinetext = collMaker.richTextBox1.Lines[currentline]; //collMaker.richTextBox1.Select(firstcharindex, currentlinetext.Length); ////collMaker.richTextBox1.Select( = collMaker.richTextBox1.Lines[int.Parse(l)-1]; //collMaker.richTextBox1.SelectionColor = System.Drawing.Color.DarkRed; //collMaker.richTextBox1.Select(0, 0); } //else // collMaker.richTextBox2.AppendText(e.Message); //collMaker.errfound = true; //int length = collMaker.richTextBox1.Lines[c].Length; //collMaker.richTextBox1.Select(start, length); //collMaker.richTextBox1.Sele //collMaker.richTextBox1. } return null; } public Color EmitColor; public float Peak; protected override void Initialize() { base.Initialize(); Simplex.Init(GraphicsDevice); rt = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height); rays = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height); buf1 = new RenderTarget2D(GraphicsDevice, GraphicsDevice.Viewport.Width, GraphicsDevice.Viewport.Height); var assembly = Assembly.GetExecutingAssembly(); var rsc = Properties.Resources.ResourceManager.GetResourceSet(CultureInfo.CurrentUICulture, true, true); foreach (DictionaryEntry n in rsc) { if (n.Value.GetType() == typeof(byte[])) using (StreamReader reader = new StreamReader(new MemoryStream((byte[])n.Value))) { ShaderLib.Add($"{n.Key.ToString()}", "Resources/" + n.Key.ToString() + ".fx"); } } e = ProcessEffect(ShaderLib["bxaa"]); ray = ProcessEffect(ShaderLib["rays"]); } protected override void Update(GameTime gameTime) { base.Update(gameTime); } RenderTarget2D rt, rays, buf1; protected override void Draw(GameTime gameTime) { if (DesignMode) return; base.Draw(gameTime); GraphicsDevice.Clear(BackColor.ToXNA()); spectrum.DrawSpectrum(spriteBatch, rt, rays, buf1, e, ray); } } }
39.166667
224
0.632882
[ "MIT" ]
Rideu/unia
Unia/Components/SpectrumViewer.cs
7,757
C#
namespace Crm.Infrastructure.Database { internal sealed class SchemaNames { internal const string Web = "Web"; } }
19.285714
42
0.659259
[ "MIT" ]
massimomannoni/CRM_BE
Ag_Crm_BE/Crm.Infrastructure/Database/SchemaNames.cs
137
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information namespace Dnn.PersonaBar.SiteSettings.Services.Dto { using Newtonsoft.Json; [JsonObject] public class LanguageTabDto { public int PageId { get; set; } public string PageName { get; set; } public string ViewUrl { get; set; } } }
28.352941
72
0.678423
[ "MIT" ]
Acidburn0zzz/Dnn.Platform
Dnn.AdminExperience/Dnn.PersonaBar.Extensions/Services/DTO/SiteSettings/LanguageTabDto.cs
484
C#
using System; using System.IO; using System.Linq; using System.Reflection; using Cake.Core; using Cake.Core.IO; using Cake.NSwag.Settings; using NJsonSchema; using NSwag.SwaggerGeneration; using NSwag.SwaggerGeneration.WebApi; namespace Cake.NSwag.Sources { /// <summary> /// Represents a .NET assembly (conventional or Web API) to gather API metadata from. /// </summary> public class AssemblySource : GenerationSource { internal AssemblySource(FilePath assemblyPath, ICakeEnvironment environment, IFileSystem fileSystem, bool useWebApi) : base(assemblyPath, environment, fileSystem) { Mode = useWebApi ? AssemblyMode.WebApi : AssemblyMode.Normal; } private AssemblyMode Mode { get; } /// <summary> /// Generates a Swagger (Open API) specification at the given path using the specified settings /// </summary> /// <param name="outputFile">File path for the generated API specification</param> /// <param name="settings">Settings to further control the spec generation process</param> /// <returns>The metadata source</returns> /// <example> /// <code><![CDATA[NSwag.FromAssembly("./assembly.dll").ToSwaggerSpecification("./swagger.json");]]></code> /// <code><![CDATA[NSwag.FromWebApiAssembly("./apicontroller.dll").ToSwaggerSpecification("./swagger.json");]]></code> /// </example> public AssemblySource ToSwaggerSpecification(FilePath outputFile, SwaggerGeneratorSettings settings) { settings = settings ?? new SwaggerGeneratorSettings(); if (Mode == AssemblyMode.Normal) { GenerateTypeSwagger(outputFile, settings); } else { GenerateWebApiSwagger(outputFile, settings); } return this; } /// <summary> /// Generates a Swagger (Open API) specification at the given path using the specified settings /// </summary> /// <param name="outputFile">File path for the generated API specification</param> /// <param name="configure">Optional settings to further control the specification</param> /// <returns>The metadata source</returns> /// <example> /// <code><![CDATA[NSwag.FromWebApiAssembly("./apicontroller.dll").ToSwaggerSpecification("./api.json");]]></code> /// </example> public AssemblySource ToSwaggerSpecification(FilePath outputFile, Action<SwaggerGeneratorSettings> configure = null) { var settings = new SwaggerGeneratorSettings(); configure?.Invoke(settings); ToSwaggerSpecification(outputFile, settings); return this; } private void GenerateTypeSwagger(FilePath outputFile, SwaggerGeneratorSettings settings) { var genSettings = settings.JsonSettings as AssemblyTypeToSwaggerGeneratorSettings ?? SettingsFactory.GetAssemblyToSwaggerSettings(); genSettings.AssemblyPath = Source.MakeAbsolute(Environment).FullPath; genSettings.DefaultEnumHandling = settings.EnumAsString ? EnumHandling.String : EnumHandling.Integer; genSettings.DefaultPropertyNameHandling = settings.CamelCaseProperties ? PropertyNameHandling.CamelCase : PropertyNameHandling.Default; genSettings.ReferencePaths = settings.AssemblyPaths.Select(a => a.FullPath).ToArray(); var gen = new AssemblyTypeToSwaggerGenerator(genSettings); var service = gen.GenerateAsync(gen.GetExportedClassNames()); using (var stream = new StreamWriter(FileSystem.GetFile(outputFile).OpenWrite())) { stream.WriteAsync(service.Result.ToJson()); } } private void GenerateWebApiSwagger(FilePath outputFile, SwaggerGeneratorSettings settings) { var genSettings = settings.JsonSettings as WebApiAssemblyToSwaggerGeneratorSettings ?? SettingsFactory.GetWebApiToSwaggerSettings(); genSettings.AssemblyPaths = new [] {Source.MakeAbsolute(Environment).FullPath }; genSettings.DefaultUrlTemplate = settings.DefaultUrlTemplate; genSettings.DefaultEnumHandling = settings.EnumAsString ? EnumHandling.String : EnumHandling.Integer; genSettings.DefaultPropertyNameHandling = settings.CamelCaseProperties ? PropertyNameHandling.CamelCase : PropertyNameHandling.Default; genSettings.NullHandling = NullHandling.Swagger; genSettings.ReferencePaths = settings.AssemblyPaths.Select(a => a.FullPath).ToArray(); var gen = new WebApiAssemblyToSwaggerGenerator(genSettings); var service = gen.GenerateForControllersAsync(gen.GetControllerClasses()).Result; service.BasePath = settings.BasePath ?? ""; service.Info.Title = settings.ApiTitle ?? ""; service.Info.Description = settings.ApiDescription ?? ""; using (var stream = new StreamWriter(FileSystem.GetFile(outputFile).OpenWrite())) { stream.WriteAsync(service.ToJson()).Wait(); } } } }
48.754545
130
0.64945
[ "MIT" ]
Jericho/Cake.NSwag
src/Cake.NSwag/Sources/AssemblySource.cs
5,365
C#
// <copyright file="ItemPage.Map.cs" company="Automate The Planet Ltd."> // Copyright 2016 Automate The Planet 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. // </copyright> // <author>Anton Angelov</author> // <site>http://automatetheplanet.com/</site> using OpenQA.Selenium; namespace PerfectSystemTestsDesign.Pages.ItemPage { public partial class ItemPage { public IWebElement AddToCartButton { get { return Driver.FindElement(By.Id("add-to-cart-button")); } } public IWebElement ProductTitle { get { return Driver.FindElement(By.Id("productTitle")); } } } }
34.111111
85
0.656352
[ "Apache-2.0" ]
alanmacgowan/AutomateThePlanet-Learning-Series
DesignPatternsInAutomatedTesting-Series/PerfectSystemTestsDesign/Pages/ItemPage/ItemPage.Map.cs
1,230
C#