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 MessagePack;
using Surging.Core.CPlatform.Messages;
using System.Collections.Generic;
using System.Linq;
namespace Surging.Core.Codec.MessagePack.Messages
{
[MessagePackObject]
public class ParameterItem
{
#region Constructor
public ParameterItem(KeyValuePair<string, object> item)
{
Key = item.Key;
Value = item.Value == null ? null : new DynamicItem(item.Value);
}
public ParameterItem()
{
}
#endregion Constructor
[Key(0)]
public string Key { get; set; }
[Key(1)]
public DynamicItem Value { get; set; }
}
[MessagePackObject]
public class MessagePackRemoteInvokeMessage
{
public MessagePackRemoteInvokeMessage(RemoteInvokeMessage message)
{
ServiceId = message.ServiceId;
Token = message.Token;
DecodeJOject = message.DecodeJOject;
ServiceKey = message.ServiceKey;
Parameters = message.Parameters?.Select(i => new ParameterItem(i)).ToArray();
Attachments = message.Attachments?.Select(i => new ParameterItem(i)).ToArray();
}
public MessagePackRemoteInvokeMessage()
{
}
[Key(0)]
public string ServiceId { get; set; }
[Key(1)]
public string Token { get; set; }
[Key(2)]
public bool DecodeJOject { get; set; }
[Key(3)]
public string ServiceKey { get; set; }
[Key(4)]
public ParameterItem[] Parameters { get; set; }
[Key(5)]
public ParameterItem[] Attachments { get; set; }
public RemoteInvokeMessage GetRemoteInvokeMessage()
{
return new RemoteInvokeMessage
{
Parameters = Parameters?.ToDictionary(i => i.Key, i => i.Value?.Get()),
Attachments = Attachments?.ToDictionary(i => i.Key, i => i.Value?.Get()),
ServiceId = ServiceId,
DecodeJOject = DecodeJOject,
ServiceKey = ServiceKey,
Token = Token
};
}
}
}
| 26.54321 | 91 | 0.563256 | [
"MIT"
] | haibinli/surging | src/Surging.Core/Surging.Core.Codec.MessagePack/Messages/MessagePackRemoteInvokeMessage.cs | 2,150 | C# |
using System;
using UnityEngine;
using UnityEngine.UI;
[AddComponentMenu("KMonoBehaviour/scripts/MinMaxSlider")]
public class MinMaxSlider : KMonoBehaviour
{
public enum LockingType
{
Toggle,
Drag
}
public enum Mode
{
Single,
Double,
Triple
}
public LockingType lockType = LockingType.Drag;
public bool lockRange;
public bool interactable = true;
public float minLimit;
public float maxLimit = 100f;
public float range = 50f;
public float barWidth = 10f;
public float barHeight = 100f;
public float currentMinValue = 10f;
public float currentMaxValue = 90f;
public float currentExtraValue = 50f;
public Slider.Direction direction;
public bool wholeNumbers = true;
public Action<MinMaxSlider> onMinChange;
public Action<MinMaxSlider> onMaxChange;
public Slider minSlider;
public Slider maxSlider;
public Slider extraSlider;
public RectTransform minRect;
public RectTransform maxRect;
public RectTransform bgFill;
public RectTransform mgFill;
public RectTransform fgFill;
public Text title;
[MyCmpGet]
public ToolTip toolTip;
public Image icon;
public Image isOverPowered;
private Vector3 mousePos;
public Mode mode { get; private set; }
protected override void OnSpawn()
{
base.OnSpawn();
ToolTip component = base.transform.parent.gameObject.GetComponent<ToolTip>();
if (component != null)
{
UnityEngine.Object.DestroyImmediate(toolTip);
toolTip = component;
}
minSlider.value = currentMinValue;
maxSlider.value = currentMaxValue;
minSlider.interactable = interactable;
maxSlider.interactable = interactable;
minSlider.maxValue = maxLimit;
maxSlider.maxValue = maxLimit;
minSlider.minValue = minLimit;
maxSlider.minValue = minLimit;
Slider.Direction direction3 = (minSlider.direction = (maxSlider.direction = this.direction));
if (isOverPowered != null)
{
isOverPowered.enabled = false;
}
minSlider.gameObject.SetActive(value: false);
if (mode != 0)
{
minSlider.gameObject.SetActive(value: true);
}
if (extraSlider != null)
{
extraSlider.value = currentExtraValue;
Slider slider = extraSlider;
Slider slider2 = minSlider;
bool flag2 = (maxSlider.wholeNumbers = wholeNumbers);
bool flag4 = (slider2.wholeNumbers = flag2);
slider.wholeNumbers = flag4;
extraSlider.direction = this.direction;
extraSlider.interactable = interactable;
extraSlider.maxValue = maxLimit;
extraSlider.minValue = minLimit;
extraSlider.gameObject.SetActive(value: false);
if (mode == Mode.Triple)
{
extraSlider.gameObject.SetActive(value: true);
}
}
}
public void SetIcon(Image newIcon)
{
icon = newIcon;
icon.gameObject.transform.SetParent(base.transform);
icon.gameObject.transform.SetAsFirstSibling();
icon.rectTransform().anchoredPosition = Vector2.zero;
}
public void SetMode(Mode mode)
{
this.mode = mode;
if (mode == Mode.Single && extraSlider != null)
{
extraSlider.gameObject.SetActive(value: false);
extraSlider.handleRect.gameObject.SetActive(value: false);
}
}
private void SetAnchor(RectTransform trans, Vector2 min, Vector2 max)
{
trans.anchorMin = min;
trans.anchorMax = max;
}
public void SetMinMaxValue(float currentMin, float currentMax, float min, float max)
{
float num2 = (currentMinValue = (minSlider.value = currentMin));
num2 = (currentMaxValue = (maxSlider.value = currentMax));
minLimit = min;
maxLimit = max;
minSlider.minValue = minLimit;
maxSlider.minValue = minLimit;
minSlider.maxValue = maxLimit;
maxSlider.maxValue = maxLimit;
if (extraSlider != null)
{
extraSlider.minValue = minLimit;
extraSlider.maxValue = maxLimit;
}
}
public void SetExtraValue(float current)
{
extraSlider.value = current;
toolTip.toolTip = base.transform.parent.name + ": " + current.ToString("F2");
}
public void SetMaxValue(float current, float max)
{
float num = current / max * 100f;
if (isOverPowered != null)
{
isOverPowered.enabled = num > 100f;
}
maxSlider.value = Mathf.Min(100f, num);
if (toolTip != null)
{
toolTip.toolTip = base.transform.parent.name + ": " + current.ToString("F2") + "/" + max.ToString("F2");
}
}
private void Update()
{
if (interactable)
{
minSlider.value = Mathf.Clamp(currentMinValue, minLimit, currentMinValue);
maxSlider.value = Mathf.Max(minSlider.value, Mathf.Clamp(currentMaxValue, Mathf.Max(minSlider.value, minLimit), maxLimit));
if (direction == Slider.Direction.LeftToRight || direction == Slider.Direction.RightToLeft)
{
minRect.anchorMax = new Vector2(minSlider.value / maxLimit, minRect.anchorMax.y);
maxRect.anchorMax = new Vector2(maxSlider.value / maxLimit, maxRect.anchorMax.y);
maxRect.anchorMin = new Vector2(minSlider.value / maxLimit, maxRect.anchorMin.y);
}
else
{
minRect.anchorMax = new Vector2(minRect.anchorMin.x, minSlider.value / maxLimit);
maxRect.anchorMin = new Vector2(maxRect.anchorMin.x, minSlider.value / maxLimit);
}
}
}
public void OnMinValueChanged(float ignoreThis)
{
if (interactable)
{
if (lockRange)
{
currentMaxValue = Mathf.Min(Mathf.Max(minLimit, minSlider.value) + range, maxLimit);
currentMinValue = Mathf.Max(minLimit, Mathf.Min(maxSlider.value, currentMaxValue - range));
}
else
{
currentMinValue = Mathf.Clamp(minSlider.value, minLimit, Mathf.Min(maxSlider.value, currentMaxValue));
}
if (onMinChange != null)
{
onMinChange(this);
}
}
}
public void OnMaxValueChanged(float ignoreThis)
{
if (interactable)
{
if (lockRange)
{
currentMinValue = Mathf.Max(maxSlider.value - range, minLimit);
currentMaxValue = Mathf.Max(minSlider.value, Mathf.Clamp(maxSlider.value, Mathf.Max(currentMinValue + range, minLimit), maxLimit));
}
else
{
currentMaxValue = Mathf.Max(minSlider.value, Mathf.Clamp(maxSlider.value, Mathf.Max(minSlider.value, minLimit), maxLimit));
}
if (onMaxChange != null)
{
onMaxChange(this);
}
}
}
public void Lock(bool shouldLock)
{
if (interactable && lockType == LockingType.Drag)
{
lockRange = shouldLock;
range = maxSlider.value - minSlider.value;
mousePos = KInputManager.GetMousePos();
}
}
public void ToggleLock()
{
if (interactable && lockType == LockingType.Toggle)
{
lockRange = !lockRange;
if (lockRange)
{
range = maxSlider.value - minSlider.value;
}
}
}
public void OnDrag()
{
if (interactable && lockRange && lockType == LockingType.Drag)
{
float num = KInputManager.GetMousePos().x - mousePos.x;
if (direction == Slider.Direction.TopToBottom || direction == Slider.Direction.BottomToTop)
{
num = KInputManager.GetMousePos().y - mousePos.y;
}
currentMinValue = Mathf.Max(currentMinValue + num, minLimit);
mousePos = KInputManager.GetMousePos();
}
}
}
| 24.169014 | 135 | 0.710227 | [
"MIT"
] | undancer/oni-data | Managed/main/MinMaxSlider.cs | 6,864 | C# |
using System;
using System.Threading.Tasks;
using Xunit;
using Xunit.Abstractions;
namespace PuppeteerSharp.Tests.FrameTests
{
[Collection("PuppeteerLoaderFixture collection")]
public class WaitForXPathTests : PuppeteerPageBaseTest
{
const string addElement = "tag => document.body.appendChild(document.createElement(tag))";
public WaitForXPathTests(ITestOutputHelper output) : base(output)
{
}
[Fact]
public async Task ShouldSupportSomeFancyXpath()
{
await Page.SetContentAsync("<p>red herring</p><p>hello world </p>");
var waitForXPath = Page.WaitForXPathAsync("//p[normalize-space(.)=\"hello world\"]");
Assert.Equal("hello world ", await Page.EvaluateFunctionAsync<string>("x => x.textContent", await waitForXPath));
}
[Fact]
public async Task ShouldRunInSpecifiedFrame()
{
await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);
await FrameUtils.AttachFrameAsync(Page, "frame2", TestConstants.EmptyPage);
var frame1 = Page.Frames[1];
var frame2 = Page.Frames[2];
var waitForXPathPromise = frame2.WaitForXPathAsync("//div");
await frame1.EvaluateFunctionAsync(addElement, "div");
await frame2.EvaluateFunctionAsync(addElement, "div");
var eHandle = await waitForXPathPromise;
Assert.Equal(frame2, eHandle.ExecutionContext.Frame);
}
[Fact]
public async Task ShouldThrowIfEvaluationFailed()
{
await Page.EvaluateOnNewDocumentAsync(@"function() {
document.evaluate = null;
}");
await Page.GoToAsync(TestConstants.EmptyPage);
var exception = await Assert.ThrowsAsync<EvaluationFailedException>(()
=> Page.WaitForXPathAsync("*"));
Assert.Contains("document.evaluate is not a function", exception.Message);
}
[Fact]
public async Task ShouldThrowWhenFrameIsDetached()
{
await FrameUtils.AttachFrameAsync(Page, "frame1", TestConstants.EmptyPage);
var frame = Page.Frames[1];
var waitPromise = frame.WaitForXPathAsync("//*[@class=\"box\"]");
await FrameUtils.DetachFrameAsync(Page, "frame1");
var exception = await Assert.ThrowsAnyAsync<Exception>(() => waitPromise);
Assert.Contains("waitForFunction failed: frame got detached.", exception.Message);
}
[Fact]
public async Task HiddenShouldWaitForDisplayNone()
{
var divHidden = false;
await Page.SetContentAsync("<div style='display: block;'></div>");
var waitForXPath = Page.WaitForXPathAsync("//div", new WaitForSelectorOptions { Hidden = true })
.ContinueWith(_ => divHidden = true);
await Page.WaitForXPathAsync("//div"); // do a round trip
Assert.False(divHidden);
await Page.EvaluateExpressionAsync("document.querySelector('div').style.setProperty('display', 'none')");
Assert.True(await waitForXPath);
Assert.True(divHidden);
}
[Fact]
public async Task ShouldReturnTheElementHandle()
{
var waitForXPath = Page.WaitForXPathAsync("//*[@class=\"zombo\"]");
await Page.SetContentAsync("<div class='zombo'>anything</div>");
Assert.Equal("anything", await Page.EvaluateFunctionAsync<string>("x => x.textContent", await waitForXPath));
}
[Fact]
public async Task ShouldAllowYouToSelectATextNode()
{
await Page.SetContentAsync("<div>some text</div>");
var text = await Page.WaitForXPathAsync("//div/text()");
Assert.Equal(3 /* Node.TEXT_NODE */, await (await text.GetPropertyAsync("nodeType")).JsonValueAsync<int>());
}
[Fact]
public async Task ShouldAllowYouToSelectAnElementWithSingleSlash()
{
await Page.SetContentAsync("<div>some text</div>");
var waitForXPath = Page.WaitForXPathAsync("/html/body/div");
Assert.Equal("some text", await Page.EvaluateFunctionAsync<string>("x => x.textContent", await waitForXPath));
}
[Fact]
public async Task ShouldRespectTimeout()
{
var exception = await Assert.ThrowsAsync<WaitTaskTimeoutException>(()
=> Page.WaitForXPathAsync("//div", new WaitForSelectorOptions { Timeout = 10 }));
Assert.Contains("waiting for XPath '//div' failed: timeout", exception.Message);
}
}
} | 43.119266 | 127 | 0.619574 | [
"MIT"
] | APMann/puppeteer-sharp | lib/PuppeteerSharp.Tests/FrameTests/WaitForXPathTests.cs | 4,702 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using EclipsePos.Apps.Context;
namespace EclipsePos.Apps.PosEvents
{
public class LoadQuickSalesDialog : PosEvent
{
public override void Engage(int keyValue)
{
try
{
PosEventStack.Instance.LoadDialog("FastSale");
PosEventStack.Instance.NextEvent();
}
catch
{
}
}
public override void Clear()
{
}
public override bool ValidTransition(string pEventName)
{
return true;
}
}
}
| 18.5 | 63 | 0.542042 | [
"MIT"
] | naushard/EclipsePOS | V.1.0.8/EclipsePOS.WPF.PosWorkBench/EclipsePos.Apps/PosEvents/LoadQuickSalesDialog.cs | 668 | C# |
using System;
using System.Collections.Generic;
using Barracuda;
using MLAgents.InferenceBrain;
namespace MLAgents.Sensor
{
/// <summary>
/// Allows sensors to write to both TensorProxy and float arrays/lists.
/// </summary>
public class WriteAdapter
{
IList<float> m_Data;
int m_Offset;
TensorProxy m_Proxy;
int m_Batch;
TensorShape m_TensorShape;
/// <summary>
/// Set the adapter to write to an IList at the given channelOffset.
/// </summary>
/// <param name="data">Float array or list that will be written to.</param>
/// <param name="shape">Shape of the observations to be written.</param>
/// <param name="offset">Offset from the start of the float data to write to.</param>
public void SetTarget(IList<float> data, int[] shape, int offset)
{
m_Data = data;
m_Offset = offset;
m_Proxy = null;
m_Batch = 0;
if (shape.Length == 1)
{
m_TensorShape = new TensorShape(m_Batch, shape[0]);
}
else
{
m_TensorShape = new TensorShape(m_Batch, shape[0], shape[1], shape[2]);
}
}
/// <summary>
/// Set the adapter to write to a TensorProxy at the given batch and channel offset.
/// </summary>
/// <param name="tensorProxy">Tensor proxy that will be writtent to.</param>
/// <param name="batchIndex">Batch index in the tensor proxy (i.e. the index of the Agent)</param>
/// <param name="channelOffset">Offset from the start of the channel to write to.</param>
public void SetTarget(TensorProxy tensorProxy, int batchIndex, int channelOffset)
{
m_Proxy = tensorProxy;
m_Batch = batchIndex;
m_Offset = channelOffset;
m_Data = null;
m_TensorShape = m_Proxy.data.shape;
}
/// <summary>
/// 1D write access at a specified index. Use AddRange if possible instead.
/// </summary>
/// <param name="index">Index to write to</param>
public float this[int index]
{
set
{
if (m_Data != null)
{
m_Data[index + m_Offset] = value;
}
else
{
m_Proxy.data[m_Batch, index + m_Offset] = value;
}
}
}
/// <summary>
/// 3D write access at the specified height, width, and channel. Only usable with a TensorProxy target.
/// </summary>
/// <param name="h"></param>
/// <param name="w"></param>
/// <param name="ch"></param>
public float this[int h, int w, int ch]
{
set
{
if (m_Data != null)
{
if (h < 0 || h >= m_TensorShape.height)
{
throw new IndexOutOfRangeException($"height value {h} must be in range [0, {m_TensorShape.height - 1}]");
}
if (w < 0 || w >= m_TensorShape.width)
{
throw new IndexOutOfRangeException($"width value {w} must be in range [0, {m_TensorShape.width - 1}]");
}
if (ch < 0 || ch >= m_TensorShape.channels)
{
throw new IndexOutOfRangeException($"channel value {ch} must be in range [0, {m_TensorShape.channels - 1}]");
}
var index = m_TensorShape.Index(m_Batch, h, w, ch + m_Offset);
m_Data[index] = value;
}
else
{
m_Proxy.data[m_Batch, h, w, ch + m_Offset] = value;
}
}
}
/// <summary>
/// Write the range of floats
/// </summary>
/// <param name="data"></param>
/// <param name="writeOffset">Optional write offset</param>
public void AddRange(IEnumerable<float> data, int writeOffset = 0)
{
if (m_Data != null)
{
int index = 0;
foreach (var val in data)
{
m_Data[index + m_Offset + writeOffset] = val;
index++;
}
}
else
{
int index = 0;
foreach (var val in data)
{
m_Proxy.data[m_Batch, index + m_Offset + writeOffset] = val;
index++;
}
}
}
}
}
| 33.801418 | 133 | 0.473773 | [
"Apache-2.0"
] | 107587084/ml-agents | com.unity.ml-agents/Runtime/Sensor/WriteAdapter.cs | 4,766 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CSharpGL;
namespace c03d02_ViewSpace
{
class CameraOutlineModel : IBufferSource
{
private const float halfWidth = 0.8f;
private const float halfHeight = halfWidth * 0.68f;
private const float halfDepth = halfHeight * 0.68f;
private static readonly vec3[] cubePostions = new vec3[]
{
new vec3(+halfWidth, +halfHeight, +halfDepth), // 0
new vec3(+halfWidth, +halfHeight, -halfDepth), // 1
new vec3(+halfWidth, -halfHeight, +halfDepth), // 2
new vec3(+halfWidth, -halfHeight, -halfDepth), // 3
new vec3(-halfWidth, +halfHeight, +halfDepth), // 4
new vec3(-halfWidth, +halfHeight, -halfDepth), // 5
new vec3(-halfWidth, -halfHeight, +halfDepth), // 6
new vec3(-halfWidth, -halfHeight, -halfDepth), // 7
};
static readonly vec3[] positions;
private static readonly uint[] cubeIndexes = new uint[]
{
0, 4, 2, 6, 3, 7, 1, 5,
0, 2, 1, 3, 5, 7, 4, 6,
0, 1, 4, 5, 6, 7, 2, 3,
};
static readonly uint[] indexes;
public const string strPosition = "position";
private VertexBuffer positionBuffer;
private IDrawCommand drawCommand;
static CameraOutlineModel()
{
const int segments = 30;
const float radius = 0.45f;
{
float shotLength = 2;
var circle = new List<vec3>();
for (int i = 0; i < segments; i++)
{
circle.Add(new vec3(
(float)Math.Cos(2.0 * Math.PI * (double)i / (double)segments) * radius,
(float)Math.Sin(2.0 * Math.PI * (double)i / (double)segments) * radius,
-halfDepth));
}
var circle2 = new List<vec3>();
for (int i = 0; i < segments; i++)
{
circle2.Add(new vec3(
(float)Math.Cos(2.0 * Math.PI * (double)i / (double)segments) * radius,
(float)Math.Sin(2.0 * Math.PI * (double)i / (double)segments) * radius,
-shotLength));
}
var list = new List<vec3>();
foreach (var item in cubePostions) { list.Add(item); }
list.AddRange(circle); list.AddRange(circle2);
CameraOutlineModel.positions = list.ToArray();
}
{
uint firstCircleIndex = (uint)cubePostions.Length;
var indexes = new List<uint>();
foreach (var item in cubeIndexes) { indexes.Add(item); }
for (uint i = 0; i < segments - 1; i++)
{
indexes.Add(i + firstCircleIndex);
indexes.Add(i + 1 + firstCircleIndex);
}
{
indexes.Add(segments - 1 + firstCircleIndex);
indexes.Add(0 + firstCircleIndex);
}
for (uint i = 0; i < segments - 1; i++)
{
indexes.Add(segments + i + firstCircleIndex);
indexes.Add(segments + i + 1 + firstCircleIndex);
}
{
indexes.Add(segments + segments - 1 + firstCircleIndex);
indexes.Add(segments + 0 + firstCircleIndex);
}
CameraOutlineModel.indexes = indexes.ToArray();
}
}
#region IBufferSource 成员
public IEnumerable<VertexBuffer> GetVertexAttribute(string bufferName)
{
if (strPosition == bufferName) // requiring position buffer.
{
if (this.positionBuffer == null)
{
this.positionBuffer = positions.GenVertexBuffer(VBOConfig.Vec3, BufferUsage.StaticDraw);
}
yield return this.positionBuffer;
}
else
{
throw new ArgumentException("bufferName");
}
}
public IEnumerable<IDrawCommand> GetDrawCommand()
{
if (this.drawCommand == null)
{
IndexBuffer indexBuffer = indexes.GenIndexBuffer(BufferUsage.StaticDraw);
this.drawCommand = new DrawElementsCmd(indexBuffer, DrawMode.Lines);
}
yield return this.drawCommand;
}
#endregion
}
}
| 36.724409 | 108 | 0.492496 | [
"MIT"
] | AugusZhan/CSharpGL | OpenGLviaCSharp/c03d02_ViewSpace/CameraOutlineModel.cs | 4,670 | 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.ComponentModel;
using System.Text.Json;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Components.RenderTree;
using Microsoft.AspNetCore.Components.Web;
using Microsoft.AspNetCore.Components.WebAssembly.Rendering;
using Microsoft.AspNetCore.Components.WebAssembly.Services;
using Microsoft.JSInterop;
namespace Microsoft.AspNetCore.Components.WebAssembly.Infrastructure
{
/// <summary>
/// Contains methods called by interop. Intended for framework use only, not supported for use in application
/// code.
/// </summary>
[EditorBrowsable(EditorBrowsableState.Never)]
public static class JSInteropMethods
{
private static WebEventJsonContext? _jsonContext;
/// <summary>
/// For framework use only.
/// </summary>
[JSInvokable(nameof(NotifyLocationChanged))]
public static void NotifyLocationChanged(string uri, bool isInterceptedLink)
{
WebAssemblyNavigationManager.Instance.SetLocation(uri, isInterceptedLink);
}
/// <summary>
/// For framework use only.
/// </summary>
[JSInvokable(nameof(DispatchEvent))]
public static Task DispatchEvent(WebEventDescriptor eventDescriptor, string eventArgsJson)
{
var renderer = RendererRegistry.Find(eventDescriptor.BrowserRendererId);
// JsonSerializerOptions are tightly bound to the JsonContext. Cache it on first use using a copy
// of the serializer settings.
if (_jsonContext is null)
{
var jsonSerializerOptions = DefaultWebAssemblyJSRuntime.Instance.ReadJsonSerializerOptions();
_jsonContext = new(new JsonSerializerOptions(jsonSerializerOptions));
}
var webEvent = WebEventData.Parse(renderer, _jsonContext, eventDescriptor, eventArgsJson);
return renderer.DispatchEventAsync(
webEvent.EventHandlerId,
webEvent.EventFieldInfo,
webEvent.EventArgs);
}
}
}
| 39.245614 | 113 | 0.688869 | [
"Apache-2.0"
] | CarlosAdmin/aspnetcore | src/Components/WebAssembly/WebAssembly/src/Infrastructure/JSInteropMethods.cs | 2,237 | C# |
// ----------------------------------------------------------------------------------
//
// Copyright Microsoft Corporation
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// http://www.apache.org/licenses/LICENSE-2.0
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ----------------------------------------------------------------------------------
using Microsoft.Azure;
using Microsoft.WindowsAzure.Commands.ServiceManagement.Network.Gateway.Model;
using System.Collections.Generic;
using System.Management.Automation;
namespace Microsoft.WindowsAzure.Commands.ServiceManagement.Network.Gateway
{
[Cmdlet(VerbsCommon.Reset, "AzureLocalNetworkGateway"), OutputType(typeof(AzureOperationResponse))]
public class ResetAzureLocalNetworkGateway : NetworkCmdletBase
{
[Parameter(Position = 0, Mandatory = true, HelpMessage = "Virtual network gateway Id.")]
[ValidateGuid]
[ValidateNotNullOrEmpty]
public string GatewayId
{
get; set;
}
[Parameter(Position = 1, Mandatory = true, HelpMessage = "The local network gateway AddressSpace.")]
[ValidateNotNullOrEmpty]
public List<string> AddressSpace
{
get; set;
}
public override void ExecuteCmdlet()
{
WriteObject(Client.UpdateLocalNetworkGateway(GatewayId, AddressSpace));
}
}
}
| 40.021739 | 109 | 0.62792 | [
"MIT"
] | DalavanCloud/azure-powershell | src/ServiceManagement/Network/Commands.Network/Gateway/UpdateAzureLocalNetworkGateway.cs | 1,798 | C# |
using System;
using Web.Api.Core.Dto.UseCaseResponses.Comment;
using Web.Api.Core.Interfaces;
namespace Web.Api.Core.Dto.UseCaseRequests.Comment
{
public class CreateCommentRequest : IUseCaseRequest<CreateCommentResponse>
{
public Guid RequestId { get; }
public string Content { get; }
public Domain.Entities.User Author { get; }
public Guid? ParentId { get; }
public CreateCommentRequest(Guid requestId, string content, Domain.Entities.User author, Guid? parentId)
{
RequestId = requestId;
Content = content;
Author = author;
ParentId = parentId;
}
}
} | 30.5 | 112 | 0.646796 | [
"MIT"
] | tdtrung17693/gdpr-system-backend | src/Web.Api.Core/Dto/UseCaseRequests/Comment/CreateCommentRequest.cs | 671 | C# |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License.
// You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0.
// Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and limitations under the License.
using System;
using NakedFramework.Architecture.Adapter;
using NakedFramework.Architecture.Component;
using NakedFramework.Architecture.Facet;
using NakedFramework.Architecture.Spec;
using NakedFramework.Core.Util;
using NakedFramework.Metamodel.SemanticsProvider;
namespace NakedFramework.Metamodel.Facet {
[Serializable]
public sealed class EncodeableFacetUsingEncoderDecoder<T> : FacetAbstract, IEncodeableFacet {
private readonly IValueSemanticsProvider<T> encoderDecoder;
public EncodeableFacetUsingEncoderDecoder(IValueSemanticsProvider<T> encoderDecoder, ISpecification holder)
: base(typeof(IEncodeableFacet), holder) =>
this.encoderDecoder = encoderDecoder;
public static string EncodedNull => "NULL";
protected override string ToStringValues() => encoderDecoder.ToString();
#region IEncodeableFacet Members
public INakedObjectAdapter FromEncodedString(string encodedData, INakedObjectManager manager) => EncodedNull.Equals(encodedData) ? null : manager.CreateAdapter(encoderDecoder.FromEncodedString(encodedData), null, null);
public string ToEncodedString(INakedObjectAdapter nakedObjectAdapter) => nakedObjectAdapter == null ? EncodedNull : encoderDecoder.ToEncodedString(nakedObjectAdapter.GetDomainObject<T>());
#endregion
}
} | 53.189189 | 227 | 0.779472 | [
"Apache-2.0"
] | NakedObjectsGroup/NakedObjectsFramework | NakedFramework/NakedFramework.Metamodel/Facet/EncodeableFacetUsingEncoderDecoder.cs | 1,968 | C# |
/*
* THIS FILE WAS GENERATED BY PLOTLY.BLAZOR.GENERATOR
*/
using System;
using System.Diagnostics.CodeAnalysis;
using System.IO;
using System.Runtime.Serialization.Formatters.Binary;
using System.Text.Json.Serialization;
namespace Plotly.Blazor.Traces.BarLib.MarkerLib.ColorBarLib.TitleLib
{
/// <summary>
/// The Font class.
/// </summary>
[System.CodeDom.Compiler.GeneratedCode("Plotly.Blazor.Generator", "1.0.0.0")]
[Serializable]
public class Font : IEquatable<Font>
{
/// <summary>
/// HTML font family - the typeface that will be applied by the web browser.
/// The web browser will only be able to apply a font if it is available on
/// the system which it operates. Provide multiple font families, separated
/// by commas, to indicate the preference in which to apply fonts if they aren't
/// available on the system. The Chart Studio Cloud (at https://chart-studio.plotly.com
/// or on-premise) generates images on a server, where only a select number
/// of fonts are installed and supported. These include <c>Arial</c>, <c>Balto</c>,
/// 'Courier New', 'Droid Sans',, 'Droid Serif', 'Droid
/// Sans Mono', 'Gravitas One', 'Old Standard TT', 'Open
/// Sans', <c>Overpass</c>, 'PT Sans Narrow', <c>Raleway</c>, 'Times
/// New Roman'.
/// </summary>
[JsonPropertyName(@"family")]
public string Family { get; set;}
/// <summary>
/// Gets or sets the Size.
/// </summary>
[JsonPropertyName(@"size")]
public decimal? Size { get; set;}
/// <summary>
/// Gets or sets the Color.
/// </summary>
[JsonPropertyName(@"color")]
public object Color { get; set;}
/// <inheritdoc />
public override bool Equals(object obj)
{
if (!(obj is Font other)) return false;
return ReferenceEquals(this, obj) || Equals(other);
}
/// <inheritdoc />
public bool Equals([AllowNull] Font other)
{
if (other == null) return false;
if (ReferenceEquals(this, other)) return true;
return
(
Family == other.Family ||
Family != null &&
Family.Equals(other.Family)
) &&
(
Size == other.Size ||
Size != null &&
Size.Equals(other.Size)
) &&
(
Color == other.Color ||
Color != null &&
Color.Equals(other.Color)
);
}
/// <inheritdoc />
public override int GetHashCode()
{
unchecked // Overflow is fine, just wrap
{
var hashCode = 41;
if (Family != null) hashCode = hashCode * 59 + Family.GetHashCode();
if (Size != null) hashCode = hashCode * 59 + Size.GetHashCode();
if (Color != null) hashCode = hashCode * 59 + Color.GetHashCode();
return hashCode;
}
}
/// <summary>
/// Checks for equality of the left Font and the right Font.
/// </summary>
/// <param name="left">Left Font.</param>
/// <param name="right">Right Font.</param>
/// <returns>Boolean</returns>
public static bool operator == (Font left, Font right)
{
return Equals(left, right);
}
/// <summary>
/// Checks for inequality of the left Font and the right Font.
/// </summary>
/// <param name="left">Left Font.</param>
/// <param name="right">Right Font.</param>
/// <returns>Boolean</returns>
public static bool operator != (Font left, Font right)
{
return !Equals(left, right);
}
/// <summary>
/// Gets a deep copy of this instance.
/// </summary>
/// <returns>Font</returns>
public Font DeepClone()
{
using var ms = new MemoryStream();
var formatter = new BinaryFormatter();
formatter.Serialize(ms, this);
ms.Position = 0;
return (Font) formatter.Deserialize(ms);
}
}
} | 35.421875 | 99 | 0.512572 | [
"MIT"
] | HansenBerlin/PlanspielWebapp | Plotly.Blazor/Traces/BarLib/MarkerLib/ColorBarLib/TitleLib/Font.cs | 4,534 | C# |
// Copyright (c) Microsoft Corporation.
// Licensed under the MIT License.
using System.Diagnostics;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Microsoft.ReverseProxy.Abstractions;
using Microsoft.ReverseProxy.Common.Tests;
using Microsoft.ReverseProxy.Telemetry;
using Xunit;
namespace Microsoft.ReverseProxy.Telemetry.Tests
{
public class ActivityPropagationHandlerTests
{
[Theory]
[InlineData(false, ActivityContextHeaders.BaggageAndCorrelationContext)]
[InlineData(true, ActivityContextHeaders.BaggageAndCorrelationContext)]
[InlineData(true, ActivityContextHeaders.Baggage)]
[InlineData(true, ActivityContextHeaders.CorrelationContext)]
public async Task SendAsync_CurrentActivitySet_RequestHeadersSet(bool useW3CFormat, ActivityContextHeaders activityContextHeaders)
{
const string TraceStateString = "CustomTraceStateString";
string expectedId = null;
var invoker = new HttpMessageInvoker(new ActivityPropagationHandler(activityContextHeaders, new MockHttpHandler(
(HttpRequestMessage request, CancellationToken cancellationToken) =>
{
var headers = request.Headers;
Assert.True(headers.TryGetValues(useW3CFormat ? "traceparent" : "Request-Id", out var values));
Assert.Equal(expectedId, Assert.Single(values));
if (useW3CFormat)
{
Assert.True(headers.TryGetValues("tracestate", out values));
Assert.Equal(TraceStateString, Assert.Single(values));
}
if (activityContextHeaders.HasFlag(ActivityContextHeaders.Baggage))
{
Assert.True(headers.TryGetValues("Baggage", out values));
Assert.Equal("foo=bar", Assert.Single(values));
}
if (activityContextHeaders.HasFlag(ActivityContextHeaders.CorrelationContext))
{
Assert.True(headers.TryGetValues("Correlation-Context", out values));
Assert.Equal("foo=bar", Assert.Single(values));
}
return Task.FromResult<HttpResponseMessage>(null);
})));
var activity = new Activity("CustomOperation");
if (useW3CFormat)
{
activity.SetIdFormat(ActivityIdFormat.W3C);
activity.TraceStateString = TraceStateString;
activity.SetParentId("00-01234567890123456789012345678901-0123456789012345-01");
}
else
{
activity.SetIdFormat(ActivityIdFormat.Hierarchical);
activity.SetParentId("|root");
}
activity.AddBaggage("foo", "bar");
activity.Start();
expectedId = activity.Id;
await invoker.SendAsync(new HttpRequestMessage(), CancellationToken.None);
activity.Stop();
}
}
}
| 38.839506 | 138 | 0.610935 | [
"MIT"
] | amweiss/reverse-proxy | test/ReverseProxy.Tests/Telemetry/ActivityPropagationHandlerTests.cs | 3,146 | 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.Okta
{
/// <summary>
/// Assigns groups to an application.
///
/// This resource allows you to create multiple App Group assignments.
///
/// ## Import
///
/// An application's group assignments can be imported via `app_id`.
///
/// ```sh
/// $ pulumi import okta:index/appGroupAssignments:AppGroupAssignments example <app_id>
/// ```
/// </summary>
[OktaResourceType("okta:index/appGroupAssignments:AppGroupAssignments")]
public partial class AppGroupAssignments : Pulumi.CustomResource
{
/// <summary>
/// The ID of the application to assign a group to.
/// </summary>
[Output("appId")]
public Output<string> AppId { get; private set; } = null!;
/// <summary>
/// A group to assign the app to.
/// </summary>
[Output("groups")]
public Output<ImmutableArray<Outputs.AppGroupAssignmentsGroup>> Groups { get; private set; } = null!;
/// <summary>
/// Create a AppGroupAssignments 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 AppGroupAssignments(string name, AppGroupAssignmentsArgs args, CustomResourceOptions? options = null)
: base("okta:index/appGroupAssignments:AppGroupAssignments", name, args ?? new AppGroupAssignmentsArgs(), MakeResourceOptions(options, ""))
{
}
private AppGroupAssignments(string name, Input<string> id, AppGroupAssignmentsState? state = null, CustomResourceOptions? options = null)
: base("okta:index/appGroupAssignments:AppGroupAssignments", 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 AppGroupAssignments 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 AppGroupAssignments Get(string name, Input<string> id, AppGroupAssignmentsState? state = null, CustomResourceOptions? options = null)
{
return new AppGroupAssignments(name, id, state, options);
}
}
public sealed class AppGroupAssignmentsArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The ID of the application to assign a group to.
/// </summary>
[Input("appId", required: true)]
public Input<string> AppId { get; set; } = null!;
[Input("groups", required: true)]
private InputList<Inputs.AppGroupAssignmentsGroupArgs>? _groups;
/// <summary>
/// A group to assign the app to.
/// </summary>
public InputList<Inputs.AppGroupAssignmentsGroupArgs> Groups
{
get => _groups ?? (_groups = new InputList<Inputs.AppGroupAssignmentsGroupArgs>());
set => _groups = value;
}
public AppGroupAssignmentsArgs()
{
}
}
public sealed class AppGroupAssignmentsState : Pulumi.ResourceArgs
{
/// <summary>
/// The ID of the application to assign a group to.
/// </summary>
[Input("appId")]
public Input<string>? AppId { get; set; }
[Input("groups")]
private InputList<Inputs.AppGroupAssignmentsGroupGetArgs>? _groups;
/// <summary>
/// A group to assign the app to.
/// </summary>
public InputList<Inputs.AppGroupAssignmentsGroupGetArgs> Groups
{
get => _groups ?? (_groups = new InputList<Inputs.AppGroupAssignmentsGroupGetArgs>());
set => _groups = value;
}
public AppGroupAssignmentsState()
{
}
}
}
| 38.604478 | 155 | 0.620723 | [
"ECL-2.0",
"Apache-2.0"
] | pulumi/pulumi-okta | sdk/dotnet/AppGroupAssignments.cs | 5,173 | C# |
using Autofac;
using Microsoft.Bot.Builder.Dialogs.Internals;
using Microsoft.Bot.Builder.Internals.Fibers;
using Microsoft.Bot.Connector;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using System.Web.Http;
namespace Microsoft.Bot.Sample.AlarmBot.Controllers
{
// Autofac provides a mechanism to inject ActionFilterAttributes from the container
// but seems to require the implementation of special interfaces
// https://github.com/autofac/Autofac.WebApi/issues/6
[BotAuthentication]
public sealed class MessagesController : ApiController
{
// TODO: "service locator"
private readonly ILifetimeScope scope;
public MessagesController(ILifetimeScope scope)
{
SetField.NotNull(out this.scope, nameof(scope), scope);
}
public async Task<HttpResponseMessage> Post([FromBody] Activity activity, CancellationToken token)
{
if (activity != null)
{
switch (activity.GetActivityType())
{
case ActivityTypes.Message:
using (var scope = DialogModule.BeginLifetimeScope(this.scope, activity))
{
var postToBot = scope.Resolve<IPostToBot>();
await postToBot.PostAsync(activity, token);
}
break;
}
}
return new HttpResponseMessage(HttpStatusCode.Accepted);
}
}
} | 34.145833 | 106 | 0.6205 | [
"MIT"
] | Aaron-Strong/BotBuilder | CSharp/Samples/AlarmBot/Controllers/MessagesController.cs | 1,641 | C# |
#region Copyright 2014 Exceptionless
// This program is free software: you can redistribute it and/or modify it
// under the terms of the GNU Affero General Public License as published
// by the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// http://www.gnu.org/licenses/agpl-3.0.html
#endregion
using System;
using ServiceStack.CacheAccess;
namespace Exceptionless.Extensions {
public static class CacheClientExtensions {
public static T TryGet<T>(this ICacheClient client, string key) {
return TryGet<T>(client, key, default(T));
}
public static T TryGet<T>(this ICacheClient client, string key, T defaultValue) {
try {
return client.Get<T>(key);
} catch (Exception) {
return defaultValue;
}
}
}
} | 30.758621 | 89 | 0.647982 | [
"Apache-2.0"
] | darbio/Exceptionless | Source/Core/Extensions/CacheClientExtensions.cs | 894 | C# |
using System;
using System.Linq;
using System.Threading.Tasks;
using UnityEngine;
#if UNITY_WSA && !UNITY_EDITOR
using Windows.Storage;
using Windows.Media.Capture;
using Windows.Media.MediaProperties;
using Windows.Media.Capture.Frames;
#endif
public class CaptureFrame : MonoBehaviour
{
private GameObject Label;
private TextMesh LabelText;
private TimeSpan predictEvery = TimeSpan.FromMilliseconds(50);
private string textToDisplay;
private bool textToDisplayChanged;
#if WINDOWS_UWP
MediaCapture MediaCapture;
#endif
private void Start()
{
LabelText = Label.GetComponent<TextMesh>();
#if WINDOWS_UWP
CreateMediaCapture();
InitializeModel();
#else
DisplayText("Does not work in player.");
#endif
}
private void DisplayText(string text)
{
textToDisplay = text;
textToDisplayChanged = true;
}
#if WINDOWS_UWP
private async void InitializeModel()
{
StorageFile imageRecoModelFile = await StorageFile.GetFileFromApplicationUriAsync(new Uri($"ms-appx:///Data/StreamingAssets/MySuperCoolOnnxModel.onnx"));
}
private async void CreateMediaCapture()
{
MediaCapture = new MediaCapture();
MediaCaptureInitializationSettings settings = new MediaCaptureInitializationSettings();
settings.StreamingCaptureMode = StreamingCaptureMode.Video;
await MediaCapture.InitializeAsync(settings);
CreateFrameReader();
}
private async void CreateFrameReader()
{
var frameSourceGroups = await MediaFrameSourceGroup.FindAllAsync();
MediaFrameSourceGroup selectedGroup = null;
MediaFrameSourceInfo colorSourceInfo = null;
foreach (var sourceGroup in frameSourceGroups)
{
foreach (var sourceInfo in sourceGroup.SourceInfos)
{
if (sourceInfo.MediaStreamType == MediaStreamType.VideoPreview
&& sourceInfo.SourceKind == MediaFrameSourceKind.Color)
{
colorSourceInfo = sourceInfo;
break;
}
}
if (colorSourceInfo != null)
{
selectedGroup = sourceGroup;
break;
}
}
var colorFrameSource = MediaCapture.FrameSources[colorSourceInfo.Id];
var preferredFormat = colorFrameSource.SupportedFormats.Where(format =>
{
return format.Subtype == MediaEncodingSubtypes.Argb32;
}).FirstOrDefault();
var mediaFrameReader = await MediaCapture.CreateFrameReaderAsync(colorFrameSource);
await mediaFrameReader.StartAsync();
StartPullFrames(mediaFrameReader);
}
private void StartPullFrames(MediaFrameReader sender)
{
Task.Run(async () =>
{
for (;;)
{
var frameReference = sender.TryAcquireLatestFrame();
var videoFrame = frameReference?.VideoMediaFrame?.GetVideoFrame();
if (videoFrame == null)
{
continue; //ignoring frame
}
if(videoFrame.Direct3DSurface == null)
{
continue; //ignoring frame
}
await Task.Delay(predictEvery);
}
});
}
#endif
private void Update()
{
if (textToDisplayChanged)
{
LabelText.text = textToDisplay;
textToDisplayChanged = false;
}
}
} | 27.369231 | 161 | 0.61439 | [
"MIT"
] | kmather73/WinML-Image-Preprocessing | Unity/WinMLImage/Assets/WinML/CaptureFrame.cs | 3,560 | C# |
using System;
using System.IO;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using Newtonsoft.Json;
using Newtonsoft.Json.Converters;
using Square.Http.Client;
using Square;
using Square.Utilities;
namespace Square.Models
{
public class GetTerminalCheckoutResponse
{
public GetTerminalCheckoutResponse(IList<Models.Error> errors = null,
Models.TerminalCheckout checkout = null)
{
Errors = errors;
Checkout = checkout;
}
[JsonIgnore]
public HttpContext Context { get; internal set; }
/// <summary>
/// Information on errors encountered during the request.
/// </summary>
[JsonProperty("errors")]
public IList<Models.Error> Errors { get; }
/// <summary>
/// Getter for checkout
/// </summary>
[JsonProperty("checkout")]
public Models.TerminalCheckout Checkout { get; }
public Builder ToBuilder()
{
var builder = new Builder()
.Errors(Errors)
.Checkout(Checkout);
return builder;
}
public class Builder
{
private IList<Models.Error> errors = new List<Models.Error>();
private Models.TerminalCheckout checkout;
public Builder() { }
public Builder Errors(IList<Models.Error> value)
{
errors = value;
return this;
}
public Builder Checkout(Models.TerminalCheckout value)
{
checkout = value;
return this;
}
public GetTerminalCheckoutResponse Build()
{
return new GetTerminalCheckoutResponse(errors,
checkout);
}
}
}
} | 27.30137 | 78 | 0.540893 | [
"Apache-2.0"
] | kaijaa/square-dotnet-sdk | Square/Models/GetTerminalCheckoutResponse.cs | 1,993 | C# |
//
// _ _ ______ _ _ _ _ _ _ _
// | \ | | | ____| | (_) | (_) | | | |
// | \| | ___ | |__ __| |_| |_ _ _ __ __ _| | | |
// | . ` |/ _ \ | __| / _` | | __| | '_ \ / _` | | | |
// | |\ | (_) | | |___| (_| | | |_| | | | | (_| |_|_|_|
// |_| \_|\___/ |______\__,_|_|\__|_|_| |_|\__, (_|_|_)
// __/ |
// |___/
//
// This file is auto-generated. Do not edit manually
//
// Copyright 2013-2022 Step Function I/O, LLC
//
// Licensed to Green Energy Corp (www.greenenergycorp.com) and Step Function I/O
// LLC (https://stepfunc.io) under one or more contributor license agreements.
// See the NOTICE file distributed with this work for additional information
// regarding copyright ownership. Green Energy Corp and Step Function I/O LLC license
// 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.
//
namespace Automatak.DNP3.Interface
{
/// <summary>
/// </summary>
public enum EventSecurityStatVariation : byte
{
Group122Var1 = 0,
Group122Var2 = 1
}
}
| 38.52381 | 85 | 0.584672 | [
"Apache-2.0"
] | bevanweiss/opendnp3 | dotnet/CLRInterface/src/gen/EventSecurityStatVariation.cs | 1,618 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("Krillin.App.UWP")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("Krillin.App.UWP")]
[assembly: AssemblyCopyright("Copyright © 2015")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// 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")]
[assembly: ComVisible(false)] | 37.068966 | 85 | 0.72 | [
"Apache-2.0"
] | marcoablanco/GS.Reader.Rss | Krillin/Krillin.App/Krillin.App/Krillin.App.UWP/Properties/AssemblyInfo.cs | 1,078 | C# |
using System;
using Zeebe.Client.Bootstrap.Abstractions;
namespace Zeebe.Client.Bootstrap.Attributes
{
public class PollIntervalAttribute : AbstractJobAttribute
{
public PollIntervalAttribute(long pollIntervalInMilliseconds)
{
if (pollIntervalInMilliseconds < 1)
{
throw new ArgumentException($"'{nameof(pollIntervalInMilliseconds)}' cannot be smaller then one millisecond.", nameof(pollIntervalInMilliseconds));
}
this.PollInterval = TimeSpan.FromMilliseconds(pollIntervalInMilliseconds);
}
public TimeSpan PollInterval { get; }
}
} | 32.45 | 163 | 0.681048 | [
"Apache-2.0"
] | camunda-community-hub/zeebe-client-csharp-bootstrap | src/Zeebe.Client.Bootstrap/Attributes/PollIntervalAttribute.cs | 649 | C# |
using Newtonsoft.Json;
using Newtonsoft.Json.Linq;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
namespace DocumentComparer
{
public class JsonComparer
{
#region Methods
public void CompareProject(CompareProject inProject, string inOutput)
{
if ( inProject == null )
{
return;
}
StringBuilder projectLog = new StringBuilder();
Console.WriteLine( $"Starting comparision for project {inProject.Name}" );
projectLog.AppendLine( $"Starting comparision for project {inProject.Name}" );
List<string> ProjectFileNames = new List<string>();
Dictionary<string, bool> FileComparisionResult = new Dictionary<string, bool>();
// Use first path as reference
string ReferencePath = inProject.Paths[ 0 ];
FileInfo[] files = ( new DirectoryInfo( ReferencePath ) ).GetFiles( "*.json" );
foreach ( FileInfo info in files )
{
ProjectFileNames.Add( info.Name );
}
// Compare files
foreach ( string fileName in ProjectFileNames )
{
projectLog.AppendLine( $"Comparing file: {fileName}" );
// Load files
List<JToken> filesToCompare = new List<JToken>();
foreach ( string baseFolder in inProject.Paths )
{
try
{
filesToCompare.Add( Utils.LoadJsonFromFile( $"{baseFolder}\\{fileName}" ) );
} catch (FileNotFoundException)
{
projectLog.AppendLine( $"File: {baseFolder}\\{fileName} does not exists." );
}
}
// use first file as base for comparision
JToken baseFile = filesToCompare[ 0 ];
bool isMatch = true;
foreach ( JToken jsonFile in filesToCompare )
{
if ( baseFile == jsonFile )
{
continue;
}
isMatch = JToken.DeepEquals( baseFile, jsonFile );
projectLog.AppendLine( $"Are files equal? {isMatch}" );
}
FileComparisionResult.Add( fileName, isMatch );
}
// Check for potential failures
var failedFiles = FileComparisionResult.Where( f => f.Value == false );
foreach ( var failedFile in failedFiles )
{
projectLog.AppendLine( $"File: {failedFile.Key} does not match reference file [comparision result: {failedFile.Value}]" );
}
// Write log file
using ( StreamWriter sw = new StreamWriter( $"{inOutput}\\{inProject.Name}.log" ) )
{
sw.Write( projectLog.ToString() );
sw.Close();
}
}
#endregion
#region Constructor
public JsonComparer() { }
#endregion
}
} | 34 | 138 | 0.514548 | [
"MIT"
] | slowvoid/mongoQueryGenerator | MongoQueryGenerator/DocumentComparer/JsonComparer.cs | 3,164 | 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.Text;
using System.Diagnostics;
using System.Collections.Generic;
using System.Threading.Tasks;
namespace System.Xml
{
internal partial class XmlWellFormedWriter : XmlWriter
{
private partial struct ElementScope
{
internal Task WriteEndElementAsync(XmlRawWriter rawWriter)
{
return rawWriter.WriteEndElementAsync(prefix, localName, namespaceUri);
}
internal Task WriteFullEndElementAsync(XmlRawWriter rawWriter)
{
return rawWriter.WriteFullEndElementAsync(prefix, localName, namespaceUri);
}
}
private partial struct Namespace
{
internal async Task WriteDeclAsync(XmlWriter writer, XmlRawWriter rawWriter)
{
Debug.Assert(kind == NamespaceKind.NeedToWrite);
if (null != rawWriter)
{
await rawWriter.WriteNamespaceDeclarationAsync(prefix, namespaceUri).ConfigureAwait(false);
}
else
{
if (prefix.Length == 0)
{
await writer.WriteStartAttributeAsync(string.Empty, "xmlns", XmlReservedNs.NsXmlNs).ConfigureAwait(false);
}
else
{
await writer.WriteStartAttributeAsync("xmlns", prefix, XmlReservedNs.NsXmlNs).ConfigureAwait(false);
}
await writer.WriteStringAsync(namespaceUri).ConfigureAwait(false);
await writer.WriteEndAttributeAsync().ConfigureAwait(false);
}
}
}
private partial class AttributeValueCache
{
internal async Task ReplayAsync(XmlWriter writer)
{
if (_singleStringValue != null)
{
await writer.WriteStringAsync(_singleStringValue).ConfigureAwait(false);
return;
}
BufferChunk bufChunk;
for (int i = _firstItem; i <= _lastItem; i++)
{
Item item = _items[i];
switch (item.type)
{
case ItemType.EntityRef:
await writer.WriteEntityRefAsync((string)item.data).ConfigureAwait(false);
break;
case ItemType.CharEntity:
await writer.WriteCharEntityAsync((char)item.data).ConfigureAwait(false);
break;
case ItemType.SurrogateCharEntity:
char[] chars = (char[])item.data;
await writer.WriteSurrogateCharEntityAsync(chars[0], chars[1]).ConfigureAwait(false);
break;
case ItemType.Whitespace:
await writer.WriteWhitespaceAsync((string)item.data).ConfigureAwait(false);
break;
case ItemType.String:
await writer.WriteStringAsync((string)item.data).ConfigureAwait(false);
break;
case ItemType.StringChars:
bufChunk = (BufferChunk)item.data;
await writer.WriteCharsAsync(bufChunk.buffer, bufChunk.index, bufChunk.count).ConfigureAwait(false);
break;
case ItemType.Raw:
await writer.WriteRawAsync((string)item.data).ConfigureAwait(false);
break;
case ItemType.RawChars:
bufChunk = (BufferChunk)item.data;
await writer.WriteCharsAsync(bufChunk.buffer, bufChunk.index, bufChunk.count).ConfigureAwait(false);
break;
case ItemType.ValueString:
await writer.WriteStringAsync((string)item.data).ConfigureAwait(false);
break;
default:
Debug.Assert(false, "Unexpected ItemType value.");
break;
}
}
}
}
}
}
| 42.614679 | 130 | 0.507427 | [
"MIT"
] | 2E0PGS/corefx | src/System.Private.Xml/src/System/Xml/Core/XmlWellFormedWriterHelpersAsync.cs | 4,645 | 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.Azure.DataFactory.Inputs
{
public sealed class DatasetDelimitedTextAzureBlobFsLocationGetArgs : Pulumi.ResourceArgs
{
/// <summary>
/// The storage data lake gen2 file system on the Azure Blob Storage Account hosting the file.
/// </summary>
[Input("fileSystem", required: true)]
public Input<string> FileSystem { get; set; } = null!;
/// <summary>
/// The filename of the file.
/// </summary>
[Input("filename")]
public Input<string>? Filename { get; set; }
/// <summary>
/// The folder path to the file.
/// </summary>
[Input("path")]
public Input<string>? Path { get; set; }
public DatasetDelimitedTextAzureBlobFsLocationGetArgs()
{
}
}
}
| 29.842105 | 102 | 0.62522 | [
"ECL-2.0",
"Apache-2.0"
] | ScriptBox99/pulumi-azure | sdk/dotnet/DataFactory/Inputs/DatasetDelimitedTextAzureBlobFsLocationGetArgs.cs | 1,134 | C# |
using System.Configuration;
using System.Linq;
namespace NServiceBus
{
using Features;
using Logging;
public class SimpleStatisticsFeature : Feature
{
internal static readonly string SettingKey = "NServiceBus/SimpleStatistics";
protected override void Setup(FeatureConfigurationContext context)
{
var settings = ConfigurationManager.AppSettings;
bool enable;
if (settings.AllKeys.Contains(SettingKey) && bool.TryParse(settings[SettingKey], out enable) && !enable) return;
EnableByDefault();
context.Container.ConfigureComponent<Collector>(DependencyLifecycle.SingleInstance);
RegisterStartupTask<StartupTask>();
context.Container.ConfigureComponent<SimpleStatisticsBehavior>(DependencyLifecycle.SingleInstance);
// Register the new step in the pipeline
context.Pipeline.Register<SimpleStatisticsBehavior.Step>();
}
internal class StartupTask : FeatureStartupTask
{
public Collector Collector { get; set; }
protected override void OnStart()
{
Collector.Start();
}
protected override void OnStop()
{
Collector.Stop();
}
}
}
} | 30.953488 | 124 | 0.628099 | [
"MIT"
] | ramonsmits/NServiceBus.SimpleStatistics | src/NServiceBus.SimpleStatistics/SimpleStatisticsFeature.cs | 1,331 | 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.Management.ApiManagement
{
using Microsoft.Azure;
using Microsoft.Azure.Management;
using Microsoft.Rest;
using Microsoft.Rest.Azure;
using Microsoft.Rest.Azure.OData;
using Models;
using System.Collections;
using System.Collections.Generic;
using System.Threading;
using System.Threading.Tasks;
/// <summary>
/// BackendOperations operations.
/// </summary>
public partial interface IBackendOperations
{
/// <summary>
/// Lists a collection of backends in the specified service instance.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='odataQuery'>
/// OData parameters to apply to the operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<BackendContract>>> ListByServiceWithHttpMessagesAsync(string resourceGroupName, string serviceName, ODataQuery<BackendContract> odataQuery = default(ODataQuery<BackendContract>), Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Gets the details of the backend specified by its identifier.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='backendid'>
/// Identifier of the Backend entity. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<BackendContract,BackendGetHeaders>> GetWithHttpMessagesAsync(string resourceGroupName, string serviceName, string backendid, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Creates or Updates a backend.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='backendid'>
/// Identifier of the Backend entity. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='parameters'>
/// Create parameters.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<BackendContract>> CreateOrUpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string backendid, BackendContract parameters, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Updates an existing backend.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='backendid'>
/// Identifier of the Backend entity. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='parameters'>
/// Update parameters.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the backend to update. A value
/// of "*" can be used for If-Match to unconditionally apply the
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> UpdateWithHttpMessagesAsync(string resourceGroupName, string serviceName, string backendid, BackendUpdateParameters parameters, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Deletes the specified backend.
/// </summary>
/// <param name='resourceGroupName'>
/// The name of the resource group.
/// </param>
/// <param name='serviceName'>
/// The name of the API Management service.
/// </param>
/// <param name='backendid'>
/// Identifier of the Backend entity. Must be unique in the current API
/// Management service instance.
/// </param>
/// <param name='ifMatch'>
/// The entity state (Etag) version of the backend to delete. A value
/// of "*" can be used for If-Match to unconditionally apply the
/// operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse> DeleteWithHttpMessagesAsync(string resourceGroupName, string serviceName, string backendid, string ifMatch, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
/// <summary>
/// Lists a collection of backends in the specified service instance.
/// </summary>
/// <param name='nextPageLink'>
/// The NextLink from the previous successful call to List operation.
/// </param>
/// <param name='customHeaders'>
/// The headers that will be added to request.
/// </param>
/// <param name='cancellationToken'>
/// The cancellation token.
/// </param>
/// <exception cref="ErrorResponseException">
/// Thrown when the operation returned an invalid status code
/// </exception>
/// <exception cref="Microsoft.Rest.SerializationException">
/// Thrown when unable to deserialize the response
/// </exception>
/// <exception cref="Microsoft.Rest.ValidationException">
/// Thrown when a required parameter is null
/// </exception>
Task<AzureOperationResponse<IPage<BackendContract>>> ListByServiceNextWithHttpMessagesAsync(string nextPageLink, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken));
}
}
| 46.75122 | 342 | 0.622496 | [
"MIT"
] | AzureAutomationTeam/azure-sdk-for-net | src/SDKs/ApiManagement/Management.ApiManagement/Generated/IBackendOperations.cs | 9,584 | C# |
/*
===============================================================================
EntitySpaces 2010 by EntitySpaces, LLC
Persistence Layer and Business Objects for Microsoft .NET
EntitySpaces(TM) is a legal trademark of EntitySpaces, LLC
http://www.entityspaces.net
===============================================================================
EntitySpaces Version : 2011.0.0321.0
EntitySpaces Driver : SQL
Date Generated : 3/19/2011 7:07:14 PM
===============================================================================
*/
using System;
using EntitySpaces.Core;
using EntitySpaces.Interfaces;
using EntitySpaces.DynamicQuery;
namespace BusinessObjects
{
public partial class EmployeesQuery : esEmployeesQuery
{
public EmployeesQuery()
{
}
}
}
| 28.166667 | 79 | 0.484024 | [
"Unlicense"
] | EntitySpaces/EntitySpaces-CompleteSource | Samples/WindowsPhone/WcfService/Custom/EmployeesQuery.cs | 845 | C# |
/* Copyright 2015-present MongoDB Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
using MongoDB.Bson.Serialization;
using MongoDB.Bson.Serialization.Serializers;
namespace MongoDB.Driver
{
internal sealed class OfTypeSerializer<TRootDocument, TDerivedDocument> : SerializerBase<TDerivedDocument>, IBsonDocumentSerializer
where TDerivedDocument : TRootDocument
{
private readonly IBsonSerializer<TDerivedDocument> _derivedDocumentSerializer;
public OfTypeSerializer(IBsonSerializer<TDerivedDocument> derivedDocumentSerializer)
{
_derivedDocumentSerializer = derivedDocumentSerializer;
}
public override TDerivedDocument Deserialize(BsonDeserializationContext context, BsonDeserializationArgs args)
{
args.NominalType = typeof(TRootDocument);
return _derivedDocumentSerializer.Deserialize(context, args);
}
public override void Serialize(BsonSerializationContext context, BsonSerializationArgs args, TDerivedDocument value)
{
args.NominalType = typeof(TRootDocument);
_derivedDocumentSerializer.Serialize(context, args, value);
}
public bool TryGetMemberSerializationInfo(string memberName, out BsonSerializationInfo serializationInfo)
{
var documentSerializer = _derivedDocumentSerializer as IBsonDocumentSerializer;
if (documentSerializer == null)
{
serializationInfo = null;
return false;
}
return documentSerializer.TryGetMemberSerializationInfo(memberName, out serializationInfo);
}
}
}
| 39.839286 | 136 | 0.705513 | [
"MIT"
] | naivetang/2019MiniGame22 | Server/ThirdParty/MongoDBDriver/MongoDB.Driver/OfTypeSerializer.cs | 2,233 | 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.Linq;
using Microsoft.CodeAnalysis.CSharp.Syntax;
using Microsoft.CodeAnalysis.CSharp.Test.Utilities;
using Roslyn.Test.Utilities;
using Xunit;
using Xunit.Abstractions;
namespace Microsoft.CodeAnalysis.CSharp.UnitTests
{
public class ExpressionParsingTests : ParsingTests
{
public ExpressionParsingTests(ITestOutputHelper output) : base(output) { }
protected override SyntaxTree ParseTree(string text, CSharpParseOptions options)
{
return SyntaxFactory.ParseSyntaxTree(text, options: options);
}
private ExpressionSyntax ParseExpression(string text, ParseOptions options = null)
{
return SyntaxFactory.ParseExpression(text, options: options);
}
[Fact]
public void TestEmptyString()
{
var text = string.Empty;
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.IdentifierName, expr.Kind());
Assert.True(((IdentifierNameSyntax)expr).Identifier.IsMissing);
Assert.Equal(text, expr.ToString());
Assert.Equal(1, expr.Errors().Length);
Assert.Equal((int)ErrorCode.ERR_ExpressionExpected, expr.Errors()[0].Code);
}
[Fact]
public void TestInterpolatedVerbatimString()
{
UsingExpression(@"$@""hello""");
N(SyntaxKind.InterpolatedStringExpression);
{
N(SyntaxKind.InterpolatedVerbatimStringStartToken);
N(SyntaxKind.InterpolatedStringText);
{
N(SyntaxKind.InterpolatedStringTextToken);
}
N(SyntaxKind.InterpolatedStringEndToken);
}
EOF();
}
[Fact]
public void TestAltInterpolatedVerbatimString_CSharp73()
{
UsingExpression(@"@$""hello""", TestOptions.Regular7_3,
// (1,1): error CS8401: To use '@$' instead of '$@' for an interpolated verbatim string, please use language version '8.0' or greater.
// @$"hello"
Diagnostic(ErrorCode.ERR_AltInterpolatedVerbatimStringsNotAvailable, @"@$""").WithArguments("8.0").WithLocation(1, 1)
);
N(SyntaxKind.InterpolatedStringExpression);
{
N(SyntaxKind.InterpolatedVerbatimStringStartToken);
N(SyntaxKind.InterpolatedStringText);
{
N(SyntaxKind.InterpolatedStringTextToken);
}
N(SyntaxKind.InterpolatedStringEndToken);
}
EOF();
}
[Fact]
public void TestAltInterpolatedVerbatimString_CSharp8()
{
UsingExpression(@"@$""hello""", TestOptions.Regular8);
N(SyntaxKind.InterpolatedStringExpression);
{
N(SyntaxKind.InterpolatedVerbatimStringStartToken);
N(SyntaxKind.InterpolatedStringText);
{
N(SyntaxKind.InterpolatedStringTextToken);
}
N(SyntaxKind.InterpolatedStringEndToken);
}
EOF();
}
[Fact]
public void TestNestedAltInterpolatedVerbatimString_CSharp73()
{
UsingExpression("$@\"aaa{@$\"bbb\nccc\"}ddd\"", TestOptions.Regular7_3,
// (1,8): error CS8401: To use '@$' instead of '$@' for an interpolated verbatim string, please use language version '8.0' or greater.
// $@"aaa{@$"bbb
Diagnostic(ErrorCode.ERR_AltInterpolatedVerbatimStringsNotAvailable, @"@$""").WithArguments("8.0").WithLocation(1, 8)
);
N(SyntaxKind.InterpolatedStringExpression);
{
N(SyntaxKind.InterpolatedVerbatimStringStartToken);
N(SyntaxKind.InterpolatedStringText);
{
N(SyntaxKind.InterpolatedStringTextToken, "aaa");
}
N(SyntaxKind.Interpolation);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.InterpolatedStringExpression);
{
N(SyntaxKind.InterpolatedVerbatimStringStartToken);
N(SyntaxKind.InterpolatedStringText);
{
N(SyntaxKind.InterpolatedStringTextToken, "bbb\nccc");
}
N(SyntaxKind.InterpolatedStringEndToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.InterpolatedStringText);
{
N(SyntaxKind.InterpolatedStringTextToken, "ddd");
}
N(SyntaxKind.InterpolatedStringEndToken);
}
EOF();
}
[Fact]
public void TestNestedAltInterpolatedVerbatimString_CSharp8()
{
UsingExpression("$@\"aaa{@$\"bbb\nccc\"}ddd\"", TestOptions.Regular8);
N(SyntaxKind.InterpolatedStringExpression);
{
N(SyntaxKind.InterpolatedVerbatimStringStartToken);
N(SyntaxKind.InterpolatedStringText);
{
N(SyntaxKind.InterpolatedStringTextToken, "aaa");
}
N(SyntaxKind.Interpolation);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.InterpolatedStringExpression);
{
N(SyntaxKind.InterpolatedVerbatimStringStartToken);
N(SyntaxKind.InterpolatedStringText);
{
N(SyntaxKind.InterpolatedStringTextToken, "bbb\nccc");
}
N(SyntaxKind.InterpolatedStringEndToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.InterpolatedStringText);
{
N(SyntaxKind.InterpolatedStringTextToken, "ddd");
}
N(SyntaxKind.InterpolatedStringEndToken);
}
EOF();
}
[Fact]
public void TestName()
{
var text = "goo";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.IdentifierName, expr.Kind());
Assert.False(((IdentifierNameSyntax)expr).Identifier.IsMissing);
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
}
[Fact]
public void TestParenthesizedExpression()
{
var text = "(goo)";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ParenthesizedExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
}
private void TestLiteralExpression(SyntaxKind kind)
{
var text = SyntaxFacts.GetText(kind);
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
var opKind = SyntaxFacts.GetLiteralExpression(kind);
Assert.Equal(opKind, expr.Kind());
Assert.Equal(0, expr.Errors().Length);
var us = (LiteralExpressionSyntax)expr;
Assert.NotEqual(default, us.Token);
Assert.Equal(kind, us.Token.Kind());
}
[Fact]
public void TestPrimaryExpressions()
{
TestLiteralExpression(SyntaxKind.NullKeyword);
TestLiteralExpression(SyntaxKind.TrueKeyword);
TestLiteralExpression(SyntaxKind.FalseKeyword);
TestLiteralExpression(SyntaxKind.ArgListKeyword);
}
private void TestInstanceExpression(SyntaxKind kind)
{
var text = SyntaxFacts.GetText(kind);
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
var opKind = SyntaxFacts.GetInstanceExpression(kind);
Assert.Equal(opKind, expr.Kind());
Assert.Equal(0, expr.Errors().Length);
SyntaxToken token;
switch (expr.Kind())
{
case SyntaxKind.ThisExpression:
token = ((ThisExpressionSyntax)expr).Token;
Assert.NotEqual(default, token);
Assert.Equal(kind, token.Kind());
break;
case SyntaxKind.BaseExpression:
token = ((BaseExpressionSyntax)expr).Token;
Assert.NotEqual(default, token);
Assert.Equal(kind, token.Kind());
break;
}
}
[Fact]
public void TestInstanceExpressions()
{
TestInstanceExpression(SyntaxKind.ThisKeyword);
TestInstanceExpression(SyntaxKind.BaseKeyword);
}
[Fact]
public void TestStringLiteralExpression()
{
var text = "\"stuff\"";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.StringLiteralExpression, expr.Kind());
Assert.Equal(0, expr.Errors().Length);
var us = (LiteralExpressionSyntax)expr;
Assert.NotEqual(default, us.Token);
Assert.Equal(SyntaxKind.StringLiteralToken, us.Token.Kind());
}
[WorkItem(540379, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540379")]
[Fact]
public void TestVerbatimLiteralExpression()
{
var text = "@\"\"\"stuff\"\"\"";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.StringLiteralExpression, expr.Kind());
Assert.Equal(0, expr.Errors().Length);
var us = (LiteralExpressionSyntax)expr;
Assert.NotEqual(default, us.Token);
Assert.Equal(SyntaxKind.StringLiteralToken, us.Token.Kind());
Assert.Equal("\"stuff\"", us.Token.ValueText);
}
[Fact]
public void TestCharacterLiteralExpression()
{
var text = "'c'";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.CharacterLiteralExpression, expr.Kind());
Assert.Equal(0, expr.Errors().Length);
var us = (LiteralExpressionSyntax)expr;
Assert.NotEqual(default, us.Token);
Assert.Equal(SyntaxKind.CharacterLiteralToken, us.Token.Kind());
}
[Fact]
public void TestNumericLiteralExpression()
{
var text = "0";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.NumericLiteralExpression, expr.Kind());
Assert.Equal(0, expr.Errors().Length);
var us = (LiteralExpressionSyntax)expr;
Assert.NotEqual(default, us.Token);
Assert.Equal(SyntaxKind.NumericLiteralToken, us.Token.Kind());
}
private void TestPrefixUnary(SyntaxKind kind)
{
var text = SyntaxFacts.GetText(kind) + "a";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
var opKind = SyntaxFacts.GetPrefixUnaryExpression(kind);
Assert.Equal(opKind, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var us = (PrefixUnaryExpressionSyntax)expr;
Assert.NotEqual(default, us.OperatorToken);
Assert.Equal(kind, us.OperatorToken.Kind());
Assert.NotNull(us.Operand);
Assert.Equal(SyntaxKind.IdentifierName, us.Operand.Kind());
Assert.Equal("a", us.Operand.ToString());
}
[Fact]
public void TestPrefixUnaryOperators()
{
TestPrefixUnary(SyntaxKind.PlusToken);
TestPrefixUnary(SyntaxKind.MinusToken);
TestPrefixUnary(SyntaxKind.TildeToken);
TestPrefixUnary(SyntaxKind.ExclamationToken);
TestPrefixUnary(SyntaxKind.PlusPlusToken);
TestPrefixUnary(SyntaxKind.MinusMinusToken);
TestPrefixUnary(SyntaxKind.AmpersandToken);
TestPrefixUnary(SyntaxKind.AsteriskToken);
}
private void TestPostfixUnary(SyntaxKind kind, ParseOptions options = null)
{
var text = "a" + SyntaxFacts.GetText(kind);
var expr = this.ParseExpression(text, options: options);
Assert.NotNull(expr);
var opKind = SyntaxFacts.GetPostfixUnaryExpression(kind);
Assert.Equal(opKind, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var us = (PostfixUnaryExpressionSyntax)expr;
Assert.NotEqual(default, us.OperatorToken);
Assert.Equal(kind, us.OperatorToken.Kind());
Assert.NotNull(us.Operand);
Assert.Equal(SyntaxKind.IdentifierName, us.Operand.Kind());
Assert.Equal("a", us.Operand.ToString());
}
[Fact]
public void TestPostfixUnaryOperators()
{
TestPostfixUnary(SyntaxKind.PlusPlusToken);
TestPostfixUnary(SyntaxKind.MinusMinusToken);
TestPostfixUnary(SyntaxKind.ExclamationToken, TestOptions.Regular8);
}
private void TestBinary(SyntaxKind kind)
{
var text = "(a) " + SyntaxFacts.GetText(kind) + " b";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
var opKind = SyntaxFacts.GetBinaryExpression(kind);
Assert.Equal(opKind, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var b = (BinaryExpressionSyntax)expr;
Assert.NotEqual(default, b.OperatorToken);
Assert.Equal(kind, b.OperatorToken.Kind());
Assert.NotNull(b.Left);
Assert.NotNull(b.Right);
Assert.Equal("(a)", b.Left.ToString());
Assert.Equal("b", b.Right.ToString());
}
[Fact]
public void TestBinaryOperators()
{
TestBinary(SyntaxKind.PlusToken);
TestBinary(SyntaxKind.MinusToken);
TestBinary(SyntaxKind.AsteriskToken);
TestBinary(SyntaxKind.SlashToken);
TestBinary(SyntaxKind.PercentToken);
TestBinary(SyntaxKind.EqualsEqualsToken);
TestBinary(SyntaxKind.ExclamationEqualsToken);
TestBinary(SyntaxKind.LessThanToken);
TestBinary(SyntaxKind.LessThanEqualsToken);
TestBinary(SyntaxKind.LessThanLessThanToken);
TestBinary(SyntaxKind.GreaterThanToken);
TestBinary(SyntaxKind.GreaterThanEqualsToken);
TestBinary(SyntaxKind.GreaterThanGreaterThanToken);
TestBinary(SyntaxKind.AmpersandToken);
TestBinary(SyntaxKind.AmpersandAmpersandToken);
TestBinary(SyntaxKind.BarToken);
TestBinary(SyntaxKind.BarBarToken);
TestBinary(SyntaxKind.CaretToken);
TestBinary(SyntaxKind.IsKeyword);
TestBinary(SyntaxKind.AsKeyword);
TestBinary(SyntaxKind.QuestionQuestionToken);
}
private void TestAssignment(SyntaxKind kind, ParseOptions options = null)
{
var text = "(a) " + SyntaxFacts.GetText(kind) + " b";
var expr = this.ParseExpression(text, options);
Assert.NotNull(expr);
var opKind = SyntaxFacts.GetAssignmentExpression(kind);
Assert.Equal(opKind, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var a = (AssignmentExpressionSyntax)expr;
Assert.NotEqual(default, a.OperatorToken);
Assert.Equal(kind, a.OperatorToken.Kind());
Assert.NotNull(a.Left);
Assert.NotNull(a.Right);
Assert.Equal("(a)", a.Left.ToString());
Assert.Equal("b", a.Right.ToString());
}
[Fact]
public void TestAssignmentOperators()
{
TestAssignment(SyntaxKind.PlusEqualsToken);
TestAssignment(SyntaxKind.MinusEqualsToken);
TestAssignment(SyntaxKind.AsteriskEqualsToken);
TestAssignment(SyntaxKind.SlashEqualsToken);
TestAssignment(SyntaxKind.PercentEqualsToken);
TestAssignment(SyntaxKind.EqualsToken);
TestAssignment(SyntaxKind.LessThanLessThanEqualsToken);
TestAssignment(SyntaxKind.GreaterThanGreaterThanEqualsToken);
TestAssignment(SyntaxKind.AmpersandEqualsToken);
TestAssignment(SyntaxKind.BarEqualsToken);
TestAssignment(SyntaxKind.CaretEqualsToken);
TestAssignment(SyntaxKind.QuestionQuestionEqualsToken, options: TestOptions.Regular8);
}
private void TestMemberAccess(SyntaxKind kind)
{
var text = "(a)" + SyntaxFacts.GetText(kind) + " b";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var e = (MemberAccessExpressionSyntax)expr;
Assert.NotEqual(default, e.OperatorToken);
Assert.Equal(kind, e.OperatorToken.Kind());
Assert.NotNull(e.Expression);
Assert.NotNull(e.Name);
Assert.Equal("(a)", e.Expression.ToString());
Assert.Equal("b", e.Name.ToString());
}
[Fact]
public void TestMemberAccessTokens()
{
TestMemberAccess(SyntaxKind.DotToken);
TestMemberAccess(SyntaxKind.MinusGreaterThanToken);
}
[Fact]
public void TestConditionalAccessNotVersion5()
{
var text = "a.b?.c.d?[1]?.e()?.f";
var expr = this.ParseExpression(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp5));
Assert.NotNull(expr);
Assert.Equal(text, expr.ToString());
Assert.Equal(1, expr.Errors().Length);
var e = (ConditionalAccessExpressionSyntax)expr;
Assert.Equal("a.b", e.Expression.ToString());
Assert.Equal(".c.d?[1]?.e()?.f", e.WhenNotNull.ToString());
}
[Fact]
public void TestConditionalAccess()
{
var text = "a.b?.c.d?[1]?.e()?.f";
var expr = this.ParseExpression(text, options: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.CSharp6));
Assert.NotNull(expr);
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var e = (ConditionalAccessExpressionSyntax)expr;
Assert.Equal("a.b", e.Expression.ToString());
var cons = e.WhenNotNull;
Assert.Equal(".c.d?[1]?.e()?.f", cons.ToString());
Assert.Equal(SyntaxKind.ConditionalAccessExpression, cons.Kind());
e = e.WhenNotNull as ConditionalAccessExpressionSyntax;
Assert.Equal(".c.d", e.Expression.ToString());
cons = e.WhenNotNull;
Assert.Equal("[1]?.e()?.f", cons.ToString());
Assert.Equal(SyntaxKind.ConditionalAccessExpression, cons.Kind());
e = e.WhenNotNull as ConditionalAccessExpressionSyntax;
Assert.Equal("[1]", e.Expression.ToString());
cons = e.WhenNotNull;
Assert.Equal(".e()?.f", cons.ToString());
Assert.Equal(SyntaxKind.ConditionalAccessExpression, cons.Kind());
e = e.WhenNotNull as ConditionalAccessExpressionSyntax;
Assert.Equal(".e()", e.Expression.ToString());
cons = e.WhenNotNull;
Assert.Equal(".f", cons.ToString());
Assert.Equal(SyntaxKind.MemberBindingExpression, cons.Kind());
}
private void TestFunctionKeyword(SyntaxKind kind, SyntaxToken keyword)
{
Assert.NotEqual(default, keyword);
Assert.Equal(kind, keyword.Kind());
}
private void TestParenthesizedArgument(SyntaxToken openParen, CSharpSyntaxNode arg, SyntaxToken closeParen)
{
Assert.NotEqual(default, openParen);
Assert.False(openParen.IsMissing);
Assert.NotEqual(default, closeParen);
Assert.False(closeParen.IsMissing);
Assert.Equal("a", arg.ToString());
}
private void TestSingleParamFunctionalOperator(SyntaxKind kind)
{
var text = SyntaxFacts.GetText(kind) + "(a)";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
var opKind = SyntaxFacts.GetPrimaryFunction(kind);
Assert.Equal(opKind, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
switch (opKind)
{
case SyntaxKind.MakeRefExpression:
var makeRefSyntax = (MakeRefExpressionSyntax)expr;
TestFunctionKeyword(kind, makeRefSyntax.Keyword);
TestParenthesizedArgument(makeRefSyntax.OpenParenToken, makeRefSyntax.Expression, makeRefSyntax.CloseParenToken);
break;
case SyntaxKind.RefTypeExpression:
var refTypeSyntax = (RefTypeExpressionSyntax)expr;
TestFunctionKeyword(kind, refTypeSyntax.Keyword);
TestParenthesizedArgument(refTypeSyntax.OpenParenToken, refTypeSyntax.Expression, refTypeSyntax.CloseParenToken);
break;
case SyntaxKind.CheckedExpression:
case SyntaxKind.UncheckedExpression:
var checkedSyntax = (CheckedExpressionSyntax)expr;
TestFunctionKeyword(kind, checkedSyntax.Keyword);
TestParenthesizedArgument(checkedSyntax.OpenParenToken, checkedSyntax.Expression, checkedSyntax.CloseParenToken);
break;
case SyntaxKind.TypeOfExpression:
var typeOfSyntax = (TypeOfExpressionSyntax)expr;
TestFunctionKeyword(kind, typeOfSyntax.Keyword);
TestParenthesizedArgument(typeOfSyntax.OpenParenToken, typeOfSyntax.Type, typeOfSyntax.CloseParenToken);
break;
case SyntaxKind.SizeOfExpression:
var sizeOfSyntax = (SizeOfExpressionSyntax)expr;
TestFunctionKeyword(kind, sizeOfSyntax.Keyword);
TestParenthesizedArgument(sizeOfSyntax.OpenParenToken, sizeOfSyntax.Type, sizeOfSyntax.CloseParenToken);
break;
case SyntaxKind.DefaultExpression:
var defaultSyntax = (DefaultExpressionSyntax)expr;
TestFunctionKeyword(kind, defaultSyntax.Keyword);
TestParenthesizedArgument(defaultSyntax.OpenParenToken, defaultSyntax.Type, defaultSyntax.CloseParenToken);
break;
}
}
[Fact]
public void TestFunctionOperators()
{
TestSingleParamFunctionalOperator(SyntaxKind.MakeRefKeyword);
TestSingleParamFunctionalOperator(SyntaxKind.RefTypeKeyword);
TestSingleParamFunctionalOperator(SyntaxKind.CheckedKeyword);
TestSingleParamFunctionalOperator(SyntaxKind.UncheckedKeyword);
TestSingleParamFunctionalOperator(SyntaxKind.SizeOfKeyword);
TestSingleParamFunctionalOperator(SyntaxKind.TypeOfKeyword);
TestSingleParamFunctionalOperator(SyntaxKind.DefaultKeyword);
}
[Fact]
public void TestRefValue()
{
var text = SyntaxFacts.GetText(SyntaxKind.RefValueKeyword) + "(a, b)";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.RefValueExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var fs = (RefValueExpressionSyntax)expr;
Assert.NotEqual(default, fs.Keyword);
Assert.Equal(SyntaxKind.RefValueKeyword, fs.Keyword.Kind());
Assert.NotEqual(default, fs.OpenParenToken);
Assert.False(fs.OpenParenToken.IsMissing);
Assert.NotEqual(default, fs.CloseParenToken);
Assert.False(fs.CloseParenToken.IsMissing);
Assert.Equal("a", fs.Expression.ToString());
Assert.Equal("b", fs.Type.ToString());
}
[Fact]
public void TestConditional()
{
var text = "a ? b : c";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ConditionalExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var ts = (ConditionalExpressionSyntax)expr;
Assert.NotEqual(default, ts.QuestionToken);
Assert.NotEqual(default, ts.ColonToken);
Assert.Equal(SyntaxKind.QuestionToken, ts.QuestionToken.Kind());
Assert.Equal(SyntaxKind.ColonToken, ts.ColonToken.Kind());
Assert.Equal("a", ts.Condition.ToString());
Assert.Equal("b", ts.WhenTrue.ToString());
Assert.Equal("c", ts.WhenFalse.ToString());
}
[Fact]
public void TestConditional02()
{
// ensure that ?: has lower precedence than assignment.
var text = "a ? b=c : d=e";
var expr = this.ParseExpression(text);
Assert.Equal(SyntaxKind.ConditionalExpression, expr.Kind());
Assert.False(expr.HasErrors);
}
[Fact]
public void TestCast()
{
var text = "(a) b";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.CastExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var cs = (CastExpressionSyntax)expr;
Assert.NotEqual(default, cs.OpenParenToken);
Assert.NotEqual(default, cs.CloseParenToken);
Assert.False(cs.OpenParenToken.IsMissing);
Assert.False(cs.CloseParenToken.IsMissing);
Assert.NotNull(cs.Type);
Assert.NotNull(cs.Expression);
Assert.Equal("a", cs.Type.ToString());
Assert.Equal("b", cs.Expression.ToString());
}
[Fact]
public void TestCall()
{
var text = "a(b)";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.InvocationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var cs = (InvocationExpressionSyntax)expr;
Assert.NotEqual(default, cs.ArgumentList.OpenParenToken);
Assert.NotEqual(default, cs.ArgumentList.CloseParenToken);
Assert.False(cs.ArgumentList.OpenParenToken.IsMissing);
Assert.False(cs.ArgumentList.CloseParenToken.IsMissing);
Assert.NotNull(cs.Expression);
Assert.Equal(1, cs.ArgumentList.Arguments.Count);
Assert.Equal("a", cs.Expression.ToString());
Assert.Equal("b", cs.ArgumentList.Arguments[0].ToString());
}
[Fact]
public void TestCallWithRef()
{
var text = "a(ref b)";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.InvocationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var cs = (InvocationExpressionSyntax)expr;
Assert.NotEqual(default, cs.ArgumentList.OpenParenToken);
Assert.NotEqual(default, cs.ArgumentList.CloseParenToken);
Assert.False(cs.ArgumentList.OpenParenToken.IsMissing);
Assert.False(cs.ArgumentList.CloseParenToken.IsMissing);
Assert.NotNull(cs.Expression);
Assert.Equal(1, cs.ArgumentList.Arguments.Count);
Assert.Equal("a", cs.Expression.ToString());
Assert.Equal("ref b", cs.ArgumentList.Arguments[0].ToString());
Assert.NotEqual(default, cs.ArgumentList.Arguments[0].RefOrOutKeyword);
Assert.Equal(SyntaxKind.RefKeyword, cs.ArgumentList.Arguments[0].RefOrOutKeyword.Kind());
Assert.NotNull(cs.ArgumentList.Arguments[0].Expression);
Assert.Equal("b", cs.ArgumentList.Arguments[0].Expression.ToString());
}
[Fact]
public void TestCallWithOut()
{
var text = "a(out b)";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.InvocationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var cs = (InvocationExpressionSyntax)expr;
Assert.NotEqual(default, cs.ArgumentList.OpenParenToken);
Assert.NotEqual(default, cs.ArgumentList.CloseParenToken);
Assert.False(cs.ArgumentList.OpenParenToken.IsMissing);
Assert.False(cs.ArgumentList.CloseParenToken.IsMissing);
Assert.NotNull(cs.Expression);
Assert.Equal(1, cs.ArgumentList.Arguments.Count);
Assert.Equal("a", cs.Expression.ToString());
Assert.Equal("out b", cs.ArgumentList.Arguments[0].ToString());
Assert.NotEqual(default, cs.ArgumentList.Arguments[0].RefOrOutKeyword);
Assert.Equal(SyntaxKind.OutKeyword, cs.ArgumentList.Arguments[0].RefOrOutKeyword.Kind());
Assert.NotNull(cs.ArgumentList.Arguments[0].Expression);
Assert.Equal("b", cs.ArgumentList.Arguments[0].Expression.ToString());
}
[Fact]
public void TestCallWithNamedArgument()
{
var text = "a(B: b)";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.InvocationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var cs = (InvocationExpressionSyntax)expr;
Assert.NotEqual(default, cs.ArgumentList.OpenParenToken);
Assert.NotEqual(default, cs.ArgumentList.CloseParenToken);
Assert.False(cs.ArgumentList.OpenParenToken.IsMissing);
Assert.False(cs.ArgumentList.CloseParenToken.IsMissing);
Assert.NotNull(cs.Expression);
Assert.Equal(1, cs.ArgumentList.Arguments.Count);
Assert.Equal("a", cs.Expression.ToString());
Assert.Equal("B: b", cs.ArgumentList.Arguments[0].ToString());
Assert.NotNull(cs.ArgumentList.Arguments[0].NameColon);
Assert.Equal("B", cs.ArgumentList.Arguments[0].NameColon.Name.ToString());
Assert.NotEqual(default, cs.ArgumentList.Arguments[0].NameColon.ColonToken);
Assert.Equal("b", cs.ArgumentList.Arguments[0].Expression.ToString());
}
[Fact]
public void TestIndex()
{
var text = "a[b]";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ElementAccessExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var ea = (ElementAccessExpressionSyntax)expr;
Assert.NotEqual(default, ea.ArgumentList.OpenBracketToken);
Assert.NotEqual(default, ea.ArgumentList.CloseBracketToken);
Assert.False(ea.ArgumentList.OpenBracketToken.IsMissing);
Assert.False(ea.ArgumentList.CloseBracketToken.IsMissing);
Assert.NotNull(ea.Expression);
Assert.Equal(1, ea.ArgumentList.Arguments.Count);
Assert.Equal("a", ea.Expression.ToString());
Assert.Equal("b", ea.ArgumentList.Arguments[0].ToString());
}
[Fact]
public void TestIndexWithRef()
{
var text = "a[ref b]";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ElementAccessExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var ea = (ElementAccessExpressionSyntax)expr;
Assert.NotEqual(default, ea.ArgumentList.OpenBracketToken);
Assert.NotEqual(default, ea.ArgumentList.CloseBracketToken);
Assert.False(ea.ArgumentList.OpenBracketToken.IsMissing);
Assert.False(ea.ArgumentList.CloseBracketToken.IsMissing);
Assert.NotNull(ea.Expression);
Assert.Equal(1, ea.ArgumentList.Arguments.Count);
Assert.Equal("a", ea.Expression.ToString());
Assert.Equal("ref b", ea.ArgumentList.Arguments[0].ToString());
Assert.NotEqual(default, ea.ArgumentList.Arguments[0].RefOrOutKeyword);
Assert.Equal(SyntaxKind.RefKeyword, ea.ArgumentList.Arguments[0].RefOrOutKeyword.Kind());
Assert.NotNull(ea.ArgumentList.Arguments[0].Expression);
Assert.Equal("b", ea.ArgumentList.Arguments[0].Expression.ToString());
}
[Fact]
public void TestIndexWithOut()
{
var text = "a[out b]";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ElementAccessExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var ea = (ElementAccessExpressionSyntax)expr;
Assert.NotEqual(default, ea.ArgumentList.OpenBracketToken);
Assert.NotEqual(default, ea.ArgumentList.CloseBracketToken);
Assert.False(ea.ArgumentList.OpenBracketToken.IsMissing);
Assert.False(ea.ArgumentList.CloseBracketToken.IsMissing);
Assert.NotNull(ea.Expression);
Assert.Equal(1, ea.ArgumentList.Arguments.Count);
Assert.Equal("a", ea.Expression.ToString());
Assert.Equal("out b", ea.ArgumentList.Arguments[0].ToString());
Assert.NotEqual(default, ea.ArgumentList.Arguments[0].RefOrOutKeyword);
Assert.Equal(SyntaxKind.OutKeyword, ea.ArgumentList.Arguments[0].RefOrOutKeyword.Kind());
Assert.NotNull(ea.ArgumentList.Arguments[0].Expression);
Assert.Equal("b", ea.ArgumentList.Arguments[0].Expression.ToString());
}
[Fact]
public void TestIndexWithNamedArgument()
{
var text = "a[B: b]";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ElementAccessExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var ea = (ElementAccessExpressionSyntax)expr;
Assert.NotEqual(default, ea.ArgumentList.OpenBracketToken);
Assert.NotEqual(default, ea.ArgumentList.CloseBracketToken);
Assert.False(ea.ArgumentList.OpenBracketToken.IsMissing);
Assert.False(ea.ArgumentList.CloseBracketToken.IsMissing);
Assert.NotNull(ea.Expression);
Assert.Equal(1, ea.ArgumentList.Arguments.Count);
Assert.Equal("a", ea.Expression.ToString());
Assert.Equal("B: b", ea.ArgumentList.Arguments[0].ToString());
}
[Fact]
public void TestNew()
{
var text = "new a()";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ObjectCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var oc = (ObjectCreationExpressionSyntax)expr;
Assert.NotNull(oc.ArgumentList);
Assert.NotEqual(default, oc.ArgumentList.OpenParenToken);
Assert.NotEqual(default, oc.ArgumentList.CloseParenToken);
Assert.False(oc.ArgumentList.OpenParenToken.IsMissing);
Assert.False(oc.ArgumentList.CloseParenToken.IsMissing);
Assert.Equal(0, oc.ArgumentList.Arguments.Count);
Assert.NotNull(oc.Type);
Assert.Equal("a", oc.Type.ToString());
Assert.Null(oc.Initializer);
}
[Fact]
public void TestNewWithArgument()
{
var text = "new a(b)";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ObjectCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var oc = (ObjectCreationExpressionSyntax)expr;
Assert.NotNull(oc.ArgumentList);
Assert.NotEqual(default, oc.ArgumentList.OpenParenToken);
Assert.NotEqual(default, oc.ArgumentList.CloseParenToken);
Assert.False(oc.ArgumentList.OpenParenToken.IsMissing);
Assert.False(oc.ArgumentList.CloseParenToken.IsMissing);
Assert.Equal(1, oc.ArgumentList.Arguments.Count);
Assert.Equal("b", oc.ArgumentList.Arguments[0].ToString());
Assert.NotNull(oc.Type);
Assert.Equal("a", oc.Type.ToString());
Assert.Null(oc.Initializer);
}
[Fact]
public void TestNewWithNamedArgument()
{
var text = "new a(B: b)";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ObjectCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var oc = (ObjectCreationExpressionSyntax)expr;
Assert.NotNull(oc.ArgumentList);
Assert.NotEqual(default, oc.ArgumentList.OpenParenToken);
Assert.NotEqual(default, oc.ArgumentList.CloseParenToken);
Assert.False(oc.ArgumentList.OpenParenToken.IsMissing);
Assert.False(oc.ArgumentList.CloseParenToken.IsMissing);
Assert.Equal(1, oc.ArgumentList.Arguments.Count);
Assert.Equal("B: b", oc.ArgumentList.Arguments[0].ToString());
Assert.NotNull(oc.Type);
Assert.Equal("a", oc.Type.ToString());
Assert.Null(oc.Initializer);
}
[Fact]
public void TestNewWithEmptyInitializer()
{
var text = "new a() { }";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ObjectCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var oc = (ObjectCreationExpressionSyntax)expr;
Assert.NotNull(oc.ArgumentList);
Assert.NotEqual(default, oc.ArgumentList.OpenParenToken);
Assert.NotEqual(default, oc.ArgumentList.CloseParenToken);
Assert.False(oc.ArgumentList.OpenParenToken.IsMissing);
Assert.False(oc.ArgumentList.CloseParenToken.IsMissing);
Assert.Equal(0, oc.ArgumentList.Arguments.Count);
Assert.NotNull(oc.Type);
Assert.Equal("a", oc.Type.ToString());
Assert.NotNull(oc.Initializer);
Assert.NotEqual(default, oc.Initializer.OpenBraceToken);
Assert.NotEqual(default, oc.Initializer.CloseBraceToken);
Assert.False(oc.Initializer.OpenBraceToken.IsMissing);
Assert.False(oc.Initializer.CloseBraceToken.IsMissing);
Assert.Equal(0, oc.Initializer.Expressions.Count);
}
[Fact]
public void TestNewWithNoArgumentsAndEmptyInitializer()
{
var text = "new a { }";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ObjectCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var oc = (ObjectCreationExpressionSyntax)expr;
Assert.Null(oc.ArgumentList);
Assert.NotNull(oc.Type);
Assert.Equal("a", oc.Type.ToString());
Assert.NotNull(oc.Initializer);
Assert.NotEqual(default, oc.Initializer.OpenBraceToken);
Assert.NotEqual(default, oc.Initializer.CloseBraceToken);
Assert.False(oc.Initializer.OpenBraceToken.IsMissing);
Assert.False(oc.Initializer.CloseBraceToken.IsMissing);
Assert.Equal(0, oc.Initializer.Expressions.Count);
}
[Fact]
public void TestNewWithNoArgumentsAndInitializer()
{
var text = "new a { b }";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ObjectCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var oc = (ObjectCreationExpressionSyntax)expr;
Assert.Null(oc.ArgumentList);
Assert.NotNull(oc.Type);
Assert.Equal("a", oc.Type.ToString());
Assert.NotNull(oc.Initializer);
Assert.NotEqual(default, oc.Initializer.OpenBraceToken);
Assert.NotEqual(default, oc.Initializer.CloseBraceToken);
Assert.False(oc.Initializer.OpenBraceToken.IsMissing);
Assert.False(oc.Initializer.CloseBraceToken.IsMissing);
Assert.Equal(1, oc.Initializer.Expressions.Count);
Assert.Equal("b", oc.Initializer.Expressions[0].ToString());
}
[Fact]
public void TestNewWithNoArgumentsAndInitializers()
{
var text = "new a { b, c, d }";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ObjectCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var oc = (ObjectCreationExpressionSyntax)expr;
Assert.Null(oc.ArgumentList);
Assert.NotNull(oc.Type);
Assert.Equal("a", oc.Type.ToString());
Assert.NotNull(oc.Initializer);
Assert.NotEqual(default, oc.Initializer.OpenBraceToken);
Assert.NotEqual(default, oc.Initializer.CloseBraceToken);
Assert.False(oc.Initializer.OpenBraceToken.IsMissing);
Assert.False(oc.Initializer.CloseBraceToken.IsMissing);
Assert.Equal(3, oc.Initializer.Expressions.Count);
Assert.Equal("b", oc.Initializer.Expressions[0].ToString());
Assert.Equal("c", oc.Initializer.Expressions[1].ToString());
Assert.Equal("d", oc.Initializer.Expressions[2].ToString());
}
[Fact]
public void TestNewWithNoArgumentsAndAssignmentInitializer()
{
var text = "new a { B = b }";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ObjectCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var oc = (ObjectCreationExpressionSyntax)expr;
Assert.Null(oc.ArgumentList);
Assert.NotNull(oc.Type);
Assert.Equal("a", oc.Type.ToString());
Assert.NotNull(oc.Initializer);
Assert.NotEqual(default, oc.Initializer.OpenBraceToken);
Assert.NotEqual(default, oc.Initializer.CloseBraceToken);
Assert.False(oc.Initializer.OpenBraceToken.IsMissing);
Assert.False(oc.Initializer.CloseBraceToken.IsMissing);
Assert.Equal(1, oc.Initializer.Expressions.Count);
Assert.Equal("B = b", oc.Initializer.Expressions[0].ToString());
}
[Fact]
public void TestNewWithNoArgumentsAndNestedAssignmentInitializer()
{
var text = "new a { B = { X = x } }";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ObjectCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var oc = (ObjectCreationExpressionSyntax)expr;
Assert.Null(oc.ArgumentList);
Assert.NotNull(oc.Type);
Assert.Equal("a", oc.Type.ToString());
Assert.NotNull(oc.Initializer);
Assert.NotEqual(default, oc.Initializer.OpenBraceToken);
Assert.NotEqual(default, oc.Initializer.CloseBraceToken);
Assert.False(oc.Initializer.OpenBraceToken.IsMissing);
Assert.False(oc.Initializer.CloseBraceToken.IsMissing);
Assert.Equal(1, oc.Initializer.Expressions.Count);
Assert.Equal("B = { X = x }", oc.Initializer.Expressions[0].ToString());
Assert.Equal(SyntaxKind.SimpleAssignmentExpression, oc.Initializer.Expressions[0].Kind());
var b = (AssignmentExpressionSyntax)oc.Initializer.Expressions[0];
Assert.Equal("B", b.Left.ToString());
Assert.Equal(SyntaxKind.ObjectInitializerExpression, b.Right.Kind());
}
[Fact]
public void TestNewArray()
{
var text = "new a[1]";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ArrayCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var ac = (ArrayCreationExpressionSyntax)expr;
Assert.NotNull(ac.Type);
Assert.Equal("a[1]", ac.Type.ToString());
Assert.Null(ac.Initializer);
}
[Fact]
public void TestNewArrayWithInitializer()
{
var text = "new a[] {b}";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ArrayCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var ac = (ArrayCreationExpressionSyntax)expr;
Assert.NotNull(ac.Type);
Assert.Equal("a[]", ac.Type.ToString());
Assert.NotNull(ac.Initializer);
Assert.NotEqual(default, ac.Initializer.OpenBraceToken);
Assert.NotEqual(default, ac.Initializer.CloseBraceToken);
Assert.False(ac.Initializer.OpenBraceToken.IsMissing);
Assert.False(ac.Initializer.CloseBraceToken.IsMissing);
Assert.Equal(1, ac.Initializer.Expressions.Count);
Assert.Equal("b", ac.Initializer.Expressions[0].ToString());
}
[Fact]
public void TestNewArrayWithInitializers()
{
var text = "new a[] {b, c, d}";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ArrayCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var ac = (ArrayCreationExpressionSyntax)expr;
Assert.NotNull(ac.Type);
Assert.Equal("a[]", ac.Type.ToString());
Assert.NotNull(ac.Initializer);
Assert.NotEqual(default, ac.Initializer.OpenBraceToken);
Assert.NotEqual(default, ac.Initializer.CloseBraceToken);
Assert.False(ac.Initializer.OpenBraceToken.IsMissing);
Assert.False(ac.Initializer.CloseBraceToken.IsMissing);
Assert.Equal(3, ac.Initializer.Expressions.Count);
Assert.Equal("b", ac.Initializer.Expressions[0].ToString());
Assert.Equal("c", ac.Initializer.Expressions[1].ToString());
Assert.Equal("d", ac.Initializer.Expressions[2].ToString());
}
[Fact]
public void TestNewMultiDimensionalArrayWithInitializer()
{
var text = "new a[][,][,,] {b}";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ArrayCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var ac = (ArrayCreationExpressionSyntax)expr;
Assert.NotNull(ac.Type);
Assert.Equal("a[][,][,,]", ac.Type.ToString());
Assert.NotNull(ac.Initializer);
Assert.NotEqual(default, ac.Initializer.OpenBraceToken);
Assert.NotEqual(default, ac.Initializer.CloseBraceToken);
Assert.False(ac.Initializer.OpenBraceToken.IsMissing);
Assert.False(ac.Initializer.CloseBraceToken.IsMissing);
Assert.Equal(1, ac.Initializer.Expressions.Count);
Assert.Equal("b", ac.Initializer.Expressions[0].ToString());
}
[Fact]
public void TestImplicitArrayCreation()
{
var text = "new [] {b}";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ImplicitArrayCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var ac = (ImplicitArrayCreationExpressionSyntax)expr;
Assert.NotNull(ac.Initializer);
Assert.NotEqual(default, ac.Initializer.OpenBraceToken);
Assert.NotEqual(default, ac.Initializer.CloseBraceToken);
Assert.False(ac.Initializer.OpenBraceToken.IsMissing);
Assert.False(ac.Initializer.CloseBraceToken.IsMissing);
Assert.Equal(1, ac.Initializer.Expressions.Count);
Assert.Equal("b", ac.Initializer.Expressions[0].ToString());
}
[Fact]
public void TestAnonymousObjectCreation()
{
var text = "new {a, b}";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.AnonymousObjectCreationExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var ac = (AnonymousObjectCreationExpressionSyntax)expr;
Assert.NotEqual(default, ac.NewKeyword);
Assert.NotEqual(default, ac.OpenBraceToken);
Assert.NotEqual(default, ac.CloseBraceToken);
Assert.False(ac.OpenBraceToken.IsMissing);
Assert.False(ac.CloseBraceToken.IsMissing);
Assert.Equal(2, ac.Initializers.Count);
Assert.Equal("a", ac.Initializers[0].ToString());
Assert.Equal("b", ac.Initializers[1].ToString());
}
[Fact]
public void TestAnonymousMethod()
{
var text = "delegate (int a) { }";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.AnonymousMethodExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var am = (AnonymousMethodExpressionSyntax)expr;
Assert.NotEqual(default, am.DelegateKeyword);
Assert.False(am.DelegateKeyword.IsMissing);
Assert.NotNull(am.ParameterList);
Assert.NotEqual(default, am.ParameterList.OpenParenToken);
Assert.NotEqual(default, am.ParameterList.CloseParenToken);
Assert.False(am.ParameterList.OpenParenToken.IsMissing);
Assert.False(am.ParameterList.CloseParenToken.IsMissing);
Assert.Equal(1, am.ParameterList.Parameters.Count);
Assert.Equal("int a", am.ParameterList.Parameters[0].ToString());
Assert.NotNull(am.Block);
Assert.NotEqual(default, am.Block.OpenBraceToken);
Assert.NotEqual(default, am.Block.CloseBraceToken);
Assert.False(am.Block.OpenBraceToken.IsMissing);
Assert.False(am.Block.CloseBraceToken.IsMissing);
Assert.Equal(0, am.Block.Statements.Count);
}
[Fact]
public void TestAnonymousMethodWithNoArguments()
{
var text = "delegate () { }";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.AnonymousMethodExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var am = (AnonymousMethodExpressionSyntax)expr;
Assert.NotEqual(default, am.DelegateKeyword);
Assert.False(am.DelegateKeyword.IsMissing);
Assert.NotNull(am.ParameterList);
Assert.NotEqual(default, am.ParameterList.OpenParenToken);
Assert.NotEqual(default, am.ParameterList.CloseParenToken);
Assert.False(am.ParameterList.OpenParenToken.IsMissing);
Assert.False(am.ParameterList.CloseParenToken.IsMissing);
Assert.Equal(0, am.ParameterList.Parameters.Count);
Assert.NotNull(am.Block);
Assert.NotEqual(default, am.Block.OpenBraceToken);
Assert.NotEqual(default, am.Block.CloseBraceToken);
Assert.False(am.Block.OpenBraceToken.IsMissing);
Assert.False(am.Block.CloseBraceToken.IsMissing);
Assert.Equal(0, am.Block.Statements.Count);
}
[Fact]
public void TestAnonymousMethodWithNoArgumentList()
{
var text = "delegate { }";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.AnonymousMethodExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var am = (AnonymousMethodExpressionSyntax)expr;
Assert.NotEqual(default, am.DelegateKeyword);
Assert.False(am.DelegateKeyword.IsMissing);
Assert.Null(am.ParameterList);
Assert.NotNull(am.Block);
Assert.NotEqual(default, am.Block.OpenBraceToken);
Assert.NotEqual(default, am.Block.CloseBraceToken);
Assert.False(am.Block.OpenBraceToken.IsMissing);
Assert.False(am.Block.CloseBraceToken.IsMissing);
Assert.Equal(0, am.Block.Statements.Count);
}
[Fact]
public void TestSimpleLambda()
{
var text = "a => b";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.SimpleLambdaExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var lambda = (SimpleLambdaExpressionSyntax)expr;
Assert.NotEqual(default, lambda.Parameter.Identifier);
Assert.False(lambda.Parameter.Identifier.IsMissing);
Assert.Equal("a", lambda.Parameter.Identifier.ToString());
Assert.NotNull(lambda.Body);
Assert.Equal("b", lambda.Body.ToString());
}
[Fact]
public void TestSimpleLambdaWithRefReturn()
{
var text = "a => ref b";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.SimpleLambdaExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var lambda = (SimpleLambdaExpressionSyntax)expr;
Assert.NotEqual(default, lambda.Parameter.Identifier);
Assert.False(lambda.Parameter.Identifier.IsMissing);
Assert.Equal("a", lambda.Parameter.Identifier.ToString());
Assert.Equal(SyntaxKind.RefExpression, lambda.Body.Kind());
Assert.Equal("ref b", lambda.Body.ToString());
}
[Fact]
public void TestSimpleLambdaWithBlock()
{
var text = "a => { }";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.SimpleLambdaExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var lambda = (SimpleLambdaExpressionSyntax)expr;
Assert.NotEqual(default, lambda.Parameter.Identifier);
Assert.False(lambda.Parameter.Identifier.IsMissing);
Assert.Equal("a", lambda.Parameter.Identifier.ToString());
Assert.NotNull(lambda.Body);
Assert.Equal(SyntaxKind.Block, lambda.Body.Kind());
var b = (BlockSyntax)lambda.Body;
Assert.Equal("{ }", lambda.Body.ToString());
}
[Fact]
public void TestLambdaWithNoParameters()
{
var text = "() => b";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ParenthesizedLambdaExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var lambda = (ParenthesizedLambdaExpressionSyntax)expr;
Assert.NotEqual(default, lambda.ParameterList.OpenParenToken);
Assert.NotEqual(default, lambda.ParameterList.CloseParenToken);
Assert.False(lambda.ParameterList.OpenParenToken.IsMissing);
Assert.False(lambda.ParameterList.CloseParenToken.IsMissing);
Assert.Equal(0, lambda.ParameterList.Parameters.Count);
Assert.NotNull(lambda.Body);
Assert.Equal("b", lambda.Body.ToString());
}
[Fact]
public void TestLambdaWithNoParametersAndRefReturn()
{
var text = "() => ref b";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ParenthesizedLambdaExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var lambda = (ParenthesizedLambdaExpressionSyntax)expr;
Assert.NotEqual(default, lambda.ParameterList.OpenParenToken);
Assert.NotEqual(default, lambda.ParameterList.CloseParenToken);
Assert.False(lambda.ParameterList.OpenParenToken.IsMissing);
Assert.False(lambda.ParameterList.CloseParenToken.IsMissing);
Assert.Equal(0, lambda.ParameterList.Parameters.Count);
Assert.Equal(SyntaxKind.RefExpression, lambda.Body.Kind());
Assert.Equal("ref b", lambda.Body.ToString());
}
[Fact]
public void TestLambdaWithNoParametersAndBlock()
{
var text = "() => { }";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ParenthesizedLambdaExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var lambda = (ParenthesizedLambdaExpressionSyntax)expr;
Assert.NotEqual(default, lambda.ParameterList.OpenParenToken);
Assert.NotEqual(default, lambda.ParameterList.CloseParenToken);
Assert.False(lambda.ParameterList.OpenParenToken.IsMissing);
Assert.False(lambda.ParameterList.CloseParenToken.IsMissing);
Assert.Equal(0, lambda.ParameterList.Parameters.Count);
Assert.NotNull(lambda.Body);
Assert.Equal(SyntaxKind.Block, lambda.Body.Kind());
var b = (BlockSyntax)lambda.Body;
Assert.Equal("{ }", lambda.Body.ToString());
}
[Fact]
public void TestLambdaWithOneParameter()
{
var text = "(a) => b";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ParenthesizedLambdaExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var lambda = (ParenthesizedLambdaExpressionSyntax)expr;
Assert.NotEqual(default, lambda.ParameterList.OpenParenToken);
Assert.NotEqual(default, lambda.ParameterList.CloseParenToken);
Assert.False(lambda.ParameterList.OpenParenToken.IsMissing);
Assert.False(lambda.ParameterList.CloseParenToken.IsMissing);
Assert.Equal(1, lambda.ParameterList.Parameters.Count);
Assert.Equal(SyntaxKind.Parameter, lambda.ParameterList.Parameters[0].Kind());
var ps = (ParameterSyntax)lambda.ParameterList.Parameters[0];
Assert.Null(ps.Type);
Assert.Equal("a", ps.Identifier.ToString());
Assert.NotNull(lambda.Body);
Assert.Equal("b", lambda.Body.ToString());
}
[Fact]
public void TestLambdaWithTwoParameters()
{
var text = "(a, a2) => b";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ParenthesizedLambdaExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var lambda = (ParenthesizedLambdaExpressionSyntax)expr;
Assert.NotEqual(default, lambda.ParameterList.OpenParenToken);
Assert.NotEqual(default, lambda.ParameterList.CloseParenToken);
Assert.False(lambda.ParameterList.OpenParenToken.IsMissing);
Assert.False(lambda.ParameterList.CloseParenToken.IsMissing);
Assert.Equal(2, lambda.ParameterList.Parameters.Count);
Assert.Equal(SyntaxKind.Parameter, lambda.ParameterList.Parameters[0].Kind());
var ps = (ParameterSyntax)lambda.ParameterList.Parameters[0];
Assert.Null(ps.Type);
Assert.Equal("a", ps.Identifier.ToString());
var ps2 = (ParameterSyntax)lambda.ParameterList.Parameters[1];
Assert.Null(ps2.Type);
Assert.Equal("a2", ps2.Identifier.ToString());
Assert.NotNull(lambda.Body);
Assert.Equal("b", lambda.Body.ToString());
}
[Fact]
public void TestLambdaWithOneTypedParameter()
{
var text = "(T a) => b";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ParenthesizedLambdaExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var lambda = (ParenthesizedLambdaExpressionSyntax)expr;
Assert.NotEqual(default, lambda.ParameterList.OpenParenToken);
Assert.NotEqual(default, lambda.ParameterList.CloseParenToken);
Assert.False(lambda.ParameterList.OpenParenToken.IsMissing);
Assert.False(lambda.ParameterList.CloseParenToken.IsMissing);
Assert.Equal(1, lambda.ParameterList.Parameters.Count);
Assert.Equal(SyntaxKind.Parameter, lambda.ParameterList.Parameters[0].Kind());
var ps = (ParameterSyntax)lambda.ParameterList.Parameters[0];
Assert.NotNull(ps.Type);
Assert.Equal("T", ps.Type.ToString());
Assert.Equal("a", ps.Identifier.ToString());
Assert.NotNull(lambda.Body);
Assert.Equal("b", lambda.Body.ToString());
}
[Fact]
public void TestLambdaWithOneRefParameter()
{
var text = "(ref T a) => b";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ParenthesizedLambdaExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var lambda = (ParenthesizedLambdaExpressionSyntax)expr;
Assert.NotEqual(default, lambda.ParameterList.OpenParenToken);
Assert.NotEqual(default, lambda.ParameterList.CloseParenToken);
Assert.False(lambda.ParameterList.OpenParenToken.IsMissing);
Assert.False(lambda.ParameterList.CloseParenToken.IsMissing);
Assert.Equal(1, lambda.ParameterList.Parameters.Count);
Assert.Equal(SyntaxKind.Parameter, lambda.ParameterList.Parameters[0].Kind());
var ps = (ParameterSyntax)lambda.ParameterList.Parameters[0];
Assert.NotNull(ps.Type);
Assert.Equal("T", ps.Type.ToString());
Assert.Equal("a", ps.Identifier.ToString());
Assert.Equal(1, ps.Modifiers.Count);
Assert.Equal(SyntaxKind.RefKeyword, ps.Modifiers[0].Kind());
Assert.NotNull(lambda.Body);
Assert.Equal("b", lambda.Body.ToString());
}
[Fact]
public void TestTupleWithTwoArguments()
{
var text = "(a, a2)";
var expr = this.ParseExpression(text, options: TestOptions.Regular);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.TupleExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var tuple = (TupleExpressionSyntax)expr;
Assert.NotEqual(default, tuple.OpenParenToken);
Assert.NotEqual(default, tuple.CloseParenToken);
Assert.False(tuple.OpenParenToken.IsMissing);
Assert.False(tuple.CloseParenToken.IsMissing);
Assert.Equal(2, tuple.Arguments.Count);
Assert.Equal(SyntaxKind.IdentifierName, tuple.Arguments[0].Expression.Kind());
Assert.Null(tuple.Arguments[1].NameColon);
}
[Fact]
public void TestTupleWithTwoNamedArguments()
{
var text = "(arg1: (a, a2), arg2: a2)";
var expr = this.ParseExpression(text, options: TestOptions.Regular);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.TupleExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var tuple = (TupleExpressionSyntax)expr;
Assert.NotEqual(default, tuple.OpenParenToken);
Assert.NotEqual(default, tuple.CloseParenToken);
Assert.False(tuple.OpenParenToken.IsMissing);
Assert.False(tuple.CloseParenToken.IsMissing);
Assert.Equal(2, tuple.Arguments.Count);
Assert.Equal(SyntaxKind.TupleExpression, tuple.Arguments[0].Expression.Kind());
Assert.NotNull(tuple.Arguments[0].NameColon.Name);
Assert.Equal("arg2", tuple.Arguments[1].NameColon.Name.ToString());
}
[Fact]
public void TestFromSelect()
{
var text = "from a in A select b";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(0, qs.Body.Clauses.Count);
var fs = (FromClauseSyntax)qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.Equal(SyntaxKind.FromKeyword, fs.FromKeyword.Kind());
Assert.False(fs.FromKeyword.IsMissing);
Assert.Null(fs.Type);
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
var ss = (SelectClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.Equal(SyntaxKind.SelectKeyword, ss.SelectKeyword.Kind());
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("b", ss.Expression.ToString());
Assert.Null(qs.Body.Continuation);
}
[Fact]
public void TestFromWithType()
{
var text = "from T a in A select b";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(0, qs.Body.Clauses.Count);
Assert.Equal(SyntaxKind.FromClause, qs.FromClause.Kind());
var fs = (FromClauseSyntax)qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.NotNull(fs.Type);
Assert.Equal("T", fs.Type.ToString());
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
var ss = (SelectClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("b", ss.Expression.ToString());
Assert.Null(qs.Body.Continuation);
}
[Fact]
public void TestFromSelectIntoSelect()
{
var text = "from a in A select b into c select d";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(0, qs.Body.Clauses.Count);
Assert.Equal(SyntaxKind.FromClause, qs.FromClause.Kind());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
var fs = (FromClauseSyntax)qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.Null(fs.Type);
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
var ss = (SelectClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("b", ss.Expression.ToString());
Assert.NotNull(qs.Body.Continuation);
Assert.Equal(SyntaxKind.QueryContinuation, qs.Body.Continuation.Kind());
Assert.NotEqual(default, qs.Body.Continuation.IntoKeyword);
Assert.Equal(SyntaxKind.IntoKeyword, qs.Body.Continuation.IntoKeyword.Kind());
Assert.False(qs.Body.Continuation.IntoKeyword.IsMissing);
Assert.Equal("c", qs.Body.Continuation.Identifier.ToString());
Assert.NotNull(qs.Body.Continuation.Body);
Assert.Equal(0, qs.Body.Continuation.Body.Clauses.Count);
Assert.NotNull(qs.Body.Continuation.Body.SelectOrGroup);
Assert.Equal(SyntaxKind.SelectClause, qs.Body.Continuation.Body.SelectOrGroup.Kind());
ss = (SelectClauseSyntax)qs.Body.Continuation.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("d", ss.Expression.ToString());
Assert.Null(qs.Body.Continuation.Body.Continuation);
}
[Fact]
public void TestFromWhereSelect()
{
var text = "from a in A where b select c";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(1, qs.Body.Clauses.Count);
Assert.Equal(SyntaxKind.FromClause, qs.FromClause.Kind());
var fs = (FromClauseSyntax)qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.Null(fs.Type);
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.WhereClause, qs.Body.Clauses[0].Kind());
var ws = (WhereClauseSyntax)qs.Body.Clauses[0];
Assert.NotEqual(default, ws.WhereKeyword);
Assert.Equal(SyntaxKind.WhereKeyword, ws.WhereKeyword.Kind());
Assert.False(ws.WhereKeyword.IsMissing);
Assert.NotNull(ws.Condition);
Assert.Equal("b", ws.Condition.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
var ss = (SelectClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("c", ss.Expression.ToString());
Assert.Null(qs.Body.Continuation);
}
[Fact]
public void TestFromFromSelect()
{
var text = "from a in A from b in B select c";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(1, qs.Body.Clauses.Count);
Assert.Equal(SyntaxKind.FromClause, qs.FromClause.Kind());
var fs = (FromClauseSyntax)qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.Null(fs.Type);
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
Assert.Equal(SyntaxKind.FromClause, qs.Body.Clauses[0].Kind());
fs = (FromClauseSyntax)qs.Body.Clauses[0];
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.Null(fs.Type);
Assert.Equal("b", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("B", fs.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
var ss = (SelectClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("c", ss.Expression.ToString());
Assert.Null(qs.Body.Continuation);
}
[Fact]
public void TestFromLetSelect()
{
var text = "from a in A let b = B select c";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(1, qs.Body.Clauses.Count);
Assert.Equal(SyntaxKind.FromClause, qs.FromClause.Kind());
var fs = (FromClauseSyntax)qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.Null(fs.Type);
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
Assert.Equal(SyntaxKind.LetClause, qs.Body.Clauses[0].Kind());
var ls = (LetClauseSyntax)qs.Body.Clauses[0];
Assert.NotEqual(default, ls.LetKeyword);
Assert.Equal(SyntaxKind.LetKeyword, ls.LetKeyword.Kind());
Assert.False(ls.LetKeyword.IsMissing);
Assert.NotEqual(default, ls.Identifier);
Assert.Equal("b", ls.Identifier.ToString());
Assert.NotEqual(default, ls.EqualsToken);
Assert.False(ls.EqualsToken.IsMissing);
Assert.NotNull(ls.Expression);
Assert.Equal("B", ls.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
var ss = (SelectClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("c", ss.Expression.ToString());
Assert.Null(qs.Body.Continuation);
}
[Fact]
public void TestFromOrderBySelect()
{
var text = "from a in A orderby b select c";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(1, qs.Body.Clauses.Count);
Assert.Equal(SyntaxKind.FromClause, qs.FromClause.Kind());
var fs = (FromClauseSyntax)qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.Null(fs.Type);
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
Assert.Equal(SyntaxKind.OrderByClause, qs.Body.Clauses[0].Kind());
var obs = (OrderByClauseSyntax)qs.Body.Clauses[0];
Assert.NotEqual(default, obs.OrderByKeyword);
Assert.Equal(SyntaxKind.OrderByKeyword, obs.OrderByKeyword.Kind());
Assert.False(obs.OrderByKeyword.IsMissing);
Assert.Equal(1, obs.Orderings.Count);
var os = (OrderingSyntax)obs.Orderings[0];
Assert.Equal(SyntaxKind.None, os.AscendingOrDescendingKeyword.Kind());
Assert.NotNull(os.Expression);
Assert.Equal("b", os.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
var ss = (SelectClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("c", ss.Expression.ToString());
Assert.Null(qs.Body.Continuation);
}
[Fact]
public void TestFromOrderBy2Select()
{
var text = "from a in A orderby b, b2 select c";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(1, qs.Body.Clauses.Count);
Assert.Equal(SyntaxKind.FromClause, qs.FromClause.Kind());
var fs = (FromClauseSyntax)qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.Null(fs.Type);
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
Assert.Equal(SyntaxKind.OrderByClause, qs.Body.Clauses[0].Kind());
var obs = (OrderByClauseSyntax)qs.Body.Clauses[0];
Assert.NotEqual(default, obs.OrderByKeyword);
Assert.False(obs.OrderByKeyword.IsMissing);
Assert.Equal(2, obs.Orderings.Count);
var os = (OrderingSyntax)obs.Orderings[0];
Assert.Equal(SyntaxKind.None, os.AscendingOrDescendingKeyword.Kind());
Assert.NotNull(os.Expression);
Assert.Equal("b", os.Expression.ToString());
os = (OrderingSyntax)obs.Orderings[1];
Assert.Equal(SyntaxKind.None, os.AscendingOrDescendingKeyword.Kind());
Assert.NotNull(os.Expression);
Assert.Equal("b2", os.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
var ss = (SelectClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("c", ss.Expression.ToString());
Assert.Null(qs.Body.Continuation);
}
[Fact]
public void TestFromOrderByAscendingSelect()
{
var text = "from a in A orderby b ascending select c";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(1, qs.Body.Clauses.Count);
Assert.Equal(SyntaxKind.FromClause, qs.FromClause.Kind());
var fs = (FromClauseSyntax)qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.Null(fs.Type);
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
Assert.Equal(SyntaxKind.OrderByClause, qs.Body.Clauses[0].Kind());
var obs = (OrderByClauseSyntax)qs.Body.Clauses[0];
Assert.NotEqual(default, obs.OrderByKeyword);
Assert.False(obs.OrderByKeyword.IsMissing);
Assert.Equal(1, obs.Orderings.Count);
var os = (OrderingSyntax)obs.Orderings[0];
Assert.NotEqual(default, os.AscendingOrDescendingKeyword);
Assert.Equal(SyntaxKind.AscendingKeyword, os.AscendingOrDescendingKeyword.Kind());
Assert.False(os.AscendingOrDescendingKeyword.IsMissing);
Assert.Equal(SyntaxKind.AscendingKeyword, os.AscendingOrDescendingKeyword.ContextualKind());
Assert.NotNull(os.Expression);
Assert.Equal("b", os.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
var ss = (SelectClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("c", ss.Expression.ToString());
Assert.Null(qs.Body.Continuation);
}
[Fact]
public void TestFromOrderByDescendingSelect()
{
var text = "from a in A orderby b descending select c";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(1, qs.Body.Clauses.Count);
Assert.Equal(SyntaxKind.FromClause, qs.FromClause.Kind());
var fs = (FromClauseSyntax)qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.Null(fs.Type);
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
Assert.Equal(SyntaxKind.OrderByClause, qs.Body.Clauses[0].Kind());
var obs = (OrderByClauseSyntax)qs.Body.Clauses[0];
Assert.NotEqual(default, obs.OrderByKeyword);
Assert.False(obs.OrderByKeyword.IsMissing);
Assert.Equal(1, obs.Orderings.Count);
var os = (OrderingSyntax)obs.Orderings[0];
Assert.NotEqual(default, os.AscendingOrDescendingKeyword);
Assert.Equal(SyntaxKind.DescendingKeyword, os.AscendingOrDescendingKeyword.Kind());
Assert.False(os.AscendingOrDescendingKeyword.IsMissing);
Assert.Equal(SyntaxKind.DescendingKeyword, os.AscendingOrDescendingKeyword.ContextualKind());
Assert.NotNull(os.Expression);
Assert.Equal("b", os.Expression.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
var ss = (SelectClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("c", ss.Expression.ToString());
Assert.Null(qs.Body.Continuation);
}
[Fact]
public void TestFromGroupBy()
{
var text = "from a in A group b by c";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(0, qs.Body.Clauses.Count);
var fs = qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.Null(fs.Type);
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.GroupClause, qs.Body.SelectOrGroup.Kind());
var gbs = (GroupClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, gbs.GroupKeyword);
Assert.Equal(SyntaxKind.GroupKeyword, gbs.GroupKeyword.Kind());
Assert.False(gbs.GroupKeyword.IsMissing);
Assert.NotNull(gbs.GroupExpression);
Assert.Equal("b", gbs.GroupExpression.ToString());
Assert.NotEqual(default, gbs.ByKeyword);
Assert.Equal(SyntaxKind.ByKeyword, gbs.ByKeyword.Kind());
Assert.False(gbs.ByKeyword.IsMissing);
Assert.NotNull(gbs.ByExpression);
Assert.Equal("c", gbs.ByExpression.ToString());
Assert.Null(qs.Body.Continuation);
}
[Fact]
public void TestFromGroupByIntoSelect()
{
var text = "from a in A group b by c into d select e";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(0, qs.Body.Clauses.Count);
var fs = qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.Null(fs.Type);
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.GroupClause, qs.Body.SelectOrGroup.Kind());
var gbs = (GroupClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, gbs.GroupKeyword);
Assert.False(gbs.GroupKeyword.IsMissing);
Assert.NotNull(gbs.GroupExpression);
Assert.Equal("b", gbs.GroupExpression.ToString());
Assert.NotEqual(default, gbs.ByKeyword);
Assert.False(gbs.ByKeyword.IsMissing);
Assert.NotNull(gbs.ByExpression);
Assert.Equal("c", gbs.ByExpression.ToString());
Assert.NotNull(qs.Body.Continuation);
Assert.Equal(SyntaxKind.QueryContinuation, qs.Body.Continuation.Kind());
Assert.NotEqual(default, qs.Body.Continuation.IntoKeyword);
Assert.False(qs.Body.Continuation.IntoKeyword.IsMissing);
Assert.Equal("d", qs.Body.Continuation.Identifier.ToString());
Assert.NotNull(qs.Body.Continuation);
Assert.Equal(0, qs.Body.Continuation.Body.Clauses.Count);
Assert.NotNull(qs.Body.Continuation.Body.SelectOrGroup);
Assert.Equal(SyntaxKind.SelectClause, qs.Body.Continuation.Body.SelectOrGroup.Kind());
var ss = (SelectClauseSyntax)qs.Body.Continuation.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("e", ss.Expression.ToString());
Assert.Null(qs.Body.Continuation.Body.Continuation);
}
[Fact]
public void TestFromJoinSelect()
{
var text = "from a in A join b in B on a equals b select c";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(1, qs.Body.Clauses.Count);
Assert.Equal(SyntaxKind.FromClause, qs.FromClause.Kind());
var fs = (FromClauseSyntax)qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.Null(fs.Type);
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.JoinClause, qs.Body.Clauses[0].Kind());
var js = (JoinClauseSyntax)qs.Body.Clauses[0];
Assert.NotEqual(default, js.JoinKeyword);
Assert.Equal(SyntaxKind.JoinKeyword, js.JoinKeyword.Kind());
Assert.False(js.JoinKeyword.IsMissing);
Assert.Null(js.Type);
Assert.NotEqual(default, js.Identifier);
Assert.Equal("b", js.Identifier.ToString());
Assert.NotEqual(default, js.InKeyword);
Assert.False(js.InKeyword.IsMissing);
Assert.NotNull(js.InExpression);
Assert.Equal("B", js.InExpression.ToString());
Assert.NotEqual(default, js.OnKeyword);
Assert.Equal(SyntaxKind.OnKeyword, js.OnKeyword.Kind());
Assert.False(js.OnKeyword.IsMissing);
Assert.NotNull(js.LeftExpression);
Assert.Equal("a", js.LeftExpression.ToString());
Assert.NotEqual(default, js.EqualsKeyword);
Assert.Equal(SyntaxKind.EqualsKeyword, js.EqualsKeyword.Kind());
Assert.False(js.EqualsKeyword.IsMissing);
Assert.NotNull(js.RightExpression);
Assert.Equal("b", js.RightExpression.ToString());
Assert.Null(js.Into);
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
var ss = (SelectClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("c", ss.Expression.ToString());
Assert.Null(qs.Body.Continuation);
}
[Fact]
public void TestFromJoinWithTypesSelect()
{
var text = "from Ta a in A join Tb b in B on a equals b select c";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(1, qs.Body.Clauses.Count);
Assert.Equal(SyntaxKind.FromClause, qs.FromClause.Kind());
var fs = (FromClauseSyntax)qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.NotNull(fs.Type);
Assert.Equal("Ta", fs.Type.ToString());
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.JoinClause, qs.Body.Clauses[0].Kind());
var js = (JoinClauseSyntax)qs.Body.Clauses[0];
Assert.NotEqual(default, js.JoinKeyword);
Assert.False(js.JoinKeyword.IsMissing);
Assert.NotNull(js.Type);
Assert.Equal("Tb", js.Type.ToString());
Assert.NotEqual(default, js.Identifier);
Assert.Equal("b", js.Identifier.ToString());
Assert.NotEqual(default, js.InKeyword);
Assert.False(js.InKeyword.IsMissing);
Assert.NotNull(js.InExpression);
Assert.Equal("B", js.InExpression.ToString());
Assert.NotEqual(default, js.OnKeyword);
Assert.False(js.OnKeyword.IsMissing);
Assert.NotNull(js.LeftExpression);
Assert.Equal("a", js.LeftExpression.ToString());
Assert.NotEqual(default, js.EqualsKeyword);
Assert.False(js.EqualsKeyword.IsMissing);
Assert.NotNull(js.RightExpression);
Assert.Equal("b", js.RightExpression.ToString());
Assert.Null(js.Into);
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
var ss = (SelectClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("c", ss.Expression.ToString());
Assert.Null(qs.Body.Continuation);
}
[Fact]
public void TestFromJoinIntoSelect()
{
var text = "from a in A join b in B on a equals b into c select d";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.Equal(1, qs.Body.Clauses.Count);
Assert.Equal(SyntaxKind.FromClause, qs.FromClause.Kind());
var fs = (FromClauseSyntax)qs.FromClause;
Assert.NotEqual(default, fs.FromKeyword);
Assert.False(fs.FromKeyword.IsMissing);
Assert.Null(fs.Type);
Assert.Equal("a", fs.Identifier.ToString());
Assert.NotEqual(default, fs.InKeyword);
Assert.False(fs.InKeyword.IsMissing);
Assert.Equal("A", fs.Expression.ToString());
Assert.Equal(SyntaxKind.JoinClause, qs.Body.Clauses[0].Kind());
var js = (JoinClauseSyntax)qs.Body.Clauses[0];
Assert.NotEqual(default, js.JoinKeyword);
Assert.False(js.JoinKeyword.IsMissing);
Assert.Null(js.Type);
Assert.NotEqual(default, js.Identifier);
Assert.Equal("b", js.Identifier.ToString());
Assert.NotEqual(default, js.InKeyword);
Assert.False(js.InKeyword.IsMissing);
Assert.NotNull(js.InExpression);
Assert.Equal("B", js.InExpression.ToString());
Assert.NotEqual(default, js.OnKeyword);
Assert.False(js.OnKeyword.IsMissing);
Assert.NotNull(js.LeftExpression);
Assert.Equal("a", js.LeftExpression.ToString());
Assert.NotEqual(default, js.EqualsKeyword);
Assert.False(js.EqualsKeyword.IsMissing);
Assert.NotNull(js.RightExpression);
Assert.Equal("b", js.RightExpression.ToString());
Assert.NotNull(js.Into);
Assert.NotEqual(default, js.Into.IntoKeyword);
Assert.False(js.Into.IntoKeyword.IsMissing);
Assert.NotEqual(default, js.Into.Identifier);
Assert.Equal("c", js.Into.Identifier.ToString());
Assert.Equal(SyntaxKind.SelectClause, qs.Body.SelectOrGroup.Kind());
var ss = (SelectClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotEqual(default, ss.SelectKeyword);
Assert.False(ss.SelectKeyword.IsMissing);
Assert.Equal("d", ss.Expression.ToString());
Assert.Null(qs.Body.Continuation);
}
[Fact]
public void TestFromGroupBy1()
{
var text = "from it in goo group x by y";
var expr = SyntaxFactory.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
var qs = (QueryExpressionSyntax)expr;
Assert.NotNull(qs.Body.SelectOrGroup);
Assert.IsType<GroupClauseSyntax>(qs.Body.SelectOrGroup);
var gs = (GroupClauseSyntax)qs.Body.SelectOrGroup;
Assert.NotNull(gs.GroupExpression);
Assert.Equal("x", gs.GroupExpression.ToString());
Assert.Equal("y", gs.ByExpression.ToString());
}
[WorkItem(543075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543075")]
[Fact]
public void UnterminatedRankSpecifier()
{
var text = "new int[";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ArrayCreationExpression, expr.Kind());
var arrayCreation = (ArrayCreationExpressionSyntax)expr;
Assert.Equal(1, arrayCreation.Type.RankSpecifiers.Single().Rank);
}
[WorkItem(543075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543075")]
[Fact]
public void UnterminatedTypeArgumentList()
{
var text = "new C<";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ObjectCreationExpression, expr.Kind());
var objectCreation = (ObjectCreationExpressionSyntax)expr;
Assert.Equal(1, ((NameSyntax)objectCreation.Type).Arity);
}
[WorkItem(675602, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/675602")]
[Fact]
public void QueryKeywordInObjectInitializer()
{
//'on' is a keyword here
var text = "from elem in aRay select new Result { A = on = true }";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.QueryExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.NotEqual(0, expr.Errors().Length);
}
[Fact]
public void IndexingExpressionInParens()
{
var text = "(aRay[i,j])";
var expr = this.ParseExpression(text);
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.ParenthesizedExpression, expr.Kind());
var parenExp = (ParenthesizedExpressionSyntax)expr;
Assert.Equal(SyntaxKind.ElementAccessExpression, parenExp.Expression.Kind());
}
[WorkItem(543993, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543993")]
[Fact]
public void ShiftOperator()
{
UsingTree(@"
class C
{
int x = 1 << 2 << 3;
}
");
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.FieldDeclaration);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType); N(SyntaxKind.IntKeyword);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken);
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
// NB: left associative
N(SyntaxKind.LeftShiftExpression);
{
N(SyntaxKind.LeftShiftExpression);
{
N(SyntaxKind.NumericLiteralExpression); N(SyntaxKind.NumericLiteralToken);
N(SyntaxKind.LessThanLessThanToken);
N(SyntaxKind.NumericLiteralExpression); N(SyntaxKind.NumericLiteralToken);
}
N(SyntaxKind.LessThanLessThanToken);
N(SyntaxKind.NumericLiteralExpression); N(SyntaxKind.NumericLiteralToken);
}
}
}
N(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
}
[WorkItem(1091974, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091974")]
[Fact]
public void ParseBigExpression()
{
var text = @"
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text.RegularExpressions;
namespace WB.Core.SharedKernels.DataCollection.Generated
{
internal partial class QuestionnaireTopLevel
{
private bool IsValid_a()
{
return (stackDepth == 100) || ((stackDepth == 200) || ((stackDepth == 300) || ((stackDepth == 400) || ((stackDepth == 501) || ((stackDepth == 502) || ((stackDepth == 600) || ((stackDepth == 701) || ((stackDepth == 702) || ((stackDepth == 801) || ((stackDepth == 802) || ((stackDepth == 901) || ((stackDepth == 902) || ((stackDepth == 903) || ((stackDepth == 1001) || ((stackDepth == 1002) || ((stackDepth == 1101) || ((stackDepth == 1102) || ((stackDepth == 1201) || ((stackDepth == 1202) || ((stackDepth == 1301) || ((stackDepth == 1302) || ((stackDepth == 1401) || ((stackDepth == 1402) || ((stackDepth == 1403) || ((stackDepth == 1404) || ((stackDepth == 1405) || ((stackDepth == 1406) || ((stackDepth == 1407) || ((stackDepth == 1408) || ((stackDepth == 1409) || ((stackDepth == 1410) || ((stackDepth == 1411) || ((stackDepth == 1412) || ((stackDepth == 1413) || ((stackDepth == 1500) || ((stackDepth == 1601) || ((stackDepth == 1602) || ((stackDepth == 1701) || ((stackDepth == 1702) || ((stackDepth == 1703) || ((stackDepth == 1800) || ((stackDepth == 1901) || ((stackDepth == 1902) || ((stackDepth == 1903) || ((stackDepth == 1904) || ((stackDepth == 2000) || ((stackDepth == 2101) || ((stackDepth == 2102) || ((stackDepth == 2103) || ((stackDepth == 2104) || ((stackDepth == 2105) || ((stackDepth == 2106) || ((stackDepth == 2107) || ((stackDepth == 2201) || ((stackDepth == 2202) || ((stackDepth == 2203) || ((stackDepth == 2301) || ((stackDepth == 2302) || ((stackDepth == 2303) || ((stackDepth == 2304) || ((stackDepth == 2305) || ((stackDepth == 2401) || ((stackDepth == 2402) || ((stackDepth == 2403) || ((stackDepth == 2404) || ((stackDepth == 2501) || ((stackDepth == 2502) || ((stackDepth == 2503) || ((stackDepth == 2504) || ((stackDepth == 2505) || ((stackDepth == 2601) || ((stackDepth == 2602) || ((stackDepth == 2603) || ((stackDepth == 2604) || ((stackDepth == 2605) || ((stackDepth == 2606) || ((stackDepth == 2607) || ((stackDepth == 2608) || ((stackDepth == 2701) || ((stackDepth == 2702) || ((stackDepth == 2703) || ((stackDepth == 2704) || ((stackDepth == 2705) || ((stackDepth == 2706) || ((stackDepth == 2801) || ((stackDepth == 2802) || ((stackDepth == 2803) || ((stackDepth == 2804) || ((stackDepth == 2805) || ((stackDepth == 2806) || ((stackDepth == 2807) || ((stackDepth == 2808) || ((stackDepth == 2809) || ((stackDepth == 2810) || ((stackDepth == 2901) || ((stackDepth == 2902) || ((stackDepth == 3001) || ((stackDepth == 3002) || ((stackDepth == 3101) || ((stackDepth == 3102) || ((stackDepth == 3103) || ((stackDepth == 3104) || ((stackDepth == 3105) || ((stackDepth == 3201) || ((stackDepth == 3202) || ((stackDepth == 3203) || ((stackDepth == 3301) || ((stackDepth == 3302) || ((stackDepth == 3401) || ((stackDepth == 3402) || ((stackDepth == 3403) || ((stackDepth == 3404) || ((stackDepth == 3405) || ((stackDepth == 3406) || ((stackDepth == 3407) || ((stackDepth == 3408) || ((stackDepth == 3409) || ((stackDepth == 3410) || ((stackDepth == 3501) || ((stackDepth == 3502) || ((stackDepth == 3503) || ((stackDepth == 3504) || ((stackDepth == 3505) || ((stackDepth == 3506) || ((stackDepth == 3507) || ((stackDepth == 3508) || ((stackDepth == 3509) || ((stackDepth == 3601) || ((stackDepth == 3602) || ((stackDepth == 3701) || ((stackDepth == 3702) || ((stackDepth == 3703) || ((stackDepth == 3704) || ((stackDepth == 3705) || ((stackDepth == 3706) || ((stackDepth == 3801) || ((stackDepth == 3802) || ((stackDepth == 3803) || ((stackDepth == 3804) || ((stackDepth == 3805) || ((stackDepth == 3901) || ((stackDepth == 3902) || ((stackDepth == 3903) || ((stackDepth == 3904) || ((stackDepth == 3905) || ((stackDepth == 4001) || ((stackDepth == 4002) || ((stackDepth == 4003) || ((stackDepth == 4004) || ((stackDepth == 4005) || ((stackDepth == 4006) || ((stackDepth == 4007) || ((stackDepth == 4100) || ((stackDepth == 4201) || ((stackDepth == 4202) || ((stackDepth == 4203) || ((stackDepth == 4204) || ((stackDepth == 4301) || ((stackDepth == 4302) || ((stackDepth == 4304) || ((stackDepth == 4401) || ((stackDepth == 4402) || ((stackDepth == 4403) || ((stackDepth == 4404) || ((stackDepth == 4501) || ((stackDepth == 4502) || ((stackDepth == 4503) || ((stackDepth == 4504) || ((stackDepth == 4600) || ((stackDepth == 4701) || ((stackDepth == 4702) || ((stackDepth == 4801) || ((stackDepth == 4802) || ((stackDepth == 4803) || ((stackDepth == 4804) || ((stackDepth == 4805) || ((stackDepth == 4806) || ((stackDepth == 4807) || ((stackDepth == 4808) || ((stackDepth == 4809) || ((stackDepth == 4811) || ((stackDepth == 4901) || ((stackDepth == 4902) || ((stackDepth == 4903) || ((stackDepth == 4904) || ((stackDepth == 4905) || ((stackDepth == 4906) || ((stackDepth == 4907) || ((stackDepth == 4908) || ((stackDepth == 4909) || ((stackDepth == 4910) || ((stackDepth == 4911) || ((stackDepth == 4912) || ((stackDepth == 4913) || ((stackDepth == 4914) || ((stackDepth == 4915) || ((stackDepth == 4916) || ((stackDepth == 4917) || ((stackDepth == 4918) || ((stackDepth == 4919) || ((stackDepth == 4920) || ((stackDepth == 4921) || ((stackDepth == 4922) || ((stackDepth == 4923) || ((stackDepth == 5001) || ((stackDepth == 5002) || ((stackDepth == 5003) || ((stackDepth == 5004) || ((stackDepth == 5005) || ((stackDepth == 5006) || ((stackDepth == 5100) || ((stackDepth == 5200) || ((stackDepth == 5301) || ((stackDepth == 5302) || ((stackDepth == 5400) || ((stackDepth == 5500) || ((stackDepth == 5600) || ((stackDepth == 5700) || ((stackDepth == 5801) || ((stackDepth == 5802) || ((stackDepth == 5901) || ((stackDepth == 5902) || ((stackDepth == 6001) || ((stackDepth == 6002) || ((stackDepth == 6101) || ((stackDepth == 6102) || ((stackDepth == 6201) || ((stackDepth == 6202) || ((stackDepth == 6203) || ((stackDepth == 6204) || ((stackDepth == 6205) || ((stackDepth == 6301) || ((stackDepth == 6302) || ((stackDepth == 6401) || ((stackDepth == 6402) || ((stackDepth == 6501) || ((stackDepth == 6502) || ((stackDepth == 6503) || ((stackDepth == 6504) || ((stackDepth == 6601) || ((stackDepth == 6602) || ((stackDepth == 6701) || ((stackDepth == 6702) || ((stackDepth == 6703) || ((stackDepth == 6704) || ((stackDepth == 6801) || ((stackDepth == 6802) || ((stackDepth == 6901) || ((stackDepth == 6902) || ((stackDepth == 6903) || ((stackDepth == 6904) || ((stackDepth == 7001) || ((stackDepth == 7002) || ((stackDepth == 7101) || ((stackDepth == 7102) || ((stackDepth == 7103) || ((stackDepth == 7200) || ((stackDepth == 7301) || ((stackDepth == 7302) || ((stackDepth == 7400) || ((stackDepth == 7501) || ((stackDepth == 7502) || ((stackDepth == 7503) || ((stackDepth == 7600) || ((stackDepth == 7700) || ((stackDepth == 7800) || ((stackDepth == 7900) || ((stackDepth == 8001) || ((stackDepth == 8002) || ((stackDepth == 8101) || ((stackDepth == 8102) || ((stackDepth == 8103) || ((stackDepth == 8200) || ((stackDepth == 8300) || ((stackDepth == 8400) || ((stackDepth == 8501) || ((stackDepth == 8502) || ((stackDepth == 8601) || ((stackDepth == 8602) || ((stackDepth == 8700) || ((stackDepth == 8801) || ((stackDepth == 8802) || ((stackDepth == 8901) || ((stackDepth == 8902) || ((stackDepth == 8903) || ((stackDepth == 9001) || ((stackDepth == 9002) || ((stackDepth == 9003) || ((stackDepth == 9004) || ((stackDepth == 9005) || ((stackDepth == 9101) || ((stackDepth == 9102) || ((stackDepth == 9200) || ((stackDepth == 9300) || ((stackDepth == 9401) || ((stackDepth == 9402) || ((stackDepth == 9403) || ((stackDepth == 9500) || ((stackDepth == 9601) || ((stackDepth == 9602) || ((stackDepth == 9701) || ((stackDepth == 9702) || ((stackDepth == 9801) || ((stackDepth == 9802) || ((stackDepth == 9900) || ((stackDepth == 10000) || ((stackDepth == 10100) || ((stackDepth == 10201) || ((stackDepth == 10202) || ((stackDepth == 10301) || ((stackDepth == 10302) || ((stackDepth == 10401) || ((stackDepth == 10402) || ((stackDepth == 10403) || ((stackDepth == 10501) || ((stackDepth == 10502) || ((stackDepth == 10601) || ((stackDepth == 10602) || ((stackDepth == 10701) || ((stackDepth == 10702) || ((stackDepth == 10703) || ((stackDepth == 10704) || ((stackDepth == 10705) || ((stackDepth == 10706) || ((stackDepth == 10801) || ((stackDepth == 10802) || ((stackDepth == 10803) || ((stackDepth == 10804) || ((stackDepth == 10805) || ((stackDepth == 10806) || ((stackDepth == 10807) || ((stackDepth == 10808) || ((stackDepth == 10809) || ((stackDepth == 10900) || ((stackDepth == 11000) || ((stackDepth == 11100) || ((stackDepth == 11201) || ((stackDepth == 11202) || ((stackDepth == 11203) || ((stackDepth == 11204) || ((stackDepth == 11205) || ((stackDepth == 11206) || ((stackDepth == 11207) || ((stackDepth == 11208) || ((stackDepth == 11209) || ((stackDepth == 11210) || ((stackDepth == 11211) || ((stackDepth == 11212) || ((stackDepth == 11213) || ((stackDepth == 11214) || ((stackDepth == 11301) || ((stackDepth == 11302) || ((stackDepth == 11303) || ((stackDepth == 11304) || ((stackDepth == 11305) || ((stackDepth == 11306) || ((stackDepth == 11307) || ((stackDepth == 11308) || ((stackDepth == 11309) || ((stackDepth == 11401) || ((stackDepth == 11402) || ((stackDepth == 11403) || ((stackDepth == 11404) || ((stackDepth == 11501) || ((stackDepth == 11502) || ((stackDepth == 11503) || ((stackDepth == 11504) || ((stackDepth == 11505) || ((stackDepth == 11601) || ((stackDepth == 11602) || ((stackDepth == 11603) || ((stackDepth == 11604) || ((stackDepth == 11605) || ((stackDepth == 11606) || ((stackDepth == 11701) || ((stackDepth == 11702) || ((stackDepth == 11800) || ((stackDepth == 11901) || ((stackDepth == 11902) || ((stackDepth == 11903) || ((stackDepth == 11904) || ((stackDepth == 11905) || ((stackDepth == 12001) || ((stackDepth == 12002) || ((stackDepth == 12003) || ((stackDepth == 12004) || ((stackDepth == 12101) || ((stackDepth == 12102) || ((stackDepth == 12103) || ((stackDepth == 12104) || ((stackDepth == 12105) || ((stackDepth == 12106) || ((stackDepth == 12107) || ((stackDepth == 12108) || ((stackDepth == 12109) || ((stackDepth == 12110) || ((stackDepth == 12111) || ((stackDepth == 12112) || ((stackDepth == 12113) || ((stackDepth == 12114) || ((stackDepth == 12115) || ((stackDepth == 12116) || ((stackDepth == 12201) || ((stackDepth == 12202) || ((stackDepth == 12203) || ((stackDepth == 12204) || ((stackDepth == 12205) || ((stackDepth == 12301) || ((stackDepth == 12302) || ((stackDepth == 12401) || ((stackDepth == 12402) || ((stackDepth == 12403) || ((stackDepth == 12404) || ((stackDepth == 12405) || ((stackDepth == 12406) || ((stackDepth == 12501) || ((stackDepth == 12502) || ((stackDepth == 12601) || ((stackDepth == 12602) || ((stackDepth == 12603) || ((stackDepth == 12700) || ((stackDepth == 12800) || ((stackDepth == 12900) || ((stackDepth == 13001) || ((stackDepth == 13002) || ((stackDepth == 13003) || ((stackDepth == 13004) || ((stackDepth == 13005) || ((stackDepth == 13101) || ((stackDepth == 13102) || ((stackDepth == 13103) || ((stackDepth == 13201) || ((stackDepth == 13202) || ((stackDepth == 13203) || ((stackDepth == 13301) || ((stackDepth == 13302) || ((stackDepth == 13303) || ((stackDepth == 13304) || ((stackDepth == 13401) || ((stackDepth == 13402) || ((stackDepth == 13403) || ((stackDepth == 13404) || ((stackDepth == 13405) || ((stackDepth == 13501) || ((stackDepth == 13502) || ((stackDepth == 13600) || ((stackDepth == 13701) || ((stackDepth == 13702) || ((stackDepth == 13703) || ((stackDepth == 13800) || ((stackDepth == 13901) || ((stackDepth == 13902) || ((stackDepth == 13903) || ((stackDepth == 14001) || ((stackDepth == 14002) || ((stackDepth == 14100) || ((stackDepth == 14200) || ((stackDepth == 14301) || ((stackDepth == 14302) || ((stackDepth == 14400) || ((stackDepth == 14501) || ((stackDepth == 14502) || ((stackDepth == 14601) || ((stackDepth == 14602) || ((stackDepth == 14603) || ((stackDepth == 14604) || ((stackDepth == 14605) || ((stackDepth == 14606) || ((stackDepth == 14607) || ((stackDepth == 14701) || ((stackDepth == 14702) || ((stackDepth == 14703) || ((stackDepth == 14704) || ((stackDepth == 14705) || ((stackDepth == 14706) || ((stackDepth == 14707) || ((stackDepth == 14708) || ((stackDepth == 14709) || ((stackDepth == 14710) || ((stackDepth == 14711) || ((stackDepth == 14712) || ((stackDepth == 14713) || ((stackDepth == 14714) || ((stackDepth == 14715) || ((stackDepth == 14716) || ((stackDepth == 14717) || ((stackDepth == 14718) || ((stackDepth == 14719) || ((stackDepth == 14720 || ((stackDepth == 14717 || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717 || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717 || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717) || ((stackDepth == 14717))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))))));
}
}
}
";
var root = SyntaxFactory.ParseSyntaxTree(text).GetRoot();
Assert.NotNull(root);
Assert.Equal(SyntaxKind.CompilationUnit, root.Kind());
}
[Fact, WorkItem(15885, "https://github.com/dotnet/roslyn/pull/15885")]
public void InProgressLocalDeclaration1()
{
const string text = @"
class C
{
async void M()
{
Task.
await Task.Delay();
}
}
";
ParseAndValidate(text,
// (6,14): error CS1001: Identifier expected
// Task.
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(6, 14),
// (6,14): error CS1002: ; expected
// Task.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 14));
UsingTree(text);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Task");
}
N(SyntaxKind.DotToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AwaitExpression);
{
N(SyntaxKind.AwaitKeyword);
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Task");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Delay");
}
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(15885, "https://github.com/dotnet/roslyn/pull/15885")]
public void InProgressLocalDeclaration2()
{
const string text = @"
class C
{
async void M()
{
Task.await Task.Delay();
}
}
";
ParseAndValidate(text,
// (6,14): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression
// Task.await Task.Delay();
Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(6, 14),
// (6,24): error CS1003: Syntax error, ',' expected
// Task.await Task.Delay();
Diagnostic(ErrorCode.ERR_SyntaxError, ".").WithArguments(",", ".").WithLocation(6, 24),
// (6,25): error CS1002: ; expected
// Task.await Task.Delay();
Diagnostic(ErrorCode.ERR_SemicolonExpected, "Delay").WithLocation(6, 25));
UsingTree(text);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Task");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "await");
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "Task");
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Delay");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(15885, "https://github.com/dotnet/roslyn/pull/15885")]
public void InProgressLocalDeclaration3()
{
const string text = @"
class C
{
async void M()
{
Task.
await Task;
}
}
";
ParseAndValidate(text,
// (7,9): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression
// await Task;
Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(7, 9));
UsingTree(text);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Task");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "await");
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "Task");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(15885, "https://github.com/dotnet/roslyn/pull/15885")]
public void InProgressLocalDeclaration4()
{
const string text = @"
class C
{
async void M()
{
Task.
await Task = 1;
}
}
";
ParseAndValidate(text,
// (7,9): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression
// await Task = 1;
Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(7, 9));
UsingTree(text);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Task");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "await");
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "Task");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(15885, "https://github.com/dotnet/roslyn/pull/15885")]
public void InProgressLocalDeclaration5()
{
const string text = @"
class C
{
async void M()
{
Task.
await Task, Task2;
}
}
";
ParseAndValidate(text,
// (7,9): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression
// await Task, Task2;
Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(7, 9));
UsingTree(text);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Task");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "await");
}
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "Task");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "Task2");
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(15885, "https://github.com/dotnet/roslyn/pull/15885")]
public void InProgressLocalDeclaration6()
{
const string text = @"
class C
{
async void M()
{
Task.
await Task();
}
}
";
ParseAndValidate(text,
// (7,9): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression
// await Task();
Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(7, 9));
UsingTree(text);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalFunctionStatement);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Task");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "await");
}
}
N(SyntaxKind.IdentifierToken, "Task");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(15885, "https://github.com/dotnet/roslyn/pull/15885")]
public void InProgressLocalDeclaration7()
{
const string text = @"
class C
{
async void M()
{
Task.
await Task<T>();
}
}
";
ParseAndValidate(text,
// (7,9): error CS4003: 'await' cannot be used as an identifier within an async method or lambda expression
// await Task<T>();
Diagnostic(ErrorCode.ERR_BadAwaitAsIdentifier, "await").WithLocation(7, 9));
UsingTree(text);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalFunctionStatement);
{
N(SyntaxKind.QualifiedName);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Task");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "await");
}
}
N(SyntaxKind.IdentifierToken, "Task");
N(SyntaxKind.TypeParameterList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.TypeParameter);
{
N(SyntaxKind.IdentifierToken, "T");
}
N(SyntaxKind.GreaterThanToken);
}
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(15885, "https://github.com/dotnet/roslyn/pull/15885")]
public void InProgressLocalDeclaration8()
{
const string text = @"
class C
{
async void M()
{
Task.
await Task[1];
}
}
";
ParseAndValidate(text,
// (6,14): error CS1001: Identifier expected
// Task.
Diagnostic(ErrorCode.ERR_IdentifierExpected, "").WithLocation(6, 14),
// (6,14): error CS1002: ; expected
// Task.
Diagnostic(ErrorCode.ERR_SemicolonExpected, "").WithLocation(6, 14));
UsingTree(text);
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AsyncKeyword);
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Task");
}
N(SyntaxKind.DotToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
M(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.ExpressionStatement);
{
N(SyntaxKind.AwaitExpression);
{
N(SyntaxKind.AwaitKeyword);
N(SyntaxKind.ElementAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Task");
}
N(SyntaxKind.BracketedArgumentList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
N(SyntaxKind.CloseBracketToken);
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(377556, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=377556")]
public void TypeArgumentShiftAmbiguity_01()
{
const string text = @"
class C
{
void M()
{
//int a = 1;
//int i = 1;
var j = a < i >> 2;
}
}
";
var tree = UsingTree(text);
tree.GetDiagnostics().Verify();
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, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "j");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "2");
}
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(377556, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=377556")]
public void TypeArgumentShiftAmbiguity_02()
{
const string text = @"
class C
{
void M()
{
//const int a = 1;
//const int i = 2;
switch (false)
{
case a < i >> 2: break;
}
}
}
";
var tree = UsingTree(text);
tree.GetDiagnostics().Verify();
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, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SwitchStatement);
{
N(SyntaxKind.SwitchKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.FalseLiteralExpression);
{
N(SyntaxKind.FalseKeyword);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SwitchSection);
{
N(SyntaxKind.CaseSwitchLabel);
{
N(SyntaxKind.CaseKeyword);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "2");
}
}
}
N(SyntaxKind.ColonToken);
}
N(SyntaxKind.BreakStatement);
{
N(SyntaxKind.BreakKeyword);
N(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(377556, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=377556")]
public void TypeArgumentShiftAmbiguity_03()
{
const string text = @"
class C
{
void M()
{
M(out a < i >> 2);
}
}
";
var tree = UsingTree(text);
tree.GetDiagnostics().Verify();
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, "M");
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.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "2");
}
}
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(377556, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=377556")]
public void TypeArgumentShiftAmbiguity_04()
{
const string text = @"
class C
{
void M()
{
// (e is a<i>) > 2
var j = e is a < i >> 2;
}
}
";
var tree = UsingTree(text);
tree.GetDiagnostics().Verify();
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, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "j");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GreaterThanExpression);
{
N(SyntaxKind.IsExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.GenericName);
{
N(SyntaxKind.IdentifierToken, "a");
N(SyntaxKind.TypeArgumentList);
{
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.GreaterThanToken);
}
}
}
N(SyntaxKind.GreaterThanToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "2");
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(377556, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=377556")]
public void TypeArgumentShiftAmbiguity_05()
{
const string text = @"
class C
{
void M()
{
// syntax error
var j = e is a < i >>> 2;
}
}
";
var tree = UsingTree(text);
tree.GetDiagnostics().Verify(
// (7,30): error CS1525: Invalid expression term '>'
// var j = e is a < i >>> 2;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ">").WithArguments(">").WithLocation(7, 30)
);
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, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "j");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GreaterThanExpression);
{
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IsExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.GreaterThanGreaterThanToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
}
N(SyntaxKind.GreaterThanToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "2");
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact, WorkItem(377556, "https://devdiv.visualstudio.com/DefaultCollection/DevDiv/_workitems?id=377556")]
public void TypeArgumentShiftAmbiguity_06()
{
const string text = @"
class C
{
void M()
{
// syntax error
var j = e is a < i > << 2;
}
}
";
var tree = UsingTree(text);
tree.GetDiagnostics().Verify(
// (7,30): error CS1525: Invalid expression term '<<'
// var j = e is a < i > << 2;
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "<<").WithArguments("<<").WithLocation(7, 30)
);
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, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.LocalDeclarationStatement);
{
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "var");
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "j");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.GreaterThanExpression);
{
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IsExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.IsKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
}
N(SyntaxKind.GreaterThanToken);
N(SyntaxKind.LeftShiftExpression);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.LessThanLessThanToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "2");
}
}
}
}
}
}
N(SyntaxKind.SemicolonToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
public void TestTargetTypedDefaultWithCSharp7_1()
{
var text = "default";
var expr = this.ParseExpression(text, TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp7_1));
Assert.NotNull(expr);
Assert.Equal(SyntaxKind.DefaultLiteralExpression, expr.Kind());
Assert.Equal(text, expr.ToString());
Assert.Equal(0, expr.Errors().Length);
}
[Fact, WorkItem(17683, "https://github.com/dotnet/roslyn/issues/17683")]
public void Bug17683a()
{
var source =
@"from t in e
where
t == Int32.
MinValue
select t";
UsingExpression(source);
N(SyntaxKind.QueryExpression);
{
N(SyntaxKind.FromClause);
{
N(SyntaxKind.FromKeyword);
N(SyntaxKind.IdentifierToken, "t");
N(SyntaxKind.InKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
}
N(SyntaxKind.QueryBody);
{
N(SyntaxKind.WhereClause);
{
N(SyntaxKind.WhereKeyword);
N(SyntaxKind.EqualsExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "t");
}
N(SyntaxKind.EqualsEqualsToken);
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Int32");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "MinValue");
}
}
}
}
N(SyntaxKind.SelectClause);
{
N(SyntaxKind.SelectKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "t");
}
}
}
}
EOF();
}
[Fact]
public void Bug17683b()
{
var source =
@"switch (e)
{
case Int32.
MaxValue when true:
break;
}";
UsingStatement(source);
N(SyntaxKind.SwitchStatement);
{
N(SyntaxKind.SwitchKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SwitchSection);
{
N(SyntaxKind.CasePatternSwitchLabel);
{
N(SyntaxKind.CaseKeyword);
N(SyntaxKind.ConstantPattern);
{
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Int32");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "MaxValue");
}
}
}
N(SyntaxKind.WhenClause);
{
N(SyntaxKind.WhenKeyword);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
}
N(SyntaxKind.ColonToken);
}
N(SyntaxKind.BreakStatement);
{
N(SyntaxKind.BreakKeyword);
N(SyntaxKind.SemicolonToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
EOF();
}
[Fact, WorkItem(22830, "https://github.com/dotnet/roslyn/issues/22830")]
public void TypeArgumentIndexerInitializer()
{
UsingExpression("new C { [0] = op1 < op2, [1] = true }");
N(SyntaxKind.ObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.ObjectInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.ImplicitElementAccess);
{
N(SyntaxKind.BracketedArgumentList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.LessThanExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "op1");
}
N(SyntaxKind.LessThanToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "op2");
}
}
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.ImplicitElementAccess);
{
N(SyntaxKind.BracketedArgumentList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.TrueLiteralExpression);
{
N(SyntaxKind.TrueKeyword);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact, WorkItem(12214, "https://github.com/dotnet/roslyn/issues/12214")]
public void ConditionalExpressionInInterpolation()
{
UsingExpression("$\"{a ? b : d}\"",
// (1,4): error CS8361: A conditional expression cannot be used directly in a string interpolation because the ':' ends the interpolation. Parenthesize the conditional expression.
// $"{a ? b : d}"
Diagnostic(ErrorCode.ERR_ConditionalInInterpolation, "a ? b ").WithLocation(1, 4)
);
N(SyntaxKind.InterpolatedStringExpression);
{
N(SyntaxKind.InterpolatedStringStartToken);
N(SyntaxKind.Interpolation);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ConditionalExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
M(SyntaxKind.ColonToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.InterpolationFormatClause);
{
N(SyntaxKind.ColonToken);
N(SyntaxKind.InterpolatedStringTextToken);
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.InterpolatedStringEndToken);
}
EOF();
}
[Fact]
public void NullCoalescingAssignmentExpression()
{
UsingExpression("a ??= b");
N(SyntaxKind.CoalesceAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.QuestionQuestionEqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
EOF();
}
[Fact]
public void NullCoalescingAssignmentExpressionParenthesized()
{
UsingExpression("(a) ??= b");
N(SyntaxKind.CoalesceAssignmentExpression);
{
N(SyntaxKind.ParenthesizedExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.QuestionQuestionEqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
EOF();
}
[Fact]
public void NullCoalescingAssignmentExpressionInvocation()
{
UsingExpression("M(a) ??= b");
N(SyntaxKind.CoalesceAssignmentExpression);
{
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "M");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.Argument);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.QuestionQuestionEqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
EOF();
}
[Fact]
public void NullCoalescingAssignmentExpressionAndCoalescingOperator()
{
UsingExpression("a ?? b ??= c");
N(SyntaxKind.CoalesceAssignmentExpression);
{
N(SyntaxKind.CoalesceExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.QuestionQuestionToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
N(SyntaxKind.QuestionQuestionEqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "c");
}
}
EOF();
}
[Fact]
public void NullCoalescingAssignmentExpressionNested()
{
UsingExpression("a ??= b ??= c");
N(SyntaxKind.CoalesceAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.QuestionQuestionEqualsToken);
N(SyntaxKind.CoalesceAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.QuestionQuestionEqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "c");
}
}
}
EOF();
}
[Fact]
public void NullCoalescingAssignmentParenthesizedNested()
{
UsingExpression("(a ??= b) ??= c");
N(SyntaxKind.CoalesceAssignmentExpression);
{
N(SyntaxKind.ParenthesizedExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CoalesceAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.QuestionQuestionEqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.QuestionQuestionEqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "c");
}
}
EOF();
}
[Fact]
public void NullCoalescingAssignmentCSharp7_3()
{
UsingExpression("a ??= b", TestOptions.Regular7_3,
// (1,3): error CS8652: The feature 'coalescing assignment' is not available in C# 7.3. Please use language version 8.0 or greater.
// a ??= b
Diagnostic(ErrorCode.ERR_FeatureNotAvailableInVersion7_3, "??=").WithArguments("coalescing assignment", "8.0").WithLocation(1, 3));
N(SyntaxKind.CoalesceAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.QuestionQuestionEqualsToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
EOF();
}
[Fact]
public void IndexExpression()
{
UsingExpression("^1");
N(SyntaxKind.IndexExpression);
{
N(SyntaxKind.CaretToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
EOF();
}
[Fact]
public void RangeExpression_ThreeDots()
{
UsingExpression("1...2",
// (1,2): error CS8401: Unexpected character sequence '...'
// 1...2
Diagnostic(ErrorCode.ERR_TripleDotNotAllowed, "").WithLocation(1, 2));
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
N(SyntaxKind.DotDotToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, ".2");
}
}
EOF();
}
[Fact]
public void RangeExpression_Binary()
{
UsingExpression("1..1");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
N(SyntaxKind.DotDotToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
EOF();
}
[Fact]
public void RangeExpression_Binary_WithIndexes()
{
UsingExpression("^5..^3");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IndexExpression);
{
N(SyntaxKind.CaretToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "5");
}
}
N(SyntaxKind.DotDotToken);
N(SyntaxKind.IndexExpression);
{
N(SyntaxKind.CaretToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "3");
}
}
}
EOF();
}
[Fact]
public void RangeExpression_Binary_WithALowerPrecedenceOperator()
{
UsingExpression("1<<2..3>>4");
N(SyntaxKind.RightShiftExpression);
{
N(SyntaxKind.LeftShiftExpression);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
N(SyntaxKind.LessThanLessThanToken);
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "2");
}
N(SyntaxKind.DotDotToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "3");
}
}
}
N(SyntaxKind.GreaterThanGreaterThanToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "4");
}
}
EOF();
}
[Fact]
public void RangeExpression_Binary_WithAHigherPrecedenceOperator()
{
UsingExpression("1+2..3-4");
N(SyntaxKind.SubtractExpression);
{
N(SyntaxKind.AddExpression);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
N(SyntaxKind.PlusToken);
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "2");
}
N(SyntaxKind.DotDotToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "3");
}
}
}
N(SyntaxKind.MinusToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "4");
}
}
EOF();
}
[Fact]
public void RangeExpression_UnaryBadLeft()
{
UsingExpression("a*..b");
N(SyntaxKind.MultiplyExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.AsteriskToken);
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
}
EOF();
}
[Fact]
public void RangeExpression_BinaryLeftPlus()
{
UsingExpression("a + b..c");
N(SyntaxKind.AddExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.PlusToken);
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.DotDotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "c");
}
}
}
EOF();
}
[Fact]
public void RangeExpression_UnaryLeftPlus()
{
UsingExpression("a + b..");
N(SyntaxKind.AddExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.PlusToken);
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.DotDotToken);
}
}
EOF();
}
[Fact]
public void RangeExpression_UnaryRightMult()
{
UsingExpression("a.. && b");
N(SyntaxKind.LogicalAndExpression);
{
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.DotDotToken);
}
N(SyntaxKind.AmpersandAmpersandToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
EOF();
}
[Fact]
public void RangeExpression_UnaryRightMult2()
{
UsingExpression("..a && b");
N(SyntaxKind.LogicalAndExpression);
{
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
}
N(SyntaxKind.AmpersandAmpersandToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
EOF();
}
[Fact]
public void RangeExpression_Ambiguity1()
{
UsingExpression(".. ..");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
}
}
EOF();
}
[Fact]
public void RangeExpression_Ambiguity2()
{
UsingExpression(".. .. e");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
}
}
EOF();
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/36514")]
public void RangeExpression_Ambiguity3()
{
UsingExpression(".. e ..");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "e");
}
N(SyntaxKind.DotDotToken);
}
}
EOF();
}
[Fact]
public void RangeExpression_Ambiguity4()
{
UsingExpression("a .. .. b");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.DotDotToken);
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
}
EOF();
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/36514")]
public void RangeExpression_Ambiguity5()
{
UsingExpression("a .. b ..");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.DotDotToken);
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.DotDotToken);
}
}
EOF();
}
[Fact(Skip = "https://github.com/dotnet/roslyn/issues/36514")]
public void RangeExpression_Ambiguity6()
{
UsingExpression("a .. b .. c");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "a");
}
N(SyntaxKind.DotDotToken);
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
N(SyntaxKind.DotDotToken);
}
}
EOF();
}
[Fact, WorkItem(36122, "https://github.com/dotnet/roslyn/issues/36122")]
public void RangeExpression_NotCast()
{
UsingExpression("(Offset)..(Offset + Count)");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.ParenthesizedExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Offset");
}
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.DotDotToken);
N(SyntaxKind.ParenthesizedExpression);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.AddExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Offset");
}
N(SyntaxKind.PlusToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Count");
}
}
N(SyntaxKind.CloseParenToken);
}
}
EOF();
}
[Fact]
public void RangeExpression_Right()
{
UsingExpression("..1");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
}
EOF();
}
[Fact]
public void RangeExpression_Right_WithIndexes()
{
UsingExpression("..^3");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
N(SyntaxKind.IndexExpression);
{
N(SyntaxKind.CaretToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "3");
}
}
}
EOF();
}
[Fact]
public void RangeExpression_Left()
{
UsingExpression("1..");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
N(SyntaxKind.DotDotToken);
}
EOF();
}
[Fact]
public void RangeExpression_Left_WithIndexes()
{
UsingExpression("^5..");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.IndexExpression);
{
N(SyntaxKind.CaretToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "5");
}
}
N(SyntaxKind.DotDotToken);
}
EOF();
}
[Fact]
public void RangeExpression_NoOperands()
{
UsingExpression("..");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
}
EOF();
}
[Fact]
public void RangeExpression_NoOperands_WithOtherOperators()
{
UsingExpression("1+..<<2");
N(SyntaxKind.LeftShiftExpression);
{
N(SyntaxKind.AddExpression);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
N(SyntaxKind.PlusToken);
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
}
}
N(SyntaxKind.LessThanLessThanToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "2");
}
}
EOF();
}
[Fact]
public void RangeExpression_DotSpaceDot()
{
UsingExpression("1. .2",
// (1,1): error CS1073: Unexpected token '.2'
// 1. .2
Diagnostic(ErrorCode.ERR_UnexpectedToken, "1. ").WithArguments(".2").WithLocation(1, 1),
// (1,4): error CS1001: Identifier expected
// 1. .2
Diagnostic(ErrorCode.ERR_IdentifierExpected, ".2").WithLocation(1, 4));
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
N(SyntaxKind.DotToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
EOF();
}
[Fact]
public void RangeExpression_MethodInvocation_NoOperands()
{
UsingExpression(".. .ToString()",
// (1,1): error CS1073: Unexpected token '.'
// .. .ToString()
Diagnostic(ErrorCode.ERR_UnexpectedToken, "..").WithArguments(".").WithLocation(1, 1));
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
}
EOF();
}
[Fact]
public void RangeExpression_MethodInvocation_LeftOperand()
{
UsingExpression("1.. .ToString()",
// (1,1): error CS1073: Unexpected token '.'
// 1.. .ToString()
Diagnostic(ErrorCode.ERR_UnexpectedToken, "1..").WithArguments(".").WithLocation(1, 1));
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
N(SyntaxKind.DotDotToken);
}
EOF();
}
[Fact]
public void RangeExpression_MethodInvocation_RightOperand()
{
UsingExpression("..2 .ToString()");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "2");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ToString");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
}
}
EOF();
}
[Fact]
public void RangeExpression_MethodInvocation_TwoOperands()
{
UsingExpression("1..2 .ToString()");
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "1");
}
N(SyntaxKind.DotDotToken);
N(SyntaxKind.InvocationExpression);
{
N(SyntaxKind.SimpleMemberAccessExpression);
{
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "2");
}
N(SyntaxKind.DotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "ToString");
}
N(SyntaxKind.ArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
}
}
}
EOF();
}
[Fact]
public void RangeExpression_ConditionalAccessExpression()
{
UsingExpression("c?..b",
// (1,6): error CS1003: Syntax error, ':' expected
// c?..b
Diagnostic(ErrorCode.ERR_SyntaxError, "").WithArguments(":", "").WithLocation(1, 6),
// (1,6): error CS1733: Expected expression
// c?..b
Diagnostic(ErrorCode.ERR_ExpressionExpected, "").WithLocation(1, 6));
N(SyntaxKind.ConditionalExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "c");
}
N(SyntaxKind.QuestionToken);
N(SyntaxKind.RangeExpression);
{
N(SyntaxKind.DotDotToken);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "b");
}
}
M(SyntaxKind.ColonToken);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
EOF();
}
[Fact]
public void BaseExpression_01()
{
UsingExpression("base");
N(SyntaxKind.BaseExpression);
{
N(SyntaxKind.BaseKeyword);
}
EOF();
}
[Fact]
[WorkItem(39072, "https://github.com/dotnet/roslyn/issues/39072")]
public void ArrayCreation_BadRef()
{
UsingExpression("new[] { ref }",
// (1,9): error CS1525: Invalid expression term 'ref'
// new[] { ref }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref ").WithArguments("ref").WithLocation(1, 9),
// (1,13): error CS1525: Invalid expression term '}'
// new[] { ref }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(1, 13));
N(SyntaxKind.ImplicitArrayCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.CloseBracketToken);
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
[WorkItem(39072, "https://github.com/dotnet/roslyn/issues/39072")]
public void ArrayCreation_BadRefExpression()
{
UsingExpression("new[] { ref obj }",
// (1,9): error CS1525: Invalid expression term 'ref'
// new[] { ref obj }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref obj").WithArguments("ref").WithLocation(1, 9));
N(SyntaxKind.ImplicitArrayCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.CloseBracketToken);
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "obj");
}
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
[WorkItem(39072, "https://github.com/dotnet/roslyn/issues/39072")]
public void ArrayCreation_BadRefElementAccess()
{
UsingExpression("new[] { ref[] }",
// (1,9): error CS1525: Invalid expression term 'ref'
// new[] { ref[] }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref[]").WithArguments("ref").WithLocation(1, 9),
// (1,12): error CS1525: Invalid expression term '['
// new[] { ref[] }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "[").WithArguments("[").WithLocation(1, 12),
// (1,13): error CS0443: Syntax error; value expected
// new[] { ref[] }
Diagnostic(ErrorCode.ERR_ValueExpected, "]").WithLocation(1, 13));
N(SyntaxKind.ImplicitArrayCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.CloseBracketToken);
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
N(SyntaxKind.ElementAccessExpression);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
N(SyntaxKind.BracketedArgumentList);
{
N(SyntaxKind.OpenBracketToken);
M(SyntaxKind.Argument);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.CloseBracketToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
[WorkItem(39072, "https://github.com/dotnet/roslyn/issues/39072")]
public void AnonymousObjectCreation_BadRef()
{
UsingExpression("new { ref }",
// (1,7): error CS1525: Invalid expression term 'ref'
// new { ref }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref ").WithArguments("ref").WithLocation(1, 7),
// (1,11): error CS1525: Invalid expression term '}'
// new { ref }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(1, 11));
N(SyntaxKind.AnonymousObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.AnonymousObjectMemberDeclarator);
{
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
EOF();
}
[Fact]
[WorkItem(39072, "https://github.com/dotnet/roslyn/issues/39072")]
public void ObjectInitializer_BadRef()
{
UsingExpression("new C { P = ref }",
// (1,13): error CS1525: Invalid expression term 'ref'
// new C { P = ref }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref ").WithArguments("ref").WithLocation(1, 13),
// (1,17): error CS1525: Invalid expression term '}'
// new C { P = ref }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(1, 17));
N(SyntaxKind.ObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.ObjectInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.SimpleAssignmentExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "P");
}
N(SyntaxKind.EqualsToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
[WorkItem(39072, "https://github.com/dotnet/roslyn/issues/39072")]
public void CollectionInitializer_BadRef_01()
{
UsingExpression("new C { ref }",
// (1,9): error CS1525: Invalid expression term 'ref'
// new C { ref }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref ").WithArguments("ref").WithLocation(1, 9),
// (1,13): error CS1525: Invalid expression term '}'
// new C { ref }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(1, 13));
N(SyntaxKind.ObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.CollectionInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
[WorkItem(39072, "https://github.com/dotnet/roslyn/issues/39072")]
public void CollectionInitializer_BadRef_02()
{
UsingExpression("new C { { 0, ref } }",
// (1,14): error CS1525: Invalid expression term 'ref'
// new C { { 0, ref } }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref ").WithArguments("ref").WithLocation(1, 14),
// (1,18): error CS1525: Invalid expression term '}'
// new C { { 0, ref } }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "}").WithArguments("}").WithLocation(1, 18));
N(SyntaxKind.ObjectCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "C");
}
N(SyntaxKind.CollectionInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ComplexElementInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
N(SyntaxKind.CommaToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
[WorkItem(39072, "https://github.com/dotnet/roslyn/issues/39072")]
public void AttributeArgument_BadRef()
{
UsingTree("class C { [Attr(ref)] void M() { } }").GetDiagnostics().Verify(
// (1,17): error CS1525: Invalid expression term 'ref'
// class C { [Attr(ref)] void M() { } }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref").WithArguments("ref").WithLocation(1, 17),
// (1,20): error CS1525: Invalid expression term ')'
// class C { [Attr(ref)] void M() { } }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ")").WithArguments(")").WithLocation(1, 20));
N(SyntaxKind.CompilationUnit);
{
N(SyntaxKind.ClassDeclaration);
{
N(SyntaxKind.ClassKeyword);
N(SyntaxKind.IdentifierToken, "C");
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.MethodDeclaration);
{
N(SyntaxKind.AttributeList);
{
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.Attribute);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "Attr");
}
N(SyntaxKind.AttributeArgumentList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.AttributeArgument);
{
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
}
N(SyntaxKind.CloseParenToken);
}
}
N(SyntaxKind.CloseBracketToken);
}
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.VoidKeyword);
}
N(SyntaxKind.IdentifierToken, "M");
N(SyntaxKind.ParameterList);
{
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.CloseParenToken);
}
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
N(SyntaxKind.EndOfFileToken);
}
EOF();
}
[Fact]
[WorkItem(39072, "https://github.com/dotnet/roslyn/issues/39072")]
public void ForLoop_BadRefCondition()
{
UsingStatement("for (int i = 0; ref; i++) { }",
// (1,17): error CS1525: Invalid expression term 'ref'
// for (int i = 0; ref; i++) { }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, "ref").WithArguments("ref").WithLocation(1, 17),
// (1,20): error CS1525: Invalid expression term ';'
// for (int i = 0; ref; i++) { }
Diagnostic(ErrorCode.ERR_InvalidExprTerm, ";").WithArguments(";").WithLocation(1, 20));
N(SyntaxKind.ForStatement);
{
N(SyntaxKind.ForKeyword);
N(SyntaxKind.OpenParenToken);
N(SyntaxKind.VariableDeclaration);
{
N(SyntaxKind.PredefinedType);
{
N(SyntaxKind.IntKeyword);
}
N(SyntaxKind.VariableDeclarator);
{
N(SyntaxKind.IdentifierToken, "i");
N(SyntaxKind.EqualsValueClause);
{
N(SyntaxKind.EqualsToken);
N(SyntaxKind.NumericLiteralExpression);
{
N(SyntaxKind.NumericLiteralToken, "0");
}
}
}
}
N(SyntaxKind.SemicolonToken);
N(SyntaxKind.RefExpression);
{
N(SyntaxKind.RefKeyword);
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.SemicolonToken);
N(SyntaxKind.PostIncrementExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "i");
}
N(SyntaxKind.PlusPlusToken);
}
N(SyntaxKind.CloseParenToken);
N(SyntaxKind.Block);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
[WorkItem(39072, "https://github.com/dotnet/roslyn/issues/39072")]
public void ArrayCreation_BadInElementAccess()
{
UsingExpression("new[] { in[] }",
// (1,9): error CS1003: Syntax error, ',' expected
// new[] { in[] }
Diagnostic(ErrorCode.ERR_SyntaxError, "in").WithArguments(",", "in").WithLocation(1, 9));
N(SyntaxKind.ImplicitArrayCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.CloseBracketToken);
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
[WorkItem(39072, "https://github.com/dotnet/roslyn/issues/39072")]
public void ArrayCreation_BadOutElementAccess()
{
UsingExpression("new[] { out[] }",
// (1,9): error CS1003: Syntax error, ',' expected
// new[] { out[] }
Diagnostic(ErrorCode.ERR_SyntaxError, "out").WithArguments(",", "out").WithLocation(1, 9));
N(SyntaxKind.ImplicitArrayCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.CloseBracketToken);
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
[Fact]
[WorkItem(39072, "https://github.com/dotnet/roslyn/issues/39072")]
public void ArrayCreation_ElementAccess()
{
UsingExpression("new[] { obj[] }",
// (1,13): error CS0443: Syntax error; value expected
// new[] { obj[] }
Diagnostic(ErrorCode.ERR_ValueExpected, "]").WithLocation(1, 13));
N(SyntaxKind.ImplicitArrayCreationExpression);
{
N(SyntaxKind.NewKeyword);
N(SyntaxKind.OpenBracketToken);
N(SyntaxKind.CloseBracketToken);
N(SyntaxKind.ArrayInitializerExpression);
{
N(SyntaxKind.OpenBraceToken);
N(SyntaxKind.ElementAccessExpression);
{
N(SyntaxKind.IdentifierName);
{
N(SyntaxKind.IdentifierToken, "obj");
}
N(SyntaxKind.BracketedArgumentList);
{
N(SyntaxKind.OpenBracketToken);
M(SyntaxKind.Argument);
{
M(SyntaxKind.IdentifierName);
{
M(SyntaxKind.IdentifierToken);
}
}
N(SyntaxKind.CloseBracketToken);
}
}
N(SyntaxKind.CloseBraceToken);
}
}
EOF();
}
}
}
| 45.359052 | 19,566 | 0.481277 | [
"MIT"
] | rstarkov/roslyn | src/Compilers/CSharp/Test/Syntax/Parsing/ExpressionParsingTests.cs | 241,038 | C# |
// ------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License (MIT). See LICENSE in the repo root for license information.
// ------------------------------------------------------------
using System;
using Microsoft.OData.Edm;
using Microsoft.OpenApi.OData.Edm;
using Microsoft.OpenApi.OData.Tests;
using Xunit;
namespace Microsoft.OpenApi.OData.Generator.Tests
{
public class OpenApiPathsGeneratorTest
{
private OpenApiConvertSettings _settings = new OpenApiConvertSettings();
[Fact]
public void CreatePathsThrowArgumentNullContext()
{
// Arrange
ODataContext context = null;
// Act & Assert
Assert.Throws<ArgumentNullException>("context", () => context.CreatePaths());
}
[Fact]
public void CreatePathsReturnsForEmptyModel()
{
// Arrange
IEdmModel model = EdmModelHelper.EmptyModel;
ODataContext context = new ODataContext(model);
// Act
var paths = context.CreatePaths();
// Assert
Assert.NotNull(paths);
Assert.Empty(paths);
}
[Fact]
public void CreatePathsReturnsForBasicModel()
{
// Arrange
IEdmModel model = EdmModelHelper.BasicEdmModel;
OpenApiConvertSettings settings = new OpenApiConvertSettings
{
EnableKeyAsSegment = true
};
ODataContext context = new ODataContext(model, settings);
// Act
var paths = context.CreatePaths();
// Assert
Assert.NotNull(paths);
Assert.Equal(7, paths.Count);
Assert.Contains("/People", paths.Keys);
Assert.Contains("/People/{UserName}", paths.Keys);
Assert.Contains("/City", paths.Keys);
Assert.Contains("/City/{Name}", paths.Keys);
Assert.Contains("/CountryOrRegion", paths.Keys);
Assert.Contains("/CountryOrRegion/{Name}", paths.Keys);
Assert.Contains("/Me", paths.Keys);
}
[Fact]
public void CreatePathsReturnsForContractModelWithHierarhicalClass()
{
// Arrange
IEdmModel model = EdmModelHelper.ContractServiceModel;
OpenApiConvertSettings settings = new OpenApiConvertSettings
{
EnableKeyAsSegment = true,
EnableUnqualifiedCall = true
};
ODataContext context = new ODataContext(model, settings);
// Act
var paths = context.CreatePaths();
// Assert
Assert.NotNull(paths);
Assert.Equal(4, paths.Count);
Assert.Contains("/Accounts", paths.Keys);
Assert.Contains("/Accounts/{id}", paths.Keys);
Assert.Contains("/Accounts/{id}/Attachments()", paths.Keys);
Assert.Contains("/Accounts/{id}/AttachmentsAdd", paths.Keys);
}
}
}
| 32.458333 | 95 | 0.556162 | [
"MIT"
] | SenyaMur/OpenAPI.NET.OData | test/Microsoft.OpenAPI.OData.Reader.Tests/Generator/OpenApiPathsGeneratorTests.cs | 3,118 | C# |
using System.Collections.Generic;
using Umbraco.Core;
namespace uSync8.Core
{
public static class ListExtensions
{
/// <summary>
/// Add item to list if the item is not null
/// </summary>
public static void AddNotNull<TObject>(this List<TObject> list, TObject item)
{
if (item == null) return;
list.Add(item);
}
/// <summary>
/// Is the value valid for this list (if the list is empty, we treat it like a wildcard).
/// </summary>
public static bool IsValid(this IList<string> list, string value)
=> list.Count == 0 || list.InvariantContains(value) || list.InvariantContains("*");
public static bool IsValidOrBlank(this IList<string> list, string value)
=> string.IsNullOrWhiteSpace(value) || list.IsValid(value);
}
}
| 31.178571 | 98 | 0.599084 | [
"MPL-2.0",
"MPL-2.0-no-copyleft-exception"
] | JoseMarcenaro/uSync8 | uSync8.Core/Extensions/ListExtensions.cs | 875 | C# |
using Apocalypse.Any.Domain.Common.Model;
using System;
namespace Apocalypse.Any.Infrastructure.Server.Services.Mechanics.Language
{
public class MechanicSingleEntityWithSingleTargetArgs<TEntity, TTargetEntity>
: MechanicSingleEntityArgs<TEntity>
where TEntity : CharacterEntity, new()
where TTargetEntity : CharacterEntity, new()
{
public TTargetEntity Target { get; private set; }
public MechanicSingleEntityWithSingleTargetArgs(
TEntity subjectEntity,
TTargetEntity targetEntity) : base(subjectEntity)
{
if (targetEntity == null)
throw new ArgumentNullException(nameof(targetEntity));
Target = targetEntity;
}
}
} | 33.545455 | 81 | 0.691057 | [
"MIT"
] | inidibininging/apocalypse_netcore | Apocalypse.Any.Infrastructure.Server.Services.Mechanics/Language/MechanicSingleEntityWithSingleTargetArgs.cs | 738 | C# |
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See License.txt in the project root for license information.
#nullable disable
using System;
namespace Microsoft.CodeAnalysis.Razor.ProjectSystem
{
[Flags]
internal enum ProjectDifference
{
None = 0,
ConfigurationChanged = 1,
ProjectWorkspaceStateChanged = 2,
DocumentAdded = 4,
DocumentRemoved = 8,
DocumentChanged = 16,
}
}
| 23.047619 | 95 | 0.673554 | [
"MIT"
] | 50Wliu/razor-tooling | src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/ProjectSystem/ProjectDifference.cs | 486 | C# |
using System;
using System.Collections.Generic;
using LavaLeak.Diplomata.Models;
namespace LavaLeak.Diplomata
{
/// <summary>
/// Interactable game objects component class.
/// </summary>
[Serializable]
public class DiplomataInteractable : DiplomataTalkable
{
/// <summary>
/// Set the main talkable fields.
/// </summary>
private void Start()
{
choices = new List<Message>();
controlIndexes = new Dictionary<string, int>();
controlIndexes.Add("context", 0);
controlIndexes.Add("column", 0);
controlIndexes.Add("message", 0);
}
}
}
| 22.296296 | 56 | 0.649502 | [
"MIT"
] | MoonAntonio/diplomata-unity | Runtime/DiplomataInteractable.cs | 602 | C# |
namespace Qooba.Framework.Bot.Abstractions.Models.Buttons
{
public enum RequestedUserInfo
{
shipping_address,
contact_name,
contact_phone,
contact_email
}
} | 20.1 | 58 | 0.656716 | [
"MIT"
] | qooba/Qooba.Framework | src/Qooba.Framework.Bot.Abstractions/Models/Buttons/RequestedUserInfo.cs | 203 | C# |
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;
using Orleans;
using Orleans.Configuration;
using Orleans.Hosting;
using System;
using System.Net;
using System.Reflection;
using System.Threading.Tasks;
namespace HelloWrold.AdoNetClustering
{
class Program
{
public static async Task Main(string[] args)
{
//初始化SQL:http://dotnet.github.io/orleans/Documentation/clusters_and_clients/configuration_guide/adonet_configuration.html
var invariant = "Microsoft.Data.SqlClient";
var connectionString = "Data Source=127.0.0.1;Initial Catalog=Orleans;User Id=sa;Password=123456;";
await Host.CreateDefaultBuilder(args)
.UseOrleans(builder =>
{
builder
.UseAdoNetClustering(options =>
{
options.ConnectionString = connectionString;
options.Invariant = invariant;
})
.Configure<ClusterOptions>(options =>
{
options.ClusterId = "orleans.test";
options.ServiceId = "orleans.test";
})
.Configure<ClusterMembershipOptions>(options =>
{
//及时下线
options.ProbeTimeout = TimeSpan.FromSeconds(3);
options.IAmAliveTablePublishTimeout = TimeSpan.FromSeconds(3);
options.NumVotesForDeathDeclaration = 1;
})
.Configure<EndpointOptions>(options =>
{
options.AdvertisedIPAddress = IPAddress.Loopback;
})
.ConfigureApplicationParts(x => x.AddApplicationPart(Assembly.GetEntryAssembly()))
.AddAdoNetGrainStorageAsDefault(options =>
{
options.ConnectionString = connectionString;
options.Invariant = invariant;
});
})
.ConfigureServices(services =>
{
services.AddHostedService<Bootstrapper>();
})
.ConfigureLogging(builder =>
{
builder.AddConsole(options =>
{
options.TimestampFormat = "HH:mm:ss.fff";
});
})
.RunConsoleAsync();
}
}
}
| 39.695652 | 133 | 0.487039 | [
"MIT"
] | Coldairarrow/OrleansDemo | HelloWrold.AdoNetClustering/Program.cs | 2,755 | C# |
namespace SMS.Net.Channel.RavenSMS.Pages;
/// <summary>
/// holds the view data keys
/// </summary>
internal static class ViewDataKeys
{
public const string PageTitle = "page_title";
public const string SelectedPage = "selected_page";
} | 24.6 | 55 | 0.723577 | [
"MIT"
] | YoussefSell/SMS.Net | src/SmsDeliveryChannels/SMS.Net.RavenSMS/SMS.Net.RavenSMS/Core/Constants/ViewDataKeys.cs | 248 | C# |
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.IO;
using System.Net;
using System.Text.RegularExpressions;
using System.Windows.Forms;
namespace Practica3
{
public partial class Vnt_consultador : Form
{
public Vnt_consultador()
{
InitializeComponent();
}
private void btn_consulta_Click(object sender, EventArgs e)
{
String url = txt_url.Text;
getIP(url);
}
private void getIP(String url) {
IPAddress[] addresses = Dns.GetHostAddresses(url);
Console.WriteLine($"GetHostAddresses({url}) returns:");
foreach (IPAddress address in addresses)
{
lbl_informacion.Text = "La direccion IP es: " + $" {address}";
}
}
private void btn_clean_Click(object sender, EventArgs e)
{
txt_url.Text = "";
lbl_informacion.Text = "";
}
private void txt_url_TextChanged(object sender, EventArgs e)
{
txt_url.Text = "";
}
private void txt_url_Click(object sender, EventArgs e)
{
txt_url.Text = "";
txt_url.ForeColor = Color.Black;
}
private void txt_url_AcceptsTabChanged(object sender, EventArgs e)
{
txt_url.ForeColor = Color.Black;
}
private void txt_url_KeyDown(object sender, KeyEventArgs e)
{
txt_url.ForeColor = Color.Black;
}
}
}
| 24.26087 | 81 | 0.583632 | [
"MIT"
] | WicasZ/TopicosC_ | Consultador/Practica3/Form1.cs | 1,676 | C# |
using Breakout.Core.Models.Balls;
using Breakout.Core.Models.Enums;
using Breakout.Core.Utilities.Audio;
using Microsoft.Xna.Framework;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System;
using System.Collections.Specialized;
using Breakout.Extensions;
namespace Breakout.Core.Models.Paddles
{
public struct TrackedBall
{
public Ball Instance { get; set; }
public float ContactArea { get; set; }
}
public class MagnetizedPaddle : Paddle
{
public ObservableCollection<TrackedBall> TrackedBalls { get; private set; }
public MagnetizedPaddle(Scene scene, int height) : base(scene, height)
{
TrackedBalls = new ObservableCollection<TrackedBall>();
TrackedBalls.CollectionChanged += OnTrackedBallsChanged;
}
private void OnTrackedBallsChanged(object sender, NotifyCollectionChangedEventArgs e)
{
if (e.Action == NotifyCollectionChangedAction.Add)
{
foreach (TrackedBall trackedBall in e.NewItems)
{
var ball = trackedBall.Instance;
ball.IsAttached = true;
ball.Position.Y = Position.Y - ball.Height;
}
}
if (e.Action == NotifyCollectionChangedAction.Remove)
{
foreach (TrackedBall trackedBall in e.OldItems)
{
var ball = trackedBall.Instance;
ball.IsAttached = false;
ball.Angle = this.GetBounceBackAngle(trackedBall.ContactArea);
}
}
}
public override void HandleBall(Ball ball)
{
if (IsTouching(ball))
{
Hit(ball);
if (!TrackedBalls.Any(trackedBall => trackedBall.Instance.Equals(ball)))
{
ball.Position.Y = Position.Y - ball.Height;
TrackedBall trackedBall = new TrackedBall();
trackedBall.Instance = ball;
trackedBall.ContactArea = GetPaddleContactArea(ball);
TrackedBalls.Add(trackedBall);
}
}
foreach (var trackedBall in TrackedBalls)
{
var ballInstance = trackedBall.Instance;
ballInstance.Position.X = Position.X + MathHelper.Lerp(0, Width, trackedBall.ContactArea);
}
}
public void Release()
{
Hit(null);
TrackedBalls.RemoveAll();
}
public override void Hit(object src)
{
AudioManager.PlaySound("HitMagnetizedPaddle", percent: scene.Volume);
}
}
}
| 23.410526 | 94 | 0.711331 | [
"BSD-3-Clause"
] | NearHuscarl/Breakout | src/Breakout.Core/Models/Paddles/MagnetizedPaddle.cs | 2,226 | C# |
using System;
using System.Drawing;
using System.Windows.Forms;
using System.Diagnostics;
namespace FontConv
{
/*
* main form
*/
public partial class FormMain : Form {
/*
* members
*/
private SizedFont _sizedFont;
/*
* constructor
*/
public FormMain() {
InitializeComponent();
}
private void RefillCharsPanel() {
FontChar fc;
try {
_charsPanel.SuspendLayout();
// empty panel
_charsPanel.Controls.Clear();
// add new. not particularly fast.
using(Graphics g=CreateGraphics()) {
foreach(FontUtil.FontRange fr in FontUtil.GetFontUnicodeRanges(_sizedFont.GdiFont)) {
for(UInt16 code=fr.Low;code<=fr.High;code++) {
char c;
int width;
fc=new FontChar(_tooltip);
c=Convert.ToChar(code);
// special case for space which we map to the width of a "-"
width=(int)g.MeasureString(c==' ' ? "-" : c.ToString(),_sizedFont.GdiFont,PointF.Empty,StringFormat.GenericTypographic).Width;
fc.Text=c.ToString();
fc.Font=_sizedFont.GdiFont;
fc.Size=new Size(width,_sizedFont.Size);
fc.Selected=_sizedFont.ContainsChar(c);
fc.Click+=OnClickFontChar;
fc.Tag=c;
_charsPanel.Controls.Add(fc);
}
}
}
_preview.Font=_sizedFont.GdiFont;
RefillPreviews();
}
finally {
_charsPanel.ResumeLayout();
}
}
/*
* refill previews panel
*/
private void RefillPreviews() {
// refill the list
_previewPanel.Controls.Clear();
foreach(CharPreview cp in _sizedFont.CreatePreviews())
_previewPanel.Controls.Add(cp);
}
/*
* font char clicked
*/
private void OnClickFontChar(object sender,EventArgs args)
{
FontChar fc;
try
{
// get values
fc=(FontChar)sender;
// toggle select
_sizedFont.ToggleSelected(fc.Text[0]);
// select control
fc.Selected^=true;
fc.Invalidate();
// add/remove from the previews
if(fc.Selected)
AddPreview(fc.Text[0]);
else
RemovePreview(fc.Text[0]);
}
catch(Exception ex) {
Util.Error(ex);
}
}
/*
* add a preview
*/
private void AddPreview(char c) {
_previewPanel.Controls.Add(_sizedFont.CreatePreview(c));
}
/*
* remove preview
*/
private void RemovePreview(char c) {
foreach(CharPreview cp in _previewPanel.Controls) {
if((char)cp.Tag==c) {
_previewPanel.Controls.Remove(cp);
return;
}
}
}
/*
* offset changed
*/
private void _xoffset_ValueChanged(object sender,EventArgs e) {
try {
_sizedFont.XOffset=(int)_xoffset.Value;
RefillPreviews();
}
catch(Exception ex) {
Util.Error(ex);
}
}
/*
* Y offset changed
*/
private void _yoffset_ValueChanged(object sender,EventArgs e) {
try {
_sizedFont.YOffset=(int)_yoffset.Value;
RefillPreviews();
}
catch(Exception ex) {
Util.Error(ex);
}
}
/*
* extra lines changed
*/
private void _extraLines_ValueChanged(object sender,EventArgs e) {
try {
_sizedFont.ExtraLines=(int)_extraLines.Value;
RefillPreviews();
}
catch(Exception ex) {
Util.Error(ex);
}
}
/*
* Character space changed
*/
private void _charSpace_ValueChanged(object sender,EventArgs e)
{
try {
_sizedFont.CharSpace=(int)_charSpace.Value;
}
catch(Exception ex) {
Util.Error(ex);
}
}
/*
* Browse for font file
*/
private void _btnBrowseFontFile_Click(object sender,EventArgs e) {
try {
// browse for font
if(_openFontFileDialog.ShowDialog(this)==DialogResult.Cancel)
return;
// set the filename
_editFontFile.Text=_openFontFileDialog.FileName;
// create the font
_sizedFont=new SizedFont(_openFontFileDialog.FileName,Convert.ToInt32(_fontSize.Value));
_preview.Font=_sizedFont.GdiFont;
_preview.Invalidate();
EnableControls();
RefillCharsPanel();
}
catch(Exception ex) {
Util.Error(ex);
}
}
/*
* Enable/disable controls
*/
private void EnableControls() {
bool enable;
enable=_sizedFont!=null;
_extraLines.Enabled=enable;
_charSpace.Enabled=enable;
_xoffset.Enabled=enable;
_yoffset.Enabled=enable;
_btnSave.Enabled=enable;
_btnSelectAlpha.Enabled=enable;
_btnSelect7Bit.Enabled=enable;
}
/*
* Check if char is valid
*/
private bool IsValidChar(char c) {
foreach(FontChar fc in _charsPanel.Controls)
if((char)fc.Tag==c)
return true;
return false;
}
/*
* Select all alphanumeric
*/
private void _btnSelectAlpha_Click(object sender,EventArgs e)
{
String alphanum="ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz01234567890";
try {
Cursor.Current=Cursors.WaitCursor;
foreach(char c in alphanum)
if(IsValidChar(c))
_sizedFont.Add(c);
RefillCharsPanel();
}
catch(Exception ex) {
Util.Error(ex);
}
finally {
Cursor.Current=Cursors.Default;
}
}
/*
* Select 7 bit chars
*/
private void _btnSelect7Bit_Click(object sender,EventArgs e) {
char c;
try {
Cursor.Current=Cursors.WaitCursor;
for(c=(char)32;c<=(char)127;c++)
if(IsValidChar(c))
_sizedFont.Add(c);
RefillCharsPanel();
}
catch(Exception ex) {
Util.Error(ex);
}
finally {
Cursor.Current=Cursors.Default;
}
}
/*
* New font size
*/
private void _fontSize_ValueChanged(object sender,EventArgs e) {
try {
_sizedFont.Size=Convert.ToInt32(_fontSize.Value);
_sizedFont.CreateFont();
RefillCharsPanel();
}
catch(Exception ex) {
Util.Error(ex);
}
}
/*
* Save out
*/
private void _btnSave_Click(object sender,EventArgs e) {
TargetDevice td;
try {
// target device
if(_btnArduino.Checked)
td=TargetDevice.ARDUINO;
else if(_btnStm32plus.Checked)
td=TargetDevice.STM32PLUS;
else
throw new Exception("Please select a target device");
// get filename
if(_saveFileDialog.ShowDialog()==DialogResult.Cancel)
return;
// save operation
FontWriter.Save(_sizedFont,_saveFileDialog.FileName,this,td);
}
catch(Exception ex) {
Util.Error(ex);
}
}
/*
* Load settings
*/
private void _btnLoad_Click(object sender,EventArgs e)
{
try {
// get filename
if(_openFileDialog.ShowDialog()==DialogResult.Cancel)
return;
// load operation
_sizedFont=FontReader.Load(_openFileDialog.FileName);
_editFontFile.Text=_sizedFont.Filename;
_fontSize.Value=_sizedFont.Size;
_extraLines.Value=_sizedFont.ExtraLines;
_xoffset.Value=_sizedFont.XOffset;
_yoffset.Value=_sizedFont.YOffset;
_charSpace.Value=_sizedFont.CharSpace;
EnableControls();
RefillCharsPanel();
}
catch(Exception ex) {
Util.Error(ex);
}
}
/*
* Logo clicked
*/
private void _logo_Click(object sender,EventArgs e)
{
Process.Start("http://www.andybrown.me.uk");
}
}
}
| 18.717949 | 140 | 0.560399 | [
"BSD-3-Clause"
] | 100ker/stm32plus | utils/fonts/FontConv/FormMain.cs | 8,032 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.SceneManagement;
using System;
using TMPro;
using UnityEngine.UI;
using UnityEngine.EventSystems;
public enum Fx
{
Love,
Confused,
Distracted,
Scared,
}
public class SideEffect
{
public Fx effect;
public float chance;
public SecondaryType effector;
public SideEffect(Fx effect, SecondaryType effector)
{
this.effect = effect;
this.effector = effector;
switch (effect)
{
case Fx.Love:
chance = 0.5f;
break;
case Fx.Distracted:
chance = 0.8f;
break;
case Fx.Confused:
chance = 0.8f;
break;
case Fx.Scared:
chance = 0.5f;
break;
}
}
}
public class ExploreCat : ExploreCatHolder
{
public ExplorePlayer owner;
public ExploreCat target;
public HealthBar healthBar;
private Animator animator;
public void setAnimator(RuntimeAnimatorController a)
{
getAnimator().runtimeAnimatorController = a;
}
public Animator getAnimator()
{
if (animator != null)
{
return animator;
}
animator = transform.GetChild(0).GetComponent<Animator>();
return animator;
}
public float currentHealth;
private float coolDown;
public CatDynamicStatsRealized realizedStats;
private Coroutine IAttack;
public Action<AttackType, ExploreCat> onHit;
public Action<ActionType, ExploreCat> onAction;
public Action<SideEffect, ExploreCat> onEffect;
#region POWERUPS/EFFECTS ------
private bool flying = false;
public Button Action;
public bool usedAction;
ushort boost = 0;
public SideEffect sideEffect;
public Material spriteMaterial;
#endregion
#region MOVEMENT/VISUALS ---
private int increment;
private float blockedTime;
#endregion
public Queue<AttackObj> attackObjs = new Queue<AttackObj>();
public AttackObj cAttack;
//object pooling
public void getAttackObj(ExploreCat enemyCat, float damage)
{
if (attackObjs.Count == 0)
{
CreateAttackObject(enemyCat, damage);
return;
}
cAttack = attackObjs.Dequeue();
cAttack.setOnHit(true);
cAttack.setDamage(damage);
}
public void init(Cat cat, ExplorePlayer owner, int i, HealthBar hb)
{
this.cat = cat;
this.owner = owner;
this.healthBar = hb;
healthBar.initHealthBar(this);
setStats();
cat.SetCat(transform.GetChild(0));
gameObject.name = cat.Name;
Debug.Log("FIGHTER " + cat.Name + " at Lv." + cat.catLvl.level);
//wait for user input to enable
increment = i + (!owner.enemy ? 5 : 0);
setPositionZ(transform.position);
enabled = false;
}
public void setStats()
{
realizedStats = cat.getRealizedStats();
currentHealth = realizedStats.maxHealth;
}
public void checkRemoveEffect()
{
Debug.Log(cat.Name + "'s checking if we remove effect at chance " + sideEffect.chance);
if (UnityEngine.Random.value < sideEffect.chance)
{
Debug.Log(cat.Name + "'s side effect removed!");
sideEffect = null;
if (boost > 0)
{
healthBar.fromEffectToFactionAdvantage();
}
else
{
healthBar.removeEffect();
}
}
else
{
sideEffect.chance += 0.3f;
}
}
public void Enable()
{
Debug.Log("trying to enable " + cat.Name);
if (enabled)
{
Debug.Log("already enabled!: " + cat.Name);
return;
}
Debug.Log("enable " + cat.Name);
enabled = true;
if (sideEffect != null)
{
StartCoroutine(initSideEffect());
return;
}
if (owner.enemy && (target == null || target.currentHealth <= 0))
{
findTarget();
}
this.getAnimator().SetBool("walk", true);
coolDown = 0.25f;
IAttack = StartCoroutine(Attack());
}
public void findTarget()
{
if (owner.enemyPlayer.aliveCats.Count == 0)
{
return;
}
ExploreCat closestCat = null;
float distance = float.PositiveInfinity;
foreach (ExploreCat c in owner.enemyPlayer.aliveCats)
{
float d2 = Vector2.Distance(transform.position, c.transform.position);
if (d2 < distance)
{
distance = d2;
closestCat = c;
}
}
target = closestCat;
}
public void Disable()
{
Debug.Log(" trying to disable " + cat.Name);
if (!enabled)
{
Debug.Log("already disabled " + cat.Name);
return;
}
// StartCoroutine(changeZ());
if (IAttack != null)
{
Debug.Log("STOP ATTACK " + cat.Name);
StopCoroutine(IAttack);
}
if (cAttack != null)
{
cAttack.setOnHit(false);
}
if (!owner.enemy)
{
target = null;
}
stopWalk();
blockedTime = 0;
enabled = false;
}
// IEnumerator changeZ()
// {
// WaitForSeconds s = new WaitForSeconds(0.1f);
// Vector3 one = transform.position, two;
// yield return new WaitForSeconds(0.2f);
// two = transform.position;
// do
// {
// one = two;
// setPositionZ(one);
// yield return s;
// two = transform.position;
// } while (one.y != two.y);
// }
private IEnumerator initSideEffect()
{
yield return null;
target = null;
onEffect(sideEffect, this);
}
public void useAction()
{
Debug.Log(cat.Name + " use action");
enabled = true;
ActionType action = cat.getCatAsset().action;
usedAction = true;
onAction(action, this);
if (!owner.enemy)
{
Action.interactable = false;
}
}
// Update is called once per frame
IEnumerator Attack()
{
if (currentHealth <= 0)
{
Disable();
yield break;
}
//so we can get multiple hits in if cooldown is low
if (target != null)
{
while ((coolDown > 0))
{
coolDown -= Time.deltaTime;
yield return null;
}
float distance;
if (cat.getCatAsset().attackType == AttackType.Melee)
{
distance = 4.5f;
}
else
{
distance = this.realizedStats.projectileSpeed;
}
if (target == null)
{
Disable();
yield break;
}
Vector2 position = transform.position;
Vector2 dir = (Vector2)target.transform.position - (Vector2)position;
WaitForFixedUpdate fu = new WaitForFixedUpdate();
while (dir.magnitude > distance)
{
// Debug.Log("distance - " + ((Vector2)target.transform.position - (Vector2)transform.position).magnitude);
// Debug.Log("velocity - " + getRigidBody2D().velocity);
dir.Normalize();
getRigidBody2D().AddForce(dir * this.realizedStats.speed, ForceMode2D.Force);
setPositionZ(position);
yield return fu;
if (target == null)
{
Disable();
yield break;
}
position = transform.position;
dir = (Vector2)target.transform.position - (Vector2)position;
}
StartCoroutine(attackEnemy());
}
stopWalk();
getRigidBody2D().velocity = Vector2.zero;
// coolDown = 1.8f + 9 / realizedStats.speed;
}
private void OnCollisionExit2D(Collision2D other)
{
//getRigidBody2D().mass = 0.9f;
setPositionZ(transform.position);
blockedTime = 0;
}
// private void OnCollisionEnter2D(Collision2D other)
// {
// getRigidBody2D().mass = 0.4f;
// setPositionZ(transform.position);
// }
void OnCollisionStay2D(Collision2D col)
{
if (!enabled || col.rigidbody == null)
{
if (!getRigidBody2D().IsSleeping())
{
setPositionZ(transform.position);
}
return;
}
blockedTime += Time.deltaTime;
//collision detection
if (blockedTime > 4f)
{
blockedTime = 0;
TextMeshPro text = owner.getDamageText(0);
text.text = "BLOCKED";
RiseText(text, null);
StartCoroutine(goAway());
// StartCoroutine(goAway(col));
}
}
IEnumerator goAway()
{
yield return null;
onHit(AttackType.None, this);
}
public void moveUp()
{
getRigidBody2D().AddForce(Vector2.up, ForceMode2D.Impulse);
}
public void moveDown()
{
getRigidBody2D().AddForce(Vector2.down, ForceMode2D.Impulse);
}
void setPositionZ(Vector3 tempPos)
{
float newZ = Mathf.Lerp(-10, 190, (tempPos.y + 4) / 5);
transform.position = new Vector3(tempPos.x, tempPos.y, newZ + increment);
}
#region Health and Damage
public void hitByObj(float damage, AttackObj attacker)
{
checkEffect(attacker);
if (damage > 0)
{
owner.getCameraShake().Shake();
}
takeDamage(damage);
}
public void takeDamage(float damage)
{
if (damage > 0 && currentHealth > 0)
{
currentHealth -= damage;
Debug.Log(cat.Name + " took damage. current health - " + currentHealth);
healthBar.updateHealthBar(this);
if (currentHealth <= 0)
{
owner.aliveCats.Remove(this);
}
StartCoroutine(Flicker(damage, () =>
{
if (currentHealth <= 0)
{
currentHealth = 0;
die();
}
}));
}
setDamageUI((int)damage);
}
private void checkEffect(AttackObj attacker)
{
Fx fx;
if (attacker.particles == null)
{
return;
}
if (attacker.particles.gameObject.name == "hypnotized")
{
fx = Fx.Distracted;
}
else if (attacker.particles.gameObject.name == "confused")
{
fx = Fx.Confused;
}
else if (attacker.particles.gameObject.name == "love")
{
fx = Fx.Love;
}
else if (attacker.particles.gameObject.name == "bats")
{
fx = Fx.Scared;
}
else
{
return;
}
if (sideEffect != null && sideEffect.effect == fx)
{
return;
}
healthBar.setSideEffect(fx, this);
sideEffect = new SideEffect(fx, attacker.owner.cat.getCatAsset().secondaryType);
}
private IEnumerator Flicker(float damage, Action onComplete)
{
Color orig = spriteMaterial.color;
yield return null;
yield return null;
spriteMaterial.color = Color.clear;
float yield = Mathf.Clamp(damage / realizedStats.maxHealth / 3, 0.03f, 0.12f);
yield return new WaitForSeconds(yield);
spriteMaterial.color = orig;
onComplete();
}
private float filterDamage(float damage, ExploreCat enemyCat, AttackType t)
{
if (t == AttackType.Melee && !flying && enemyCat.flying)
{
Debug.Log("miss because " + cat.Name + " isn't flying and " + enemyCat.cat.Name + " is");
return 0;
}
//if speed more than enemy's, higher likelihood of enemy missing
float multiply;
if (t == AttackType.Melee)
{
multiply = 15;
}
else
{
multiply = 3;
}
if (UnityEngine.Random.value > (realizedStats.speed / enemyCat.realizedStats.speed) - (2f / (realizedStats.speed * multiply)))
{
Debug.Log("Miss! With " + cat.Name + " having speed " + realizedStats.speed + " and enemy " + enemyCat.cat.Name + " having speed " + enemyCat.realizedStats.speed);
return 0;
}
return damage;
}
// show rising numbers on damage
public void setDamageUI(int damage)
{
TextMeshPro text = owner.getDamageText(damage);
text.text = damage > 0 ? "-" + damage.ToString() : "MISSED";
RiseText(text, null);
}
public void RiseText(TextMeshPro text, Action onComplete)
{
text.transform.SetParent(transform, false);
text.transform.localEulerAngles = transform.eulerAngles;
text.transform.localPosition = new Vector3(0, 1, 0);
Color textColor = text.color;
LeanTween.value(text.gameObject, 0, 1, 0.8f).setOnUpdate((float value) =>
{
text.transform.localPosition = new Vector3(0, value * 1.2f + 1, 0);
textColor.a = 1f - value;
text.color = textColor;
}).setEaseInQuart().setDelay(0.7f).setOnComplete(() =>
{
text.gameObject.SetActive(false);
textColor.a = 1;
text.color = textColor;
owner.damageTexts.Enqueue(text);
if (onComplete != null)
{
onComplete();
}
});
}
private void die()
{
owner.GameOver(owner);
onHit(AttackType.None, this);
target = null;
getRigidBody2D().velocity = Vector2.zero;
Destroy(GetComponent<Collider2D>());
healthBar.setDead();
RandomCatNoises n = transform.GetChild(0).GetComponent<RandomCatNoises>();
n.playMeow();
n.enableNoises = false;
if (owner.enemy)
{
EventTrigger ET = GetComponent<EventTrigger>();
if (ET != null)
{
Destroy(ET);
}
gameObject.layer = owner.getLayer(false);
}
else
{
Action.interactable = false;
}
if (getAnimator().GetBool("fly"))
{
Vector3 startPos = transform.position;
Vector3 endPos = owner.getLosePos(this);
Vector3 bending = Vector3.left;
LeanTween.value(gameObject, 0, 1, 2.1f).setDelay(0.5f).setOnUpdate((float val) =>
{
Vector3 currentPos = Vector3.Lerp(startPos, endPos, val);
currentPos.x += bending.x * Mathf.Sin(val * Mathf.PI);
currentPos.y += bending.y * Mathf.Sin(val * Mathf.PI);
transform.position = currentPos;
setPositionZ(currentPos);
}).setOnComplete(() =>
getAnimator().SetBool("fly", false));
flying = false;
}
else
{
StartCoroutine(moveToOrig());
}
}
IEnumerator moveToOrig()
{
Vector3 endPos = owner.getLosePos(this), position = transform.position;
Debug.Log(endPos);
getAnimator().SetBool("walk", true);
Vector2 dir = endPos - position;
WaitForFixedUpdate fu = new WaitForFixedUpdate();
while (dir.magnitude > 0.3f)
{
// Debug.Log("distance - " + ((Vector2)target.transform.position - (Vector2)transform.position).magnitude);
// Debug.Log("velocity - " + getRigidBody2D().velocity);
dir.Normalize();
getRigidBody2D().AddForce(dir * (this.realizedStats.speed / 2), ForceMode2D.Force);
yield return fu;
position = transform.position;
setPositionZ(position);
dir = endPos - position;
}
setPositionZ(position);
stopWalk();
}
#endregion
#region Attack
public IEnumerator attackEnemy()
{
if (!enabled || target == null)
{
yield break;
}
ExploreCat targ = target;
AttackType aType = cat.getCatAsset().attackType;
Debug.Log(cat.Name + " ATTACK " + target.cat.Name);
if (aType == AttackType.Melee)
{
this.getAnimator().SetTrigger("swipe");
}
else if (aType == AttackType.Ranged)
{
this.getAnimator().SetTrigger("throw");
}
getAttackObj(targ, filterDamage(this.realizedStats.attackDamage, targ, aType));
//wait for animation
yield return new WaitForSeconds(0.75f);
cAttack.gameObject.SetActive(true);
if (aType == AttackType.Melee)
{
cAttack.transform.position = targ.transform.position;
((Melee)cAttack).Target(targ);
}
else if (aType == AttackType.Ranged)
{
((Projectile)cAttack).Target(targ);
}
}
private void CreateAttackObject(ExploreCat enemyCat, float damage)
{
cAttack = Instantiate(Resources.Load<GameObject>("miscPrefabs/" + cat.getCatAsset().attackType.ToString())).GetComponent<AttackObj>();
Sprite secondarySprite = Resources.Load<Sprite>("fightUI/" + this.cat.getCatAsset().secondaryType.ToString());
if (cat.getCatAsset().attackType == AttackType.Melee)
{
((Melee)cAttack).Init(this);
((Melee)cAttack).getSprite().sprite = secondarySprite;
}
else if (cat.getCatAsset().attackType == AttackType.Ranged)
{
cAttack.GetComponent<SpriteRenderer>().sprite = secondarySprite;
((Projectile)cAttack).Init(this, this.realizedStats.projectileSpeed, cat.getCatAsset().secondaryType);
}
cAttack.setDamage(damage);
}
// add advantage due to having a faction that is compatible to the WorldType
//particle effects and stuff
public void factionAdvantage()
{
Transform powerUpParticles = GameObject.Instantiate(Resources.Load<GameObject>("miscPrefabs/powerUp")).transform;
powerUpParticles.name = "powerUp";
powerUpParticles.SetParent(transform, false);
healthBar.setFactionAdvantage();
tempBoost(7);
}
public void FadeAndAvoidHit()
{
Debug.Log("fade");
LeanTween.value(1, 0.25f, 2.5f).setEaseInSine().setOnUpdate((float val) =>
{
//set alpha
spriteMaterial.color = new Color(1, 1, 1, val);
});
//harder to land a hit
boost += 7;
realizedStats.speed = cat.getSpeedBoost((uint)(boost));
}
public void FlyAndAvoidHit()
{
// todo
Vector3 startPos = transform.position;
Vector3 endPos = new Vector3(startPos.x + (owner.enemy ? -1f : 1f), startPos.y + 1f, 0);
Vector3 bending = Vector3.left;
Physics2D.IgnoreCollision(GetComponent<Collider2D>(), GameObject.FindGameObjectWithTag("MainMenu").GetComponent<Collider2D>());
LeanTween.value(gameObject, 0, 1, 2.1f).setDelay(0.5f).setOnUpdate((float val) =>
{
Vector3 currentPos = Vector3.Lerp(startPos, endPos, val);
currentPos.x += bending.x * Mathf.Sin(val * Mathf.PI);
currentPos.y += bending.y * Mathf.Sin(val * Mathf.PI);
transform.position = currentPos;
setPositionZ(currentPos);
});
getAnimator().SetBool("fly", true);
getRigidBody2D().constraints = RigidbodyConstraints2D.FreezePositionY | RigidbodyConstraints2D.FreezeRotation;
flying = true;
//avoid hit - only ranged cats or other flying cats can land a hit
}
public void Magic()
{
GameObject.Instantiate(Resources.Load<GameObject>("Particles/magic"), transform, false);
StartCoroutine(groupHeal());
}
public IEnumerator groupHeal()
{
yield return new WaitForSeconds(2.5f);
WaitForSeconds pause = new WaitForSeconds(0.5f);
float maxHealth = realizedStats.maxHealth * 0.85f;
Color oldColor = Color.clear;
foreach (ExploreCat cat in owner.aliveCats)
{
if (cat.currentHealth == cat.realizedStats.maxHealth)
{
continue;
}
float increment = maxHealth;
increment = Mathf.Clamp(increment, 0, cat.realizedStats.maxHealth - cat.currentHealth);
cat.currentHealth += increment;
maxHealth -= increment;
TextMeshPro text = owner.getDamageText((int)increment);
text.text = "+" + (int)increment;
if (oldColor == Color.clear)
{
oldColor = new Color(text.color.r, text.color.g, text.color.b, 1);
}
text.color = new Color32(103, 195, 0, 255);
cat.RiseText(text, () =>
{
text.color = oldColor;
Debug.Log("HEYY CHANGE BACK THE COLORS " + oldColor);
});
cat.healthBar.updateHealthBar(cat);
if (maxHealth <= 0)
{
break;
}
yield return pause;
}
}
public void loveParticles()
{
GameObject.Instantiate(Resources.Load<GameObject>("miscPrefabs/love"), transform, false);
}
public void setEffect()
{
string textureName = sideEffect.effect.ToString() + "Tex";
int overlay = Shader.PropertyToID("_OverlayTex");
Texture overlayTex = spriteMaterial.GetTexture(overlay);
if ((overlayTex == null || overlayTex != null && overlayTex.name != textureName))
{
spriteMaterial.SetTexture(overlay, Resources.Load<Texture2D>("miscUI/" + textureName));
}
moveTexture(overlay);
}
private void moveTexture(int overlay)
{
//offset X from 0.25 to -0.14
//ofset Y from -0.24 to 0.3
//overlay color from Color.clear to Color.white
int color = Shader.PropertyToID("_ColorOverlay");
LeanTween.value(GameControl.control.gameObject, (float val) =>
{
spriteMaterial.SetTextureOffset(overlay, new Vector2(0.25f - (0.25f * val), -0.24f + (0.24f * val)));
spriteMaterial.SetColor(color, new Color(1, 1, 1, val * 0.4f));
}, 0, 1, 1.5f).setOnComplete(() =>
{
LeanTween.value(GameControl.control.gameObject, (float val) =>
{
spriteMaterial.SetTextureOffset(overlay, new Vector2(-0.14f + (0.14f * val), 0.3f - (0.3f * val)));
spriteMaterial.SetColor(color, new Color(1, 1, 1, val * 0.4f));
}, 1, 0, 1.5f).setOnComplete(() =>
{
spriteMaterial.SetColor(color, Color.clear);
});
});
}
public void tempBoost(ushort boost)
{
this.boost += boost;
float prevHealth = realizedStats.maxHealth;
realizedStats = cat.getTemporaryBoost(this.boost);
currentHealth = (currentHealth * realizedStats.maxHealth) / prevHealth;
}
#endregion
#region Move
public void stopWalk()
{
this.getAnimator().SetBool("walk", false);
// getRigidBody2D().velocity = Vector2.zero;
}
// public void moveRandom()
// {
// Rigidbody2D rigidbody2D = getRigidBody2D();
// rigidbody2D.velocity = new Vector2(rigidbody2D.velocity.x + UnityEngine.Random.Range(-.2f * realizedStats.speed, .2f * realizedStats.speed),
// rigidbody2D.velocity.y + UnityEngine.Random.Range(-.2f * realizedStats.speed, .2f * realizedStats.speed));
// }
#endregion
}
| 32.073548 | 176 | 0.530032 | [
"MIT"
] | zephyo/Wholesome-Cats | Scripts/Explore/ExploreCat.cs | 24,859 | C# |
namespace Products_Management_System.Presentation_Layer
{
partial class FRM_ORDERS
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
/// <summary>
/// Clean up any resources being used.
/// </summary>
/// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param>
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
this.groupBox1 = new System.Windows.Forms.GroupBox();
this.dtorder = new System.Windows.Forms.DateTimePicker();
this.txtSalesMan = new System.Windows.Forms.TextBox();
this.txtDescOrder = new System.Windows.Forms.TextBox();
this.txtOrderId = new System.Windows.Forms.TextBox();
this.label4 = new System.Windows.Forms.Label();
this.label3 = new System.Windows.Forms.Label();
this.label2 = new System.Windows.Forms.Label();
this.label1 = new System.Windows.Forms.Label();
this.groupBox2 = new System.Windows.Forms.GroupBox();
this.button1 = new System.Windows.Forms.Button();
this.pboxo = new System.Windows.Forms.PictureBox();
this.txtEm = new System.Windows.Forms.TextBox();
this.txtT = new System.Windows.Forms.TextBox();
this.txtLName = new System.Windows.Forms.TextBox();
this.txtFName = new System.Windows.Forms.TextBox();
this.txtCustomerId = new System.Windows.Forms.TextBox();
this.label9 = new System.Windows.Forms.Label();
this.label8 = new System.Windows.Forms.Label();
this.label7 = new System.Windows.Forms.Label();
this.label6 = new System.Windows.Forms.Label();
this.label5 = new System.Windows.Forms.Label();
this.groupBox3 = new System.Windows.Forms.GroupBox();
this.txtWithDiscountProduct = new System.Windows.Forms.TextBox();
this.txtDiscountProduct = new System.Windows.Forms.TextBox();
this.txtWithoutDiscountProduct = new System.Windows.Forms.TextBox();
this.txtQteProduct = new System.Windows.Forms.TextBox();
this.txtPriceProduct = new System.Windows.Forms.TextBox();
this.txtNameProduct = new System.Windows.Forms.TextBox();
this.label17 = new System.Windows.Forms.Label();
this.label16 = new System.Windows.Forms.Label();
this.label15 = new System.Windows.Forms.Label();
this.label14 = new System.Windows.Forms.Label();
this.label13 = new System.Windows.Forms.Label();
this.label12 = new System.Windows.Forms.Label();
this.label18 = new System.Windows.Forms.Label();
this.txtIdProduct = new System.Windows.Forms.TextBox();
this.label11 = new System.Windows.Forms.Label();
this.txtSumTotals = new System.Windows.Forms.TextBox();
this.label10 = new System.Windows.Forms.Label();
this.dgvProducts = new System.Windows.Forms.DataGridView();
this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components);
this.تعديلToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.toolStripSeparator1 = new System.Windows.Forms.ToolStripSeparator();
this.حذفالسطرالحاليToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.حذفالكلToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem();
this.btnBrowseProdcuts = new System.Windows.Forms.Button();
this.btnNewOrder = new System.Windows.Forms.Button();
this.btnSaveOrder = new System.Windows.Forms.Button();
this.btnPrintOrder = new System.Windows.Forms.Button();
this.button6 = new System.Windows.Forms.Button();
this.groupBox1.SuspendLayout();
this.groupBox2.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.pboxo)).BeginInit();
this.groupBox3.SuspendLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvProducts)).BeginInit();
this.contextMenuStrip1.SuspendLayout();
this.SuspendLayout();
//
// groupBox1
//
this.groupBox1.Controls.Add(this.dtorder);
this.groupBox1.Controls.Add(this.txtSalesMan);
this.groupBox1.Controls.Add(this.txtDescOrder);
this.groupBox1.Controls.Add(this.txtOrderId);
this.groupBox1.Controls.Add(this.label4);
this.groupBox1.Controls.Add(this.label3);
this.groupBox1.Controls.Add(this.label2);
this.groupBox1.Controls.Add(this.label1);
this.groupBox1.Location = new System.Drawing.Point(11, 12);
this.groupBox1.Name = "groupBox1";
this.groupBox1.Size = new System.Drawing.Size(560, 284);
this.groupBox1.TabIndex = 0;
this.groupBox1.TabStop = false;
this.groupBox1.Text = " بيانات الفاتورة ";
this.groupBox1.Enter += new System.EventHandler(this.groupBox1_Enter);
//
// dtorder
//
this.dtorder.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.dtorder.Location = new System.Drawing.Point(112, 185);
this.dtorder.Name = "dtorder";
this.dtorder.Size = new System.Drawing.Size(317, 30);
this.dtorder.TabIndex = 2;
//
// txtSalesMan
//
this.txtSalesMan.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtSalesMan.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtSalesMan.Location = new System.Drawing.Point(112, 230);
this.txtSalesMan.Name = "txtSalesMan";
this.txtSalesMan.ReadOnly = true;
this.txtSalesMan.Size = new System.Drawing.Size(319, 30);
this.txtSalesMan.TabIndex = 3;
//
// txtDescOrder
//
this.txtDescOrder.Location = new System.Drawing.Point(112, 85);
this.txtDescOrder.Multiline = true;
this.txtDescOrder.Name = "txtDescOrder";
this.txtDescOrder.Size = new System.Drawing.Size(317, 81);
this.txtDescOrder.TabIndex = 1;
//
// txtOrderId
//
this.txtOrderId.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtOrderId.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtOrderId.Location = new System.Drawing.Point(112, 40);
this.txtOrderId.Name = "txtOrderId";
this.txtOrderId.ReadOnly = true;
this.txtOrderId.Size = new System.Drawing.Size(319, 30);
this.txtOrderId.TabIndex = 0;
//
// label4
//
this.label4.AutoSize = true;
this.label4.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label4.Location = new System.Drawing.Point(448, 230);
this.label4.Name = "label4";
this.label4.Size = new System.Drawing.Size(61, 20);
this.label4.TabIndex = 3;
this.label4.Text = "اسم البائع";
this.label4.Click += new System.EventHandler(this.label4_Click);
//
// label3
//
this.label3.AutoSize = true;
this.label3.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label3.Location = new System.Drawing.Point(448, 185);
this.label3.Name = "label3";
this.label3.Size = new System.Drawing.Size(67, 20);
this.label3.TabIndex = 2;
this.label3.Text = "تاريخ البيع";
//
// label2
//
this.label2.AutoSize = true;
this.label2.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label2.Location = new System.Drawing.Point(448, 85);
this.label2.Name = "label2";
this.label2.Size = new System.Drawing.Size(88, 20);
this.label2.TabIndex = 1;
this.label2.Text = "وصف الفاتورة";
//
// label1
//
this.label1.AutoSize = true;
this.label1.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label1.Location = new System.Drawing.Point(448, 40);
this.label1.Name = "label1";
this.label1.Size = new System.Drawing.Size(73, 20);
this.label1.TabIndex = 0;
this.label1.Text = "رقم الفاتورة";
this.label1.Click += new System.EventHandler(this.label1_Click);
//
// groupBox2
//
this.groupBox2.Controls.Add(this.button1);
this.groupBox2.Controls.Add(this.pboxo);
this.groupBox2.Controls.Add(this.txtEm);
this.groupBox2.Controls.Add(this.txtT);
this.groupBox2.Controls.Add(this.txtLName);
this.groupBox2.Controls.Add(this.txtFName);
this.groupBox2.Controls.Add(this.txtCustomerId);
this.groupBox2.Controls.Add(this.label9);
this.groupBox2.Controls.Add(this.label8);
this.groupBox2.Controls.Add(this.label7);
this.groupBox2.Controls.Add(this.label6);
this.groupBox2.Controls.Add(this.label5);
this.groupBox2.Location = new System.Drawing.Point(578, 12);
this.groupBox2.Name = "groupBox2";
this.groupBox2.Size = new System.Drawing.Size(601, 284);
this.groupBox2.TabIndex = 1;
this.groupBox2.TabStop = false;
this.groupBox2.Text = " بيانات العميل ";
//
// button1
//
this.button1.Location = new System.Drawing.Point(217, 44);
this.button1.Name = "button1";
this.button1.Size = new System.Drawing.Size(96, 30);
this.button1.TabIndex = 0;
this.button1.Text = "...";
this.button1.UseVisualStyleBackColor = true;
this.button1.Click += new System.EventHandler(this.button1_Click);
//
// pboxo
//
this.pboxo.BackColor = System.Drawing.SystemColors.ControlLight;
this.pboxo.Location = new System.Drawing.Point(7, 26);
this.pboxo.Name = "pboxo";
this.pboxo.Size = new System.Drawing.Size(180, 235);
this.pboxo.SizeMode = System.Windows.Forms.PictureBoxSizeMode.Zoom;
this.pboxo.TabIndex = 6;
this.pboxo.TabStop = false;
//
// txtEm
//
this.txtEm.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtEm.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtEm.Location = new System.Drawing.Point(217, 231);
this.txtEm.Name = "txtEm";
this.txtEm.ReadOnly = true;
this.txtEm.Size = new System.Drawing.Size(235, 30);
this.txtEm.TabIndex = 5;
//
// txtT
//
this.txtT.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtT.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtT.Location = new System.Drawing.Point(217, 183);
this.txtT.Name = "txtT";
this.txtT.ReadOnly = true;
this.txtT.Size = new System.Drawing.Size(235, 30);
this.txtT.TabIndex = 5;
//
// txtLName
//
this.txtLName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtLName.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtLName.Location = new System.Drawing.Point(217, 136);
this.txtLName.Name = "txtLName";
this.txtLName.ReadOnly = true;
this.txtLName.Size = new System.Drawing.Size(235, 30);
this.txtLName.TabIndex = 5;
//
// txtFName
//
this.txtFName.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtFName.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtFName.Location = new System.Drawing.Point(217, 88);
this.txtFName.Name = "txtFName";
this.txtFName.ReadOnly = true;
this.txtFName.Size = new System.Drawing.Size(235, 30);
this.txtFName.TabIndex = 5;
//
// txtCustomerId
//
this.txtCustomerId.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtCustomerId.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtCustomerId.Location = new System.Drawing.Point(319, 44);
this.txtCustomerId.Name = "txtCustomerId";
this.txtCustomerId.ReadOnly = true;
this.txtCustomerId.Size = new System.Drawing.Size(135, 30);
this.txtCustomerId.TabIndex = 5;
//
// label9
//
this.label9.AutoSize = true;
this.label9.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label9.Location = new System.Drawing.Point(475, 234);
this.label9.Name = "label9";
this.label9.Size = new System.Drawing.Size(101, 20);
this.label9.TabIndex = 4;
this.label9.Text = "البريد الإلكتروني";
//
// label8
//
this.label8.AutoSize = true;
this.label8.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label8.Location = new System.Drawing.Point(475, 186);
this.label8.Name = "label8";
this.label8.Size = new System.Drawing.Size(69, 20);
this.label8.TabIndex = 3;
this.label8.Text = "رقم الهاتف";
//
// label7
//
this.label7.AutoSize = true;
this.label7.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label7.Location = new System.Drawing.Point(475, 139);
this.label7.Name = "label7";
this.label7.Size = new System.Drawing.Size(76, 20);
this.label7.TabIndex = 2;
this.label7.Text = "الاسم الاخير";
//
// label6
//
this.label6.AutoSize = true;
this.label6.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label6.Location = new System.Drawing.Point(475, 91);
this.label6.Name = "label6";
this.label6.Size = new System.Drawing.Size(71, 20);
this.label6.TabIndex = 1;
this.label6.Text = "الاسم الاول";
//
// label5
//
this.label5.AutoSize = true;
this.label5.Font = new System.Drawing.Font("Microsoft Sans Serif", 10F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label5.Location = new System.Drawing.Point(475, 44);
this.label5.Name = "label5";
this.label5.Size = new System.Drawing.Size(68, 20);
this.label5.TabIndex = 0;
this.label5.Text = "رقم العميل";
//
// groupBox3
//
this.groupBox3.Controls.Add(this.txtWithDiscountProduct);
this.groupBox3.Controls.Add(this.txtDiscountProduct);
this.groupBox3.Controls.Add(this.txtWithoutDiscountProduct);
this.groupBox3.Controls.Add(this.txtQteProduct);
this.groupBox3.Controls.Add(this.txtPriceProduct);
this.groupBox3.Controls.Add(this.txtNameProduct);
this.groupBox3.Controls.Add(this.label17);
this.groupBox3.Controls.Add(this.label16);
this.groupBox3.Controls.Add(this.label15);
this.groupBox3.Controls.Add(this.label14);
this.groupBox3.Controls.Add(this.label13);
this.groupBox3.Controls.Add(this.label12);
this.groupBox3.Controls.Add(this.label18);
this.groupBox3.Controls.Add(this.txtIdProduct);
this.groupBox3.Controls.Add(this.label11);
this.groupBox3.Controls.Add(this.txtSumTotals);
this.groupBox3.Controls.Add(this.label10);
this.groupBox3.Controls.Add(this.dgvProducts);
this.groupBox3.Controls.Add(this.btnBrowseProdcuts);
this.groupBox3.Location = new System.Drawing.Point(11, 302);
this.groupBox3.Name = "groupBox3";
this.groupBox3.Size = new System.Drawing.Size(1168, 356);
this.groupBox3.TabIndex = 2;
this.groupBox3.TabStop = false;
this.groupBox3.Text = " المنتجات ";
this.groupBox3.Enter += new System.EventHandler(this.groupBox3_Enter);
//
// txtWithDiscountProduct
//
this.txtWithDiscountProduct.BackColor = System.Drawing.SystemColors.Menu;
this.txtWithDiscountProduct.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtWithDiscountProduct.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtWithDiscountProduct.Location = new System.Drawing.Point(7, 64);
this.txtWithDiscountProduct.Name = "txtWithDiscountProduct";
this.txtWithDiscountProduct.ReadOnly = true;
this.txtWithDiscountProduct.Size = new System.Drawing.Size(182, 30);
this.txtWithDiscountProduct.TabIndex = 7;
this.txtWithDiscountProduct.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.txtWithDiscountProduct.TextChanged += new System.EventHandler(this.textBox7_TextChanged);
//
// txtDiscountProduct
//
this.txtDiscountProduct.BackColor = System.Drawing.SystemColors.Menu;
this.txtDiscountProduct.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtDiscountProduct.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtDiscountProduct.Location = new System.Drawing.Point(188, 64);
this.txtDiscountProduct.MaxLength = 3;
this.txtDiscountProduct.Name = "txtDiscountProduct";
this.txtDiscountProduct.Size = new System.Drawing.Size(137, 30);
this.txtDiscountProduct.TabIndex = 7;
this.txtDiscountProduct.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.txtDiscountProduct.TextChanged += new System.EventHandler(this.textBox7_TextChanged);
this.txtDiscountProduct.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtDiscountProduct_KeyDown);
this.txtDiscountProduct.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtDiscountProduct_KeyPress);
this.txtDiscountProduct.KeyUp += new System.Windows.Forms.KeyEventHandler(this.txtDiscountProduct_KeyUp);
//
// txtWithoutDiscountProduct
//
this.txtWithoutDiscountProduct.BackColor = System.Drawing.SystemColors.Menu;
this.txtWithoutDiscountProduct.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtWithoutDiscountProduct.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtWithoutDiscountProduct.Location = new System.Drawing.Point(324, 64);
this.txtWithoutDiscountProduct.Name = "txtWithoutDiscountProduct";
this.txtWithoutDiscountProduct.ReadOnly = true;
this.txtWithoutDiscountProduct.Size = new System.Drawing.Size(137, 30);
this.txtWithoutDiscountProduct.TabIndex = 7;
this.txtWithoutDiscountProduct.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.txtWithoutDiscountProduct.TextChanged += new System.EventHandler(this.textBox7_TextChanged);
//
// txtQteProduct
//
this.txtQteProduct.BackColor = System.Drawing.SystemColors.Menu;
this.txtQteProduct.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtQteProduct.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtQteProduct.Location = new System.Drawing.Point(460, 64);
this.txtQteProduct.MaxLength = 8;
this.txtQteProduct.Name = "txtQteProduct";
this.txtQteProduct.Size = new System.Drawing.Size(137, 30);
this.txtQteProduct.TabIndex = 7;
this.txtQteProduct.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.txtQteProduct.TextChanged += new System.EventHandler(this.txtQteProduct_TextChanged);
this.txtQteProduct.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtQteProduct_KeyDown);
this.txtQteProduct.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtQteProduct_KeyPress);
this.txtQteProduct.KeyUp += new System.Windows.Forms.KeyEventHandler(this.txtQteProduct_KeyUp);
//
// txtPriceProduct
//
this.txtPriceProduct.BackColor = System.Drawing.SystemColors.Menu;
this.txtPriceProduct.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtPriceProduct.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtPriceProduct.Location = new System.Drawing.Point(596, 64);
this.txtPriceProduct.MaxLength = 8;
this.txtPriceProduct.Name = "txtPriceProduct";
this.txtPriceProduct.Size = new System.Drawing.Size(137, 30);
this.txtPriceProduct.TabIndex = 7;
this.txtPriceProduct.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
this.txtPriceProduct.KeyDown += new System.Windows.Forms.KeyEventHandler(this.txtPriceProduct_KeyDown);
this.txtPriceProduct.KeyPress += new System.Windows.Forms.KeyPressEventHandler(this.txtPriceProduct_KeyPress);
this.txtPriceProduct.KeyUp += new System.Windows.Forms.KeyEventHandler(this.txtPriceProduct_KeyUp);
//
// txtNameProduct
//
this.txtNameProduct.BackColor = System.Drawing.SystemColors.Menu;
this.txtNameProduct.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtNameProduct.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtNameProduct.Location = new System.Drawing.Point(732, 64);
this.txtNameProduct.Name = "txtNameProduct";
this.txtNameProduct.ReadOnly = true;
this.txtNameProduct.Size = new System.Drawing.Size(231, 30);
this.txtNameProduct.TabIndex = 7;
//
// label17
//
this.label17.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label17.Location = new System.Drawing.Point(7, 31);
this.label17.Name = "label17";
this.label17.Padding = new System.Windows.Forms.Padding(5);
this.label17.Size = new System.Drawing.Size(182, 34);
this.label17.TabIndex = 6;
this.label17.Text = "المبلغ بعد الخصم";
this.label17.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label17.Click += new System.EventHandler(this.label15_Click);
//
// label16
//
this.label16.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label16.Location = new System.Drawing.Point(188, 31);
this.label16.Name = "label16";
this.label16.Padding = new System.Windows.Forms.Padding(5);
this.label16.Size = new System.Drawing.Size(137, 34);
this.label16.TabIndex = 6;
this.label16.Text = "الخصم (%)";
this.label16.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label16.Click += new System.EventHandler(this.label15_Click);
//
// label15
//
this.label15.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label15.Location = new System.Drawing.Point(324, 31);
this.label15.Name = "label15";
this.label15.Padding = new System.Windows.Forms.Padding(5);
this.label15.Size = new System.Drawing.Size(137, 34);
this.label15.TabIndex = 6;
this.label15.Text = "المبلغ بدون خصم";
this.label15.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
this.label15.Click += new System.EventHandler(this.label15_Click);
//
// label14
//
this.label14.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label14.Location = new System.Drawing.Point(460, 31);
this.label14.Name = "label14";
this.label14.Padding = new System.Windows.Forms.Padding(5);
this.label14.Size = new System.Drawing.Size(137, 34);
this.label14.TabIndex = 6;
this.label14.Text = "الكمية";
this.label14.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label13
//
this.label13.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label13.Location = new System.Drawing.Point(596, 31);
this.label13.Name = "label13";
this.label13.Padding = new System.Windows.Forms.Padding(5);
this.label13.Size = new System.Drawing.Size(137, 34);
this.label13.TabIndex = 6;
this.label13.Text = "الثمن";
this.label13.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label12
//
this.label12.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label12.Location = new System.Drawing.Point(732, 31);
this.label12.Name = "label12";
this.label12.Padding = new System.Windows.Forms.Padding(5);
this.label12.Size = new System.Drawing.Size(231, 34);
this.label12.TabIndex = 6;
this.label12.Text = "اسم المنتج";
this.label12.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// label18
//
this.label18.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label18.Location = new System.Drawing.Point(1075, 31);
this.label18.Name = "label18";
this.label18.Padding = new System.Windows.Forms.Padding(5);
this.label18.Size = new System.Drawing.Size(87, 34);
this.label18.TabIndex = 6;
this.label18.Text = "اختيار منتج";
this.label18.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// txtIdProduct
//
this.txtIdProduct.BackColor = System.Drawing.SystemColors.Menu;
this.txtIdProduct.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtIdProduct.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtIdProduct.Location = new System.Drawing.Point(962, 64);
this.txtIdProduct.Name = "txtIdProduct";
this.txtIdProduct.ReadOnly = true;
this.txtIdProduct.Size = new System.Drawing.Size(114, 30);
this.txtIdProduct.TabIndex = 7;
this.txtIdProduct.TextAlign = System.Windows.Forms.HorizontalAlignment.Center;
//
// label11
//
this.label11.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.label11.Location = new System.Drawing.Point(962, 31);
this.label11.Name = "label11";
this.label11.Padding = new System.Windows.Forms.Padding(5);
this.label11.Size = new System.Drawing.Size(116, 34);
this.label11.TabIndex = 6;
this.label11.Text = "رقم المنتج";
this.label11.TextAlign = System.Drawing.ContentAlignment.MiddleCenter;
//
// txtSumTotals
//
this.txtSumTotals.BorderStyle = System.Windows.Forms.BorderStyle.FixedSingle;
this.txtSumTotals.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.txtSumTotals.Location = new System.Drawing.Point(6, 320);
this.txtSumTotals.Name = "txtSumTotals";
this.txtSumTotals.ReadOnly = true;
this.txtSumTotals.Size = new System.Drawing.Size(130, 30);
this.txtSumTotals.TabIndex = 5;
//
// label10
//
this.label10.AutoSize = true;
this.label10.Font = new System.Drawing.Font("Microsoft Sans Serif", 12F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.label10.Location = new System.Drawing.Point(142, 322);
this.label10.Name = "label10";
this.label10.Size = new System.Drawing.Size(106, 25);
this.label10.TabIndex = 4;
this.label10.Text = "المبلغ الإجمالي";
//
// dgvProducts
//
this.dgvProducts.AllowUserToAddRows = false;
this.dgvProducts.AllowUserToDeleteRows = false;
this.dgvProducts.AllowUserToResizeRows = false;
this.dgvProducts.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dgvProducts.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgvProducts.ContextMenuStrip = this.contextMenuStrip1;
this.dgvProducts.Location = new System.Drawing.Point(7, 102);
this.dgvProducts.MultiSelect = false;
this.dgvProducts.Name = "dgvProducts";
this.dgvProducts.ReadOnly = true;
this.dgvProducts.RowHeadersWidth = 51;
this.dgvProducts.RowTemplate.Height = 24;
this.dgvProducts.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect;
this.dgvProducts.Size = new System.Drawing.Size(1155, 212);
this.dgvProducts.TabIndex = 0;
this.dgvProducts.CellContentClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dgvProducts_CellContentClick);
this.dgvProducts.RowsRemoved += new System.Windows.Forms.DataGridViewRowsRemovedEventHandler(this.dgvProducts_RowsRemoved);
this.dgvProducts.DockChanged += new System.EventHandler(this.dgvProducts_DockChanged);
this.dgvProducts.DoubleClick += new System.EventHandler(this.dgvProducts_DoubleClick);
//
// contextMenuStrip1
//
this.contextMenuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20);
this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] {
this.تعديلToolStripMenuItem,
this.toolStripSeparator1,
this.حذفالسطرالحاليToolStripMenuItem,
this.حذفالكلToolStripMenuItem});
this.contextMenuStrip1.Name = "contextMenuStrip1";
this.contextMenuStrip1.Size = new System.Drawing.Size(200, 82);
//
// تعديلToolStripMenuItem
//
this.تعديلToolStripMenuItem.Name = "تعديلToolStripMenuItem";
this.تعديلToolStripMenuItem.Size = new System.Drawing.Size(199, 24);
this.تعديلToolStripMenuItem.Text = "تعديل";
this.تعديلToolStripMenuItem.Click += new System.EventHandler(this.تعديلToolStripMenuItem_Click);
//
// toolStripSeparator1
//
this.toolStripSeparator1.Name = "toolStripSeparator1";
this.toolStripSeparator1.Size = new System.Drawing.Size(196, 6);
//
// حذفالسطرالحاليToolStripMenuItem
//
this.حذفالسطرالحاليToolStripMenuItem.Name = "حذفالسطرالحاليToolStripMenuItem";
this.حذفالسطرالحاليToolStripMenuItem.Size = new System.Drawing.Size(199, 24);
this.حذفالسطرالحاليToolStripMenuItem.Text = "حذف السطر الحالي";
this.حذفالسطرالحاليToolStripMenuItem.Click += new System.EventHandler(this.حذفالسطرالحاليToolStripMenuItem_Click);
//
// حذفالكلToolStripMenuItem
//
this.حذفالكلToolStripMenuItem.Name = "حذفالكلToolStripMenuItem";
this.حذفالكلToolStripMenuItem.Size = new System.Drawing.Size(199, 24);
this.حذفالكلToolStripMenuItem.Text = "حذف الكل";
this.حذفالكلToolStripMenuItem.Click += new System.EventHandler(this.حذفالكلToolStripMenuItem_Click);
//
// btnBrowseProdcuts
//
this.btnBrowseProdcuts.Location = new System.Drawing.Point(1075, 64);
this.btnBrowseProdcuts.Name = "btnBrowseProdcuts";
this.btnBrowseProdcuts.Size = new System.Drawing.Size(87, 32);
this.btnBrowseProdcuts.TabIndex = 0;
this.btnBrowseProdcuts.Text = "...";
this.btnBrowseProdcuts.UseVisualStyleBackColor = true;
this.btnBrowseProdcuts.Click += new System.EventHandler(this.button3_Click_1);
//
// btnNewOrder
//
this.btnNewOrder.Location = new System.Drawing.Point(215, 668);
this.btnNewOrder.Name = "btnNewOrder";
this.btnNewOrder.Size = new System.Drawing.Size(185, 38);
this.btnNewOrder.TabIndex = 0;
this.btnNewOrder.Text = "عملية بيع جديدة";
this.btnNewOrder.UseVisualStyleBackColor = true;
this.btnNewOrder.Click += new System.EventHandler(this.button3_Click);
//
// btnSaveOrder
//
this.btnSaveOrder.Enabled = false;
this.btnSaveOrder.Location = new System.Drawing.Point(407, 668);
this.btnSaveOrder.Name = "btnSaveOrder";
this.btnSaveOrder.Size = new System.Drawing.Size(185, 38);
this.btnSaveOrder.TabIndex = 1;
this.btnSaveOrder.Text = "حفظ عملية البيع";
this.btnSaveOrder.UseVisualStyleBackColor = true;
this.btnSaveOrder.Click += new System.EventHandler(this.button4_Click);
//
// btnPrintOrder
//
this.btnPrintOrder.Location = new System.Drawing.Point(599, 668);
this.btnPrintOrder.Name = "btnPrintOrder";
this.btnPrintOrder.Size = new System.Drawing.Size(185, 38);
this.btnPrintOrder.TabIndex = 2;
this.btnPrintOrder.Text = "طباعة اخر فاتورة";
this.btnPrintOrder.UseVisualStyleBackColor = true;
this.btnPrintOrder.Click += new System.EventHandler(this.btnPrintOrder_Click);
//
// button6
//
this.button6.Location = new System.Drawing.Point(791, 668);
this.button6.Name = "button6";
this.button6.Size = new System.Drawing.Size(185, 38);
this.button6.TabIndex = 3;
this.button6.Text = "خروج";
this.button6.UseVisualStyleBackColor = true;
this.button6.Click += new System.EventHandler(this.button6_Click);
//
// FRM_ORDERS
//
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 16F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(1191, 719);
this.Controls.Add(this.button6);
this.Controls.Add(this.btnPrintOrder);
this.Controls.Add(this.btnSaveOrder);
this.Controls.Add(this.btnNewOrder);
this.Controls.Add(this.groupBox3);
this.Controls.Add(this.groupBox2);
this.Controls.Add(this.groupBox1);
this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.FixedSingle;
this.MaximizeBox = false;
this.MinimizeBox = false;
this.Name = "FRM_ORDERS";
this.RightToLeft = System.Windows.Forms.RightToLeft.Yes;
this.RightToLeftLayout = true;
this.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen;
this.Text = "إدارة المبيعات";
this.groupBox1.ResumeLayout(false);
this.groupBox1.PerformLayout();
this.groupBox2.ResumeLayout(false);
this.groupBox2.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.pboxo)).EndInit();
this.groupBox3.ResumeLayout(false);
this.groupBox3.PerformLayout();
((System.ComponentModel.ISupportInitialize)(this.dgvProducts)).EndInit();
this.contextMenuStrip1.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private System.Windows.Forms.GroupBox groupBox1;
private System.Windows.Forms.TextBox txtDescOrder;
private System.Windows.Forms.TextBox txtOrderId;
private System.Windows.Forms.Label label4;
private System.Windows.Forms.Label label3;
private System.Windows.Forms.Label label2;
private System.Windows.Forms.Label label1;
private System.Windows.Forms.TextBox txtSalesMan;
private System.Windows.Forms.GroupBox groupBox2;
private System.Windows.Forms.Button button1;
private System.Windows.Forms.PictureBox pboxo;
private System.Windows.Forms.TextBox txtEm;
private System.Windows.Forms.TextBox txtT;
private System.Windows.Forms.TextBox txtLName;
private System.Windows.Forms.TextBox txtFName;
private System.Windows.Forms.TextBox txtCustomerId;
private System.Windows.Forms.Label label9;
private System.Windows.Forms.Label label8;
private System.Windows.Forms.Label label7;
private System.Windows.Forms.Label label6;
private System.Windows.Forms.Label label5;
private System.Windows.Forms.GroupBox groupBox3;
private System.Windows.Forms.TextBox txtSumTotals;
private System.Windows.Forms.Label label10;
private System.Windows.Forms.Button btnNewOrder;
private System.Windows.Forms.Button btnSaveOrder;
private System.Windows.Forms.Button btnPrintOrder;
private System.Windows.Forms.Button button6;
private System.Windows.Forms.DateTimePicker dtorder;
private System.Windows.Forms.Label label11;
private System.Windows.Forms.TextBox txtWithoutDiscountProduct;
private System.Windows.Forms.TextBox txtQteProduct;
private System.Windows.Forms.TextBox txtPriceProduct;
private System.Windows.Forms.TextBox txtNameProduct;
private System.Windows.Forms.Label label15;
private System.Windows.Forms.Label label14;
private System.Windows.Forms.Label label13;
private System.Windows.Forms.Label label12;
private System.Windows.Forms.TextBox txtWithDiscountProduct;
private System.Windows.Forms.TextBox txtDiscountProduct;
private System.Windows.Forms.Label label17;
private System.Windows.Forms.Label label16;
private System.Windows.Forms.Button btnBrowseProdcuts;
private System.Windows.Forms.Label label18;
private System.Windows.Forms.TextBox txtIdProduct;
public System.Windows.Forms.DataGridView dgvProducts;
private System.Windows.Forms.ContextMenuStrip contextMenuStrip1;
private System.Windows.Forms.ToolStripMenuItem تعديلToolStripMenuItem;
private System.Windows.Forms.ToolStripSeparator toolStripSeparator1;
private System.Windows.Forms.ToolStripMenuItem حذفالسطرالحاليToolStripMenuItem;
private System.Windows.Forms.ToolStripMenuItem حذفالكلToolStripMenuItem;
}
} | 56.39159 | 185 | 0.628117 | [
"MIT"
] | TawfikYasser/Products-Management-System | Products Management System/Presentation Layer/FRM_ORDERS.Designer.cs | 43,474 | C# |
using Amazon.JSII.Runtime.Deputy;
#pragma warning disable CS0672,CS0809,CS1591
namespace Amazon.JSII.Tests.CalculatorNamespace
{
#pragma warning disable CS8618
/// <summary>Verifies that, in languages that do keyword lifting (e.g: Python), having a struct member with the same name as a positional parameter results in the correct code being emitted.</summary>
/// <remarks>
/// See: https://github.com/aws/aws-cdk/issues/4302
///
/// <strong>Stability</strong>: Experimental
/// </remarks>
[JsiiByValue(fqn: "jsii-calc.StructParameterType")]
public class StructParameterType : Amazon.JSII.Tests.CalculatorNamespace.IStructParameterType
{
/// <remarks>
/// <strong>Stability</strong>: Experimental
/// </remarks>
[JsiiProperty(name: "scope", typeJson: "{\"primitive\":\"string\"}", isOverride: true)]
public string Scope
{
get;
set;
}
/// <remarks>
/// <strong>Stability</strong>: Experimental
/// </remarks>
[JsiiOptional]
[JsiiProperty(name: "props", typeJson: "{\"primitive\":\"boolean\"}", isOptional: true, isOverride: true)]
public bool? Props
{
get;
set;
}
}
}
| 32.125 | 204 | 0.607004 | [
"Apache-2.0"
] | NGL321/jsii | packages/jsii-pacmak/test/expected.jsii-calc/dotnet/Amazon.JSII.Tests.CalculatorPackageId/Amazon/JSII/Tests/CalculatorNamespace/StructParameterType.cs | 1,285 | C# |
using System;
using System.Collections.Generic;
using System.Text;
namespace $safeprojectname$.ViewModels
{
public class MainWindowViewModel : ViewModelBase
{
public string Greeting => "Welcome to Avalonia!";
}
}
| 19.5 | 57 | 0.722222 | [
"MIT"
] | AvaloniaUI/AvaloniaVS | templates/AvaloniaMvvmApplicationTemplate/ViewModels/MainWindowViewModel.cs | 234 | C# |
namespace ASPNETCoreReactJS_Example.Data.Models
{
public class Score
{
public int Id { get; set; }
public int Guesses { get; set; }
public double Time { get; set; }
public string UserId { get; set; }
public User User { get; set; }
}
} | 19.4 | 48 | 0.56701 | [
"MIT"
] | SaiYaduvanshi/APNETCOREAND-REACT | ASPNETCoreReactJS-Example/ASPNETCoreReactJS-Example/Data/Models/Score.cs | 293 | C# |
// --------------------------------------------------------------------------------------------------------------------
// <copyright file="TrackerHitResult.cs" company="OxyPlot">
// Copyright (c) 2014 OxyPlot contributors
// </copyright>
// <summary>
// Provides data for a tracker hit result.
// </summary>
// --------------------------------------------------------------------------------------------------------------------
namespace OxyPlot
{
using OxyPlot.Series;
/// <summary>
/// Provides data for a tracker hit result.
/// </summary>
/// <remarks>This is used as DataContext for the TrackerControl.
/// The TrackerControl is visible when the user use the left mouse button to "track" points on the series.</remarks>
public class TrackerHitResult
{
/// <summary>
/// Gets or sets the nearest or interpolated data point.
/// </summary>
public DataPoint DataPoint { get; set; }
/// <summary>
/// Gets or sets the source item of the point.
/// If the current point is from an ItemsSource and is not interpolated, this property will contain the item.
/// </summary>
public object Item { get; set; }
/// <summary>
/// Gets or sets the index for the Item.
/// </summary>
public double Index { get; set; }
/// <summary>
/// Gets or sets the horizontal/vertical line extents.
/// </summary>
public OxyRect LineExtents { get; set; }
/// <summary>
/// Gets or sets the plot model.
/// </summary>
public PlotModel PlotModel { get; set; }
/// <summary>
/// Gets or sets the position in screen coordinates.
/// </summary>
public ScreenPoint Position { get; set; }
/// <summary>
/// Gets or sets the series that is being tracked.
/// </summary>
public Series.Series Series { get; set; }
/// <summary>
/// Gets or sets the text shown in the tracker.
/// </summary>
public string Text { get; set; }
/// <summary>
/// Gets the X axis.
/// </summary>
public Axes.Axis XAxis
{
get
{
var xyas = this.Series as XYAxisSeries;
return xyas != null ? xyas.XAxis : null;
}
}
/// <summary>
/// Gets the Y axis.
/// </summary>
public Axes.Axis YAxis
{
get
{
var xyas = this.Series as XYAxisSeries;
return xyas != null ? xyas.YAxis : null;
}
}
/// <summary>
/// Returns a <see cref="System.String" /> that represents this instance.
/// </summary>
/// <returns>A <see cref="System.String" /> that represents this instance.</returns>
public override string ToString()
{
return this.Text != null ? this.Text.Trim() : string.Empty;
}
}
} | 31.894737 | 120 | 0.489109 | [
"MIT"
] | AELIENUS/oxyplot | Source/OxyPlot/PlotController/Manipulators/TrackerHitResult.cs | 3,032 | C# |
using System;
using FFImageLoading;
using System.Threading.Tasks;
using System.Diagnostics;
using Android.Content;
using Android.Widget;
using FFImageLoading.Drawables;
using AView = Android.Views.View;
namespace HotUI.Android.Controls
{
public class HUIImageView : ImageView
{
private Image _image;
private string _source;
public HUIImageView(Context context) : base(context)
{
}
public string Source
{
get => _source;
set => UpdateSource(value);
}
public async void UpdateSource(string source)
{
if (source == _source)
return;
_source = source;
try
{
var image = await source.LoadImage();
if (source == _source)
SetImageBitmap(image.Bitmap);
}
catch (Exception e)
{
Debug.WriteLine(e);
}
}
}
} | 22.777778 | 60 | 0.519024 | [
"MIT"
] | BenBtg/HotUI | src/HotUI.Android/Controls/HUIImageView.cs | 1,027 | C# |
using FluentValidation.Results;
using SimpleLibrary.Application.EventSourcedNormlizers;
using SimpleLibrary.Application.ViewModels;
namespace SimpleLibrary.Application.Interfaces;
public interface IBookAppService : IDisposable
{
Task<ValidationResult> Register(BookViewModel bookViewModel);
Task<ValidationResult> Update(BookViewModel bookViewModel);
Task<ValidationResult> Remove(Guid id);
Task<IEnumerable<BookViewModel>> GetAll();
Task<BookViewModel> GetById(Guid id);
Task<IList<BookHistoryData>> GetAllHistory(Guid id);
}
| 34.625 | 65 | 0.806859 | [
"MIT"
] | leosousa/simple-library-api | SimpleLibrary.Application/Interfaces/IBookAppService.cs | 556 | C# |
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class BagItem : MonoBehaviour,
UnityEngine.EventSystems.IDragHandler,
UnityEngine.EventSystems.IBeginDragHandler,
UnityEngine.EventSystems.IEndDragHandler
{
// Use this for initialization
void Start () {
}
// Update is called once per frame
void Update () {
}
public void OnBeginDrag(UnityEngine.EventSystems.PointerEventData eventData)
{
Debug.Log("begin drag.." + eventData.pointerDrag);
}
public void OnDrag(UnityEngine.EventSystems.PointerEventData eventData)
{
}
public void OnEndDrag(UnityEngine.EventSystems.PointerEventData eventData)
{
Debug.Log("end drag.." + eventData.pointerCurrentRaycast.gameObject);
}
}
public static class BagItemExtension
{
public static BagItem Get(this GameObject go)
{
BagItem component = go.GetComponent<BagItem>();
if(component == null)
go.AddComponent<BagItem>();
return component;
}
} | 21.4 | 80 | 0.759086 | [
"MIT"
] | icansmile/UGUITest | Assets/UGUI_Learn/Scripts/Bag/BagItem.cs | 965 | C# |
using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;
public class PositionData : MonoBehaviour
{
[Header("Name for the CSV File")]
[SerializeField] string csvName;
[Header("Oculus Components")]
[SerializeField] GameObject player;
[Header("Recording Parameters")]
[SerializeField] float recordEverySeconds;
private string participantID;
private string filePath;
private bool startNewWrite;
private bool canRecord;
private void Start()
{
participantID = PlayerPrefs.GetString("ID", "INVALID");
startNewWrite = true;
canRecord = true;
filePath = GetFilePath();
}
private void Update()
{
if (canRecord)
{
addRecord(participantID, Time.time, player.transform.position.x, player.transform.position.z, filePath);
StartCoroutine(delayRecord());
}
}
private void addRecord(string ID,
float time,
float x,
float z,
string filePath)
{
try
{
if (startNewWrite)
{
using (StreamWriter file = new StreamWriter(@filePath, false))
{
file.WriteLine("UserID,Time,XPos,ZPos");
}
startNewWrite = false;
}
else
{
using (StreamWriter file = new StreamWriter(@filePath, true))
{
file.WriteLine(ID + "," +
time + "," +
x + "," +
z);
}
}
}
catch (Exception ex)
{
print("Something went wrong! Error: " + ex.Message);
}
}
private IEnumerator delayRecord()
{
canRecord = false;
yield return new WaitForSeconds(recordEverySeconds);
canRecord = true;
}
public string GetFilePath()
{
return Application.dataPath + "/" + participantID + "_" + csvName + ".csv";
}
}
// End of File. | 25.94186 | 116 | 0.500224 | [
"MIT"
] | bluejaelly/Data-Extraction-Kit-For-VR | Data-Extraction-Kit-For-Rift/Assets/DataKit/Scripts/PositionData.cs | 2,233 | C# |
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace Heemoney.Models.Pay
{
public class PayRequest
{
[JsonProperty("version")]
public string Version { get; set; }
[JsonProperty("app_id")]
public string App_ID { get; set; }
[JsonProperty("mch_id")]
public string Mch_Id { get; set; }
[JsonProperty("charset")]
public string Charset { get; set; }
[JsonProperty("timestamp")]
public string TimeStamp { get; set; }
[JsonProperty("sign_type")]
public string Sign_Type { get; set; }
[JsonProperty("channel_provider")]
public string Channel_Provider { get; set; }
[JsonProperty("channel_code")]
public string Channel_Code { get; set; }
[JsonProperty("out_trade_no")]
public string Out_Trade_No { get; set; }
[JsonProperty("currency")]
public string Currency { get; set; }
[JsonProperty("total_amt_fen")]
public string Total_Amt_Fen { get; set; }
[JsonProperty("bill_timeout")]
public string Bill_TimeOut { get; set; }
[JsonProperty("subject")]
public string Subject { get; set; }
[JsonProperty("subject_detail")]
public string Subject_Detail { get; set; }
[JsonProperty("user_identity")]
public string User_Identity { get; set; }
[JsonProperty("user_ip")]
public string User_Ip { get; set; }
[JsonProperty("merch_extra")]
public string Merch_Extra { get; set; }
[JsonProperty("meta_option")]
public string Meta_Option { get; set; }
[JsonProperty("pay_option")]
public string Pay_Option { get; set; }
[JsonProperty("notify_url")]
public string Notify_Url { get; set; }
[JsonProperty("return_url")]
public string Return_Url { get; set; }
}
}
| 26.253333 | 52 | 0.602336 | [
"MIT"
] | Heemoney/heemoney-csharp | Heemoney/Models/Pay/PayRequest.cs | 1,971 | C# |
namespace Nevermore.Mapping
{
public enum ColumnDirection
{
Both,
ToDatabase,
FromDatabase
}
} | 14.444444 | 31 | 0.584615 | [
"Apache-2.0"
] | OctopusDeploy/Nevermore | source/Nevermore/Mapping/ColumnDirection.cs | 130 | C# |
using System;
namespace Domino
{
//Clase Domino
class Domino
{
//Espacio 1
public int A;
//Espacio 2
public int B;
//Constructor
public Domino(int a,int b)
{
A=a;
B=b;
}
//Sobrecarga de operadores(Operador Suma)
//Se estan sumando dos piezas de domino
//d1(domino 1), d2(domino 2), A(Espacio 1) y B(Espacio 2)
public static int operator +(Domino d1, Domino d2)
{
return (d1.A+d2.A+d1.B+d2.B);
}
}
class Program
{
static void Main(string[] args)
{
//Crear objetos tipo Domino
Domino a=new Domino (2,0);
Domino b=new Domino(4,1);
//Imprimir la suma de los objetos tipo Domino
Console.WriteLine(a+b);
}
}
}
| 22.076923 | 65 | 0.494774 | [
"MIT"
] | ArturoTecuapa50/EjerciciosOPP | LopezRoblero/Domino/Program.cs | 863 | C# |
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Control.Web
{
/// <summary>
/// 蒙板控件
/// </summary>
[ParseChildren(false)]
[PersistChildren(true)]
[ToolboxData("<{0}:JointMaskPanel runat=server></{0}:JointMaskPanel>")]
public class JointMaskPanel : WebControlsBase
{
public JointMaskPanel()
: base()
{
this.LaySkin = "demo-class";
this.WHSize = "auto";
this.ButtonAlign = "r";
this.CloseSkin = 1;
this.ShadowCSS = "[0.3, '#000']";
this.ShadowClose = false;
this.AnimType = 0;
this.IsCloseAnim = false;
this.ShowMaxMin = false;
this.Fixed = true;
this.Resize = true;
this.BuutonArray = "['确定', '关闭']";
this.ScrollBar = true;
this.ZIndex = 19891014;
this.SetMostTop = false;
this.ControlType = ControlsType.JointMaskPanel;
this.Width = 800;
this.Height = 500;
}
#region 控件属性
/// <summary>
/// 控件的总宽度
/// </summary>
public override Unit Width { get; set; }
/// <summary>
/// 文本框的高度
/// </summary>
public override Unit Height { get; set; }
/// <summary>
/// 弹窗皮肤,默认值为demo-class。
/// 可选:layui-layer-lan 和 layui-layer-molv
/// </summary>
public string LaySkin { get; set; }
/// <summary>
/// 窗体大小
/// '500px':表示宽度500px,高度仍然是自适应
/// ['500px', '300px']:标识宽度500px,宽度300px
/// 这里,暂时将该参数去掉功能,改为通过Width和Height属性来进行设置
/// </summary>
public string WHSize { get; set; }
/// <summary>
/// 弹出框标题。默认值:'信息'。
/// 也可以设置 ['文本', 'font-size:18px;']
/// 如果不想显示标题,设置值为false即可
/// </summary>
public string Title { get; set; }
/// <summary>
/// 坐标,默认值为空,表示“垂直水平居中”
/// '100px' ==> 只定义top坐标,水平保持居中
/// ['100px', '50px'] ==> 同时定义top、left坐标
/// 't' ==> 快捷设置顶部坐标
/// 'r' ==> 快捷设置右边缘坐标
/// 'b' ==> 快捷设置底部坐标
/// 'l' ==> 快捷设置左边缘坐标
/// 'lt' ==> 快捷设置左上角
/// 'lb' ==> 快捷设置左下角
/// 'rt' ==> 快捷设置右上角
/// 'rb' ==> 快捷设置右下角
/// </summary>
public string Offeset { get; set; }
/// <summary>
/// 按钮数组。默认值为['确定', '关闭']
/// ['按钮1', '按钮2', '按钮3', …]
/// </summary>
public string BuutonArray { get; set; }
/// <summary>
/// 按钮排列位置:默认值为 'r':右对齐
/// 'l':左对齐 'c':居中对齐
/// </summary>
public string ButtonAlign { get; set; }
/// <summary>
/// 关闭按钮风格,默认值为1
/// 可选择值2:关闭按钮弹出模式。
/// 值为0时。标识不显示关闭按钮。
/// </summary>
public int CloseSkin { get; set; }
/// <summary>
/// 遮罩样式,默认值[0.3, '#000']
/// 若不显示遮罩,值为0即可
/// </summary>
public string ShadowCSS { get; set; }
/// <summary>
/// 是否点击遮罩关闭,默认值为false
/// </summary>
public bool ShadowClose { get; set; }
/// <summary>
/// 自动关闭时间,默认不自动关闭
/// 5000:表示5秒后自动关闭
/// </summary>
public int AutoCloseTime { get; set; }
/// <summary>
/// 弹出动画类型。默认值为0,可支持的动画类型有0-6。
/// 如果不想显示动画,设置 anim: -1 即可
/// </summary>
public int AnimType { get; set; }
/// <summary>
/// 关闭动画。默认值为true
/// </summary>
public bool IsCloseAnim { get; set; }
/// <summary>
/// 是否显示最大小化按钮。默认不显示
/// </summary>
public bool ShowMaxMin { get; set; }
/// <summary>
/// 鼠标滚动时,层是否固定在可视区域。默认值为true
/// 如果不想,设置fixed: false即可
/// </summary>
public bool Fixed { get; set; }
/// <summary>
/// 是否允许拉伸。默认值为true
/// </summary>
public bool Resize { get; set; }
/// <summary>
/// 是否允许浏览器出现滚动条。默认值为true
/// </summary>
public bool ScrollBar { get; set; }
/// <summary>
/// 最大宽度。默认值为360。
/// 只有当WHSize: 'auto'时,maxWidth的设定才有效。
/// </summary>
public string MaxWidth { get; set; }
/// <summary>
/// 层叠顺序。默认值为19891014
/// </summary>
public int ZIndex { get; set; }
/// <summary>
/// 是否最前。默认值为false
/// </summary>
public bool SetMostTop { get; set; }
#endregion
/// <summary>
/// 重写控件的头部标签输出
/// </summary>
/// <param name="writer"></param>
public override void RenderBeginTag(HtmlTextWriter writer)
{
writer.AddAttribute(HtmlTextWriterAttribute.Id, this.ClientID);
writer.AddStyleAttribute(HtmlTextWriterStyle.Height, this.Height.ToString());
writer.AddStyleAttribute(HtmlTextWriterStyle.Width, this.Width.ToString());
writer.AddStyleAttribute(HtmlTextWriterStyle.Display, "none");
writer.RenderBeginTag(HtmlTextWriterTag.Div);
}
/// <summary>
/// 重写控件的尾部标签输出
/// </summary>
/// <param name="writer"></param>
public override void RenderEndTag(HtmlTextWriter writer)
{
base.RenderEndTag(writer);
writer.Write("<script type='text/javascript' language='javascript'>" + this.ClientInitScript + "</script>");
}
/// <summary>
/// 控件对应的JS变量输出
/// </summary>
private string ClientInitScript
{
get
{
return string.Format("var {0}_JSDS={{LaySkin:'{1}', WHSize:['{2}','{3}'], Title:'{4}', Offeset:'{5}', BuutonArray:{6}," +
"ButtonAlign:'{7}', CloseSkin:{8}, ShadowCSS:{9}, ShadowClose:{10}, AutoCloseTime:{11}," +
"AnimType:{12}, IsCloseAnim:{13}, ShowMaxMin:{14}, Fixed:{15}, Resize:{16}, ScrollBar:{17}," +
"MaxWidth:'{18}', ZIndex:{19}, SetMostTop:{20}}};",
this.ClientID,
this.LaySkin,
this.Width.ToString(),
((Unit)(this.Height.Value + 140)).ToString(),
string.IsNullOrEmpty(this.Title) ? "" : this.Title,
string.IsNullOrEmpty(this.Offeset) ? "" : this.Offeset,
this.BuutonArray,
this.ButtonAlign,
this.CloseSkin,
this.ShadowCSS,
this.ShadowClose ? "true" : "false",
this.AutoCloseTime,
this.AnimType,
this.IsCloseAnim ? "true" : "false",
this.ShowMaxMin ? "true" : "false",
this.Fixed ? "true" : "false",
this.Resize ? "true" : "false",
this.ScrollBar ? "true" : "false",
this.MaxWidth,
this.ZIndex,
this.SetMostTop ? "true" : "false"
);
}
}
}
}
| 30.905172 | 137 | 0.46569 | [
"MIT"
] | 1586270999/Control.Net | Control.Net/Control.Web/containers/JointMaskPanel.cs | 8,276 | C# |
using Connecterra.StateTracking.Common.Core;
using Connecterra.StateTracking.Common.Dispatcher;
using Connecterra.StateTracking.Common.Interface;
using System.Threading.Tasks;
namespace Connecterra.StateTracking.Common.Routing
{
public interface IRouter
{
Task<Result> ExecuteAsync<T>(T command) where T : ICommand;
Task<Result<TResult>> ExecuteAsync<TQuery, TResult>(TQuery query) where TQuery : IQuery<TResult>;
}
public class Router : IRouter
{
private readonly ICommandDispatcher _commandDispatcher;
private readonly IQueryDispatcher _queryDispatcher;
public Router(ICommandDispatcher commandDispatcher, IQueryDispatcher queryDispatcher)
{
_commandDispatcher = commandDispatcher;
_queryDispatcher = queryDispatcher;
}
public Task<Result> ExecuteAsync<T>(T command) where T : ICommand
{
return _commandDispatcher.HandleAsync(command);
}
public Task<Result<TResult>> ExecuteAsync<TQuery, TResult>(TQuery query) where TQuery : IQuery<TResult>
{
return _queryDispatcher.HandleAsync<TQuery, TResult>(query);
}
}
}
| 33.194444 | 111 | 0.699582 | [
"MIT"
] | ASMaharana/AI.Connecterra.StateTracking | src/Connecterra.StateTracking.Common/Routing/Router.cs | 1,197 | C# |
// Copyright 2020 The Tilt Brush Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using Newtonsoft.Json;
using NUnit.Framework;
using UnityEditor;
using UnityEngine;
namespace TiltBrush
{
/// Contains helpers that allow brush geometry to be generated at edit-time.
/// Also serves as a good record of the global state touched by our geometry
/// generation process (and therefore as a record of places to fix if we want
/// to run geometry generation on some other thread)
public class TestBrush
{
// true if we've set up any singletons
private bool m_needSingletonTeardown;
// Contains all the components we need in order to run geometry generation
private GameObject m_container;
// Some stroke data for testing
private List<Stroke> m_testStrokes;
/// Creates and returns a temporary Canvas, with proper clean-up.
class TempCanvas : IDisposable
{
// Hack this to true if you want to examine the results.
public static bool kPersistent = false;
public CanvasScript m_canvas;
public TempCanvas(string name = "Some unit test")
{
m_canvas = CanvasScript.UnitTestSetUp(new GameObject(name + " canvas"));
}
void IDisposable.Dispose()
{
if (kPersistent)
{
m_canvas.BatchManager.FlushMeshUpdates();
}
else
{
CanvasScript.UnitTestTearDown(m_canvas.gameObject);
}
}
}
[OneTimeSetUp]
public void RunBeforeAnyTests()
{
m_container = new GameObject("Singletons for TestBrush");
Coords.AsLocal[m_container.transform] = TrTransform.identity;
var path = Path.Combine(Application.dataPath, "../Support/Sketches/PerfTest/Simple.tilt");
m_testStrokes = GetStrokesFromTilt(path);
if (DevOptions.I == null)
{
m_needSingletonTeardown = true;
App.Instance = GameObject.Find("/App").GetComponent<App>();
Config.m_SingletonState = GameObject.Find("/App/Config").GetComponent<Config>();
DevOptions.I = App.Instance.GetComponent<DevOptions>();
// A lot of code needs access to BrushCatalog.Instance.m_guidToBrush.
// We could avoid having to depend on this global state, if only Tilt Brush
// directly referenced BrushDescriptor instead of indirecting through Guid.
BrushCatalog.UnitTestSetUp(m_container);
}
}
[OneTimeTearDown]
public void RunAfterAllTests()
{
Assert.IsTrue(m_container != null);
if (m_needSingletonTeardown)
{
BrushCatalog.UnitTestTearDown(m_container);
DevOptions.I = null;
Config.m_SingletonState = null;
App.Instance = null;
m_needSingletonTeardown = false;
}
UnityEngine.Object.DestroyImmediate(m_container);
}
/// Returns strokes read from the passed .tilt file
public static List<Stroke> GetStrokesFromTilt(string path)
{
var file = new DiskSceneFileInfo(path, readOnly: true);
SketchMetadata metadata;
using (var jsonReader = new JsonTextReader(
new StreamReader(
SaveLoadScript.GetMetadataReadStream(file))))
{
// TODO: should cache this?
var serializer = new JsonSerializer();
serializer.ContractResolver = new CustomJsonContractResolver();
serializer.Error += (sender, args) =>
{
throw new Exception(args.ErrorContext.Error.Message);
};
metadata = serializer.Deserialize<SketchMetadata>(jsonReader);
}
using (var stream = file.GetReadStream(TiltFile.FN_SKETCH))
{
var bufferedStream = new BufferedStream(stream, 4096);
return SketchWriter.GetStrokes(
bufferedStream, metadata.BrushIndex, BitConverter.IsLittleEndian);
}
}
/// Creates and returns a BatchSubset in the passed Canvas.
/// If stroke contains too many CPs to fit, it will be cut short.
/// This differs from what TB does, which is to create multiple subsets.
public static BatchSubset CreateSubsetFromStroke(CanvasScript canvas, Stroke stroke)
{
// See PointerScript.RecreateLineFromMemory
BrushDescriptor desc = BrushCatalog.m_Instance.GetBrush(stroke.m_BrushGuid);
var cp0 = stroke.m_ControlPoints[0];
var xf0 = TrTransform.TRS(cp0.m_Pos, cp0.m_Orient, stroke.m_BrushScale);
BaseBrushScript bbs = BaseBrushScript.Create(
canvas.transform, xf0, desc, stroke.m_Color, stroke.m_BrushSize);
try
{
bbs.SetIsLoading();
Assert.True(bbs.Canvas != null);
foreach (var cp in stroke.m_ControlPoints)
{
bbs.UpdatePosition_LS(
TrTransform.TRS(cp.m_Pos, cp.m_Orient, stroke.m_BrushScale), cp.m_Pressure);
}
return bbs.FinalizeBatchedBrush();
}
finally
{
UnityEngine.Object.DestroyImmediate(bbs.gameObject);
}
}
//
// Tests
//
// Unity thinks it's bad to create MeshFilter-owned Meshes at edit time, and
// will spam an Error log message if you do. This causes the test to fail.
// Every geometry generation unit test should call this.
private void HackIgnoreMeshErrorLog()
{
// The number and type of these messages changes from version to version, so be broad
UnityEngine.TestTools.LogAssert.ignoreFailingMessages = true;
// UnityEngine.TestTools.LogAssert.Expect(LogType.Error, "Instantiating mesh due to calling MeshFilter.mesh during edit mode. This will leak meshes. Please use MeshFilter.sharedMesh instead.");
}
// This test doesn't actually do anything useful except exercise the scaffolding
[Test]
public void CreateSubsetFromStrokeWorksAtEditTime()
{
HackIgnoreMeshErrorLog();
using (var tempCanvas = new TempCanvas())
{
var subset = CreateSubsetFromStroke(tempCanvas.m_canvas, m_testStrokes[0]);
Assert.True(subset != null);
}
}
#if false
// Example code showing the hoops you need to jump through in order to generate
// and examine geometry at edit-time.
// Unit tests run inside an ephemeral scene, so if you want to examine
// the results you need to manually run the test
static public class TestBrushHelper {
[MenuItem("OpenBrush/Run Tests In Scene")]
public static void RunTestsInScene() {
var tb = new TestBrush();
tb.RunBeforeAnyTests();
try {
tb.TimeGeometryGeneration(true);
tb.TimeGeometryGeneration(false);
} finally {
tb.RunAfterAllTests();
}
}
}
class TempEnableReduction : IDisposable {
bool m_prev;
public TempEnableReduction(bool val) {
m_prev = App.Config.m_WeldQuadStripVertices;
App.Config.m_WeldQuadStripVertices = val;
}
void IDisposable.Dispose() { App.Config.m_WeldQuadStripVertices = m_prev; }
}
public void TimeGeometryGeneration(bool withReduction) {
var path = "c:/Users/pld/Documents/Tilt Brush/Sketches/Rescue.tilt";
var strokes = GetStrokesFromTilt(path);
using (var tempCanvas = new TempCanvas(string.Format("reduce {0}", withReduction)))
using (var dummy = new TempEnableReduction(withReduction)) {
var sw = new System.Diagnostics.Stopwatch();
sw.Start();
foreach (var stroke in strokes) {
CreateSubsetFromStroke(tempCanvas.m_canvas, stroke, m_master);
}
sw.Stop();
Debug.LogFormat("Iter {0} elapsed {1}", withReduction, sw.ElapsedMilliseconds * .001f);
}
}
#endif
}
}
| 38.253165 | 205 | 0.608979 | [
"Apache-2.0"
] | Master109/open-brush | Assets/Editor/Tests/TestBrush.cs | 9,066 | C# |
//
// Copyright 2020 Carbonfrost Systems, Inc. (https://carbonfrost.com)
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// https://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 Carbonfrost.Commons.Web.Dom;
namespace Carbonfrost.Commons.Html {
public class HtmlAttributeDefinition : DomAttributeDefinition {
public HtmlAttributeDefinition(string name) : base(DomName.Create(name)) {
}
public HtmlAttributeDefinition(DomName name) : base(name) {
}
}
}
| 33.034483 | 82 | 0.724426 | [
"Apache-2.0"
] | Carbonfrost/f-html | dotnet/src/Carbonfrost.Commons.Html/Src/Carbonfrost/Commons/Html/HtmlAttributeDefinition.cs | 958 | C# |
// ------------------------------------------------------------------------------
// Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information.
// ------------------------------------------------------------------------------
// **NOTE** This file was generated by a tool and any changes will be overwritten.
// <auto-generated/>
// Template Source: MethodRequestBuilder.cs.tt
namespace Microsoft.Graph
{
using System;
using System.Collections.Generic;
using System.IO;
/// <summary>
/// The type WorkbookFunctionsSignRequestBuilder.
/// </summary>
public partial class WorkbookFunctionsSignRequestBuilder : BaseActionMethodRequestBuilder<IWorkbookFunctionsSignRequest>, IWorkbookFunctionsSignRequestBuilder
{
/// <summary>
/// Constructs a new <see cref="WorkbookFunctionsSignRequestBuilder"/>.
/// </summary>
/// <param name="requestUrl">The URL for the request.</param>
/// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param>
/// <param name="number">A number parameter for the OData method call.</param>
public WorkbookFunctionsSignRequestBuilder(
string requestUrl,
IBaseClient client,
System.Text.Json.JsonDocument number)
: base(requestUrl, client)
{
this.SetParameter("number", number, true);
}
/// <summary>
/// A method used by the base class to construct a request class instance.
/// </summary>
/// <param name="functionUrl">The request URL to </param>
/// <param name="options">The query and header options for the request.</param>
/// <returns>An instance of a specific request class.</returns>
protected override IWorkbookFunctionsSignRequest CreateRequest(string functionUrl, IEnumerable<Option> options)
{
var request = new WorkbookFunctionsSignRequest(functionUrl, this.Client, options);
if (this.HasParameter("number"))
{
request.RequestBody.Number = this.GetParameter<System.Text.Json.JsonDocument>("number");
}
return request;
}
}
}
| 41.8 | 162 | 0.606351 | [
"MIT"
] | Aliases/msgraph-sdk-dotnet | src/Microsoft.Graph/Generated/requests/WorkbookFunctionsSignRequestBuilder.cs | 2,299 | C# |
namespace Zinnia.Event.Proxy
{
using System;
using UnityEngine.Events;
using Zinnia.Data.Type;
/// <summary>
/// Emits a <see cref="UnityEvent"/> with a <see cref="TransformData"/> payload whenever <see cref="SingleEventProxyEmitter{TValue,TEvent}.Receive"/> is called.
/// </summary>
public class TransformDataProxyEmitter : SingleEventProxyEmitter<TransformData, TransformDataProxyEmitter.UnityEvent>
{
/// <summary>
/// Defines the event with the specified state.
/// </summary>
[Serializable]
public class UnityEvent : UnityEvent<TransformData> { }
}
} | 35.222222 | 164 | 0.66877 | [
"MIT"
] | fight4dream/Zinnia.Unity | Runtime/Event/Proxy/TransformDataProxyEmitter.cs | 636 | C# |
//-----------------------------------------------------------------------
// <copyright file="ActorCellTests_SerializationOfUserMessages.cs" company="Akka.NET Project">
// Copyright (C) 2009-2021 Lightbend Inc. <http://www.lightbend.com>
// Copyright (C) 2013-2021 .NET Foundation <https://github.com/akkadotnet/akka.net>
// </copyright>
//-----------------------------------------------------------------------
using System;
using Akka.Actor;
using Akka.TestKit;
using Akka.Tests.TestUtils;
using Xunit;
namespace Akka.Tests.Actor
{
public class WhenSerializeAllMessagesIsOff : AkkaSpec
{
public class SomeUserMessage : Comparable
{
public string A { get; set; }
public int B { get; set; }
public Guid C { get; set; }
}
public WhenSerializeAllMessagesIsOff()
: base(@"akka.actor.serialize-messages = off")
{
}
[Fact]
public void Does_not_serializes_user_messages()
{
var message = new SomeUserMessage
{
A = "abc",
B = 123,
C = Guid.Empty
};
TestActor.Tell(message);
var result = ExpectMsg<SomeUserMessage>();
Assert.False(Sys.Settings.SerializeAllMessages);
Assert.Equal(message, result);
Assert.Same(message, result);
}
}
public class WhenSerializeAllMessagesIsOn : AkkaSpec
{
public class SomeUserMessage : Comparable
{
public string A { get; set; }
public int B { get; set; }
public Guid C { get; set; }
}
public WhenSerializeAllMessagesIsOn():base(@"akka.actor.serialize-messages = on")
{
}
[Fact]
public void Do_serialize_user_messages()
{
var message = new SomeUserMessage
{
A = "abc",
B = 123,
C = Guid.Empty
};
TestActor.Tell(message);
var result = ExpectMsg<SomeUserMessage>();
Assert.True(Sys.Settings.SerializeAllMessages);
Assert.Equal(message, result);
Assert.NotSame(message, result);
}
}
}
| 27.566265 | 94 | 0.509178 | [
"Apache-2.0"
] | Aaronontheweb/akka.net | src/core/Akka.Tests/Actor/ActorCellTests_SerializationOfUserMessages.cs | 2,290 | C# |
namespace BeautyBooking.Web.ViewModels.Salons
{
using BeautyBooking.Data.Models;
using BeautyBooking.Services.Mapping;
public class SalonServiceViewModel : IMapFrom<SalonService>
{
public string SalonId { get; set; }
public int ServiceId { get; set; }
public string ServiceName { get; set; }
public string ServiceDescription { get; set; }
public bool Available { get; set; }
}
}
| 23.421053 | 63 | 0.658427 | [
"MIT"
] | DiePathologie/BeautySalon | Web/BeautyBooking.Web.ViewModels/Salons/SalonServiceViewModel.cs | 447 | C# |
using System;
using Core.Commands;
using EventSourcing.Sample.Clients.Contracts.Clients.DTOs;
namespace EventSourcing.Sample.Clients.Contracts.Clients.Commands
{
public class CreateClient: ICommand
{
public Guid? Id { get; set; }
public ClientInfo Data { get; }
public CreateClient(Guid? id, ClientInfo data)
{
Id = id;
Data = data;
}
}
}
| 21.947368 | 65 | 0.623501 | [
"MIT"
] | NicoJuicy/EventSourcing.NetCore | Sample/BankAccounts/EventSourcing.Sample.Clients.Contracts/Clients/Commands/CreateClient.cs | 417 | 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 1.0.0.0
// Changes may cause incorrect behavior and will be lost if the code is
// regenerated.
namespace Microsoft.Azure.Management.EventHub.Models
{
using Azure;
using Management;
using EventHub;
using Rest;
using Rest.Azure;
using Newtonsoft.Json;
using System.Collections;
using System.Collections.Generic;
/// <summary>
/// Defines a page in Azure responses.
/// </summary>
/// <typeparam name="T">Type of the page content items</typeparam>
[JsonObject]
public class Page<T> : IPage<T>
{
/// <summary>
/// Gets the link to the next page.
/// </summary>
[JsonProperty("nextLink")]
public string NextPageLink { get; private set; }
[JsonProperty("value")]
private IList<T> Items{ get; set; }
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A an enumerator that can be used to iterate through the collection.</returns>
public IEnumerator<T> GetEnumerator()
{
return Items == null ? System.Linq.Enumerable.Empty<T>().GetEnumerator() : Items.GetEnumerator();
}
/// <summary>
/// Returns an enumerator that iterates through the collection.
/// </summary>
/// <returns>A an enumerator that can be used to iterate through the collection.</returns>
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
}
}
| 31.821429 | 111 | 0.617845 | [
"MIT"
] | azuresdkci1x/azure-sdk-for-net-1722 | src/SDKs/EventHub/Management.EventHub/Generated/Models/Page.cs | 1,782 | C# |
// FlaxVoxels (c) 2018-2019 Damian 'Erdroy' Korczowski
using System.Collections.Generic;
using System.Linq;
using FlaxEngine;
namespace FlaxVoxels.Gameplay
{
/// <inheritdoc />
/// <summary>
/// FreeCameraController script. Provides basic camera controls.
/// </summary>
public class FreeCameraController : Script
{
private Vector3 _targetRotation;
private Vector3 _targetPosition;
private readonly List<Vector2> _deltaBuffer = new List<Vector2>();
private Vector2 _lastDelta = Vector2.Zero;
private Vector2 _lastCursorPosition = Vector2.Zero;
public override void OnStart()
{
base.OnStart();
_targetPosition = Transform.Translation;
}
public override void OnUpdate()
{
base.OnUpdate();
if (Input.GetMouseButtonDown(MouseButton.Right))
_lastCursorPosition = Input.MousePosition;
if (!Input.GetMouseButton(MouseButton.Right))
return;
UpdateLook();
UpdateMovement();
Actor.Orientation = Quaternion.RotationYawPitchRoll(_targetRotation.X * Mathf.DegreesToRadians, _targetRotation.Y * Mathf.DegreesToRadians, _targetRotation.Z * Mathf.DegreesToRadians);
Actor.Position = Vector3.Lerp(Actor.Position, _targetPosition, CameraSmoothing * Time.DeltaTime);
}
private void UpdateLook()
{
var cursorDelta = (Input.MousePosition - _lastCursorPosition) * MouseSensitivity;
_lastCursorPosition = Input.MousePosition;
if (MouseFiltering)
{
// Update buffer
_deltaBuffer.Add(cursorDelta);
while (_deltaBuffer.Count > MouseFilteringFrames)
_deltaBuffer.RemoveAt(0);
cursorDelta = _deltaBuffer.Aggregate(Vector2.Zero, (current, delta) => current + delta);
cursorDelta /= _deltaBuffer.Count;
}
if (MouseAcceleration)
{
var tmp = cursorDelta;
cursorDelta = (cursorDelta + _lastDelta) * MouseAccelerationMultiplier;
_lastDelta = tmp;
}
_targetRotation += new Vector3(cursorDelta.X / 10.0f, cursorDelta.Y / 10.0f, 0.0f);
// Clamp Y
_targetRotation.Y = Mathf.Clamp(_targetRotation.Y, -89.9f, 89.9f);
}
private void UpdateMovement()
{
var direction = Vector3.Zero;
var transform = Transform;
var currentSpeed = 10.0f;
if (Input.GetKey(KeyboardKeys.Shift))
currentSpeed *= 2.5f;
if (Input.GetKey(KeyboardKeys.Control))
currentSpeed *= 0.05f;
if (Input.GetKey(KeyboardKeys.W))
direction += transform.Forward;
if (Input.GetKey(KeyboardKeys.S))
direction -= transform.Forward;
if (Input.GetKey(KeyboardKeys.A))
direction -= transform.Right;
if (Input.GetKey(KeyboardKeys.D))
direction += transform.Right;
if (Input.GetKey(KeyboardKeys.E))
direction += transform.Up;
if (Input.GetKey(KeyboardKeys.Q))
direction -= transform.Up;
direction.Normalize();
direction *= currentSpeed;
direction *= 100.0f; // Flax is in centimeters
_targetPosition += direction * Time.DeltaTime;
}
public bool MouseFiltering { get; set; } = true;
public int MouseFilteringFrames { get; set; } = 3;
public bool MouseAcceleration { get; set; } = true;
public float MouseAccelerationMultiplier { get; set; } = 0.7f;
public float MouseSensitivity { get; set; } = 2.0f;
public float CameraSmoothing { get; set; } = 20.0f;
}
}
| 33.218487 | 196 | 0.579307 | [
"MIT"
] | Erdroy/FlaxVoxels | Source/Game/FlaxVoxels/Gameplay/FreeCameraController.cs | 3,953 | C# |
//========= Copyright 2016-2018, HTC Corporation. All rights reserved. ===========
// this file is fully replaced by UnityEngineVRModule_5_5 | 47.333333 | 83 | 0.676056 | [
"MIT"
] | JacobDusseault/smithy | Assets/HTC.UnityPlugin/VRModule/Modules/UnityEngineVRModule_5_6.cs | 144 | C# |
namespace p04._01.FirstAndReserveTeam
{
using p04._01.FirstAndReserveTeam.Core;
public class Person
{
private string firstName;
private string lastName;
private int age;
private decimal salary;
public Person(
string firstName,
string lastName,
int age,
decimal salary)
{
this.FirstName = firstName;
this.LastName = lastName;
this.Age = age;
this.Salary = salary;
}
public string FirstName
{
get
{
return this.firstName;
}
private set
{
Validation.ValidateName(value, "First");
this.firstName = value;
}
}
public string LastName
{
get
{
return this.lastName;
}
private set
{
Validation.ValidateName(value, "Last");
this.lastName = value;
}
}
public int Age
{
get
{
return this.age;
}
private set
{
Validation.ValidateAge(value);
this.age = value;
}
}
public decimal Salary
{
get
{
return this.salary;
}
private set
{
Validation.ValidateSalary(value);
this.salary = value;
}
}
public void IncreaseSalary(decimal percentage)
{
if (this.Age > 30)
{
this.Salary += this.Salary * percentage / 100;
}
else
{
this.Salary += this.Salary * percentage / 200;
}
}
public override string ToString()
{
string result = string.Empty;
result = string.Format(
$"{this.FirstName} {this.LastName} gets {this.Salary:F2} leva.");
return result;
}
}
}
| 20.523364 | 81 | 0.413024 | [
"MIT"
] | vesy53/SoftUni | C# Advanced/C# OOP/LabAndExercises/05.EncapsulationLab/p04.01.FirstAndReserveTeam/Person.cs | 2,198 | C# |
using Xunit;
namespace Project048.UnitTests;
public class UnitTest1
{
[Fact]
public void Test1()
{
}
} | 10.083333 | 31 | 0.636364 | [
"MIT"
] | reduckted/ProjectFilter | sample/Large/tests/Beta/Project048.UnitTests/UnitTest1.cs | 121 | C# |
using System;
namespace MasterChief.DotNet4.Utilities.Common
{
/// <summary>
/// Double 帮助类
/// </summary>
public static class DoubleHelper
{
#region Methods
/// <summary>
/// 计算百分比(保持两位小数)
/// </summary>
/// <param name="value">The value.</param>
/// <param name="total">The total.</param>
/// <returns>double</returns>
/// 日期:2015-09-16 13:57
/// 备注:
public static double CalcPercentage(double value, double total)
{
return Math.Round(100 * value / total, 2);
}
/// <summary>
/// 转换成钱表示形式(保持两位小数)
/// </summary>
/// <param name="data">The data.</param>
/// <returns>double</returns>
/// 日期:2015-09-16 13:57
/// 备注:
public static double ToMoney(this double data)
{
return Math.Round(data, 2);
}
#endregion Methods
}
} | 24.794872 | 71 | 0.496381 | [
"MIT"
] | AkonCoder/MasterChief | MasterChief.DotNet4.Utilities/Common/DoubleHelper.cs | 1,053 | C# |
#if !FRAMEWORK35
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;
namespace NightlyCode.Japi.Json.Expressions {
/// <summary>
/// serializes <see cref="BlockExpression"/>s
/// </summary>
public class BlockExpressionSerializer : ISpecificExpressionSerializer {
readonly IJsonSerializer serializer;
/// <summary>
/// creates a new <see cref="BlockExpressionSerializer"/>
/// </summary>
/// <param name="serializer"></param>
public BlockExpressionSerializer(IJsonSerializer serializer) {
this.serializer = serializer;
}
public void Serialize(JsonObject json, Expression expression) {
BlockExpression block = (BlockExpression)expression;
json["expressions"] = new JsonArray(block.Expressions.Select(serializer.Write));
json["variables"] = new JsonArray(block.Variables.Select(serializer.Write));
}
public Expression Deserialize(JsonObject json) {
return Expression.Block(
json["variables"].Select(serializer.Read<ParameterExpression>),
json["expressions"].Select(serializer.Read<Expression>)
);
}
public IEnumerable<ExpressionType> Supported
{
get { yield return ExpressionType.Block; }
}
}
}
#endif | 31.636364 | 92 | 0.637213 | [
"Unlicense"
] | telmengedar/japi | Japi/Json/Expressions/BlockExpressionSerializer.cs | 1,394 | C# |
using Renci.SshNet;
using Renci.SshNet.Common;
using SSH.Stores;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Management.Automation;
using System.Management.Automation.Host;
using System.Text;
namespace SSH
{
[Cmdlet(VerbsCommon.Set, "SCPFile", DefaultParameterSetName = "NoKey")]
public class SetScpFile : NewSessionBase
{
internal override PoshSessionType Protocol
{
get
{
return PoshSessionType.SCP;
}
}
//Local File
private String _localfile = "";
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
Position = 2)]
[Alias("FullName")]
public String LocalFile
{
get { return _localfile; }
set { _localfile = value; }
}
//Remote File
private String _remotepath = "";
[Parameter(Mandatory = true,
ValueFromPipelineByPropertyName = true,
Position = 3)]
public String RemotePath
{
get { return _remotepath; }
set { _remotepath = value; }
}
// Supress progress bar.
private bool _noProgress = false;
[Parameter(Mandatory = false,
ValueFromPipelineByPropertyName = true)]
public SwitchParameter NoProgress
{
get { return _noProgress; }
set { _noProgress = value; }
}
protected override void ProcessRecord()
{
foreach (var computer in ComputerName)
{
var client = CreateConnection(computer) as ScpClient;
try
{
if (client != default && client.IsConnected)
{
var _progresspreference = (ActionPreference)this.SessionState.PSVariable.GetValue("ProgressPreference");
if (_noProgress == false)
{
var counter = 0;
// Print progess of download.
client.Uploading += delegate (object sender, ScpUploadEventArgs e)
{
if (e.Size != 0)
{
counter++;
if (counter > 900)
{
var percent = Convert.ToInt32((e.Uploaded * 100) / e.Size);
if (percent == 100)
{
return;
}
var progressRecord = new ProgressRecord(1,
"Uploading " + e.Filename,
String.Format("{0} Bytes Uploaded of {1}",
e.Uploaded, e.Size))
{ PercentComplete = percent };
Host.UI.WriteProgress(1, progressRecord);
counter = 0;
}
}
};
}
WriteVerbose("Connection successful");
// Resolve the path even if a relative one is given.
ProviderInfo provider;
var pathinfo = GetResolvedProviderPathFromPSPath(_localfile, out provider);
var localfullPath = pathinfo[0];
if (File.Exists(@localfullPath))
{
try
{
WriteVerbose("Uploading " + localfullPath);
var fil = new FileInfo(@localfullPath);
var remoteFullpath = RemotePath.TrimEnd(new[] { '/' }) + "/" + fil.Name;
client.Upload(fil, remoteFullpath);
client.Disconnect();
}
catch (Exception e)
{
ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.InvalidOperation, client);
WriteError(erec);
}
}
else
{
var ex = new FileNotFoundException("File to upload " + localfullPath + " was not found.");
WriteError(new ErrorRecord(ex,
"File to upload " + localfullPath + " was not found.",
ErrorCategory.InvalidArgument,
localfullPath));
}
client.Disconnect();
}
}
catch (Exception e)
{
ErrorRecord erec = new ErrorRecord(e, null, ErrorCategory.OperationStopped, client);
WriteError(erec);
}
}
} // End process record
} //end of the class for the Set-SCPFile
////###################################################
}
| 37.298013 | 128 | 0.402521 | [
"BSD-3-Clause"
] | FDlucifer/Posh-SSH | Source/PoshSSH/PoshSSH/SetScpFile.cs | 5,634 | C# |
using System.Linq;
using Conflux.ABI.Model;
namespace Conflux.ABI
{
public class TupleType : ABIType
{
public Parameter[] Components { get; protected set; }
public void SetComponents(Parameter[] components)
{
this.Components = components;
((TupleTypeEncoder) Encoder).Components = components;
((TupleTypeDecoder) Decoder).Components = components;
}
public TupleType() : base("tuple")
{
Decoder = new TupleTypeDecoder();
Encoder = new TupleTypeEncoder();
}
public override int FixedSize {
get
{
if (Components == null) return -1;
if (Components.Any(x => x.ABIType.IsDynamic())) return -1;
return Components.Sum(x => x.ABIType.FixedSize);
}
}
}
} | 27.375 | 74 | 0.545662 | [
"Apache-2.0",
"MIT"
] | NconfluxSDK/Nconflux | src/Conflux.ABI/TupleType.cs | 876 | C# |
using System;
namespace _41_Sweet_Dreams
{
public class Program
{
public static void Main(string[] args)
{
decimal cash = decimal.Parse(Console.ReadLine());
decimal guests = int.Parse(Console.ReadLine());
decimal aBanana = decimal.Parse(Console.ReadLine());
decimal anEgg = decimal.Parse(Console.ReadLine());
decimal kgBerries = decimal.Parse(Console.ReadLine());
decimal groupsOfGuests = Math.Ceiling(guests / 6);
decimal bananas = ((groupsOfGuests * 2) * aBanana);
decimal eggs = ((groupsOfGuests * 4) * anEgg);
decimal berries = (groupsOfGuests * ( kgBerries / 5));
decimal groceriesSum = bananas + eggs + berries;
if(groceriesSum <= cash)
{
Console.WriteLine($"Ivancho has enough money - it would cost {groceriesSum:f2}lv.");
}
else
{
Console.WriteLine($"Ivancho will have to withdraw money - he will need {Math.Abs(groceriesSum-cash):f2}lv more.");
}
}
}
}
| 35.1875 | 130 | 0.563943 | [
"MIT"
] | martinmihov/Programming-Fundamentals | ExamPreparation/41 Sweet Dreams/Program.cs | 1,128 | C# |
using System;
using System.Data.OleDb;
namespace Kutuphane.Data
{
//Bu class bizim Base Classımız. Yani Data katmanındaki diğer classların ortak olarak kalıtım alacağı sınıf bu sınıf
//Neden abstract?
//interface= nesnesi oluşturulamaz | body'e sahip metod yok |public destekliyor
//abstract= nesnesi oluşturulamaz | body'e sahip metod var |private,protected,public destekliyor
//Öncelikle bu classı nesne olarak çağırmayacağım için aklıma bu classı abstract veya interface yapmak geldi.
//Veritabanı bağlantısında kullandığım değişkenleri constructor'da oluşturmak ve destructor'da imha etmek istiyordum.
//Bu sebeple body'li metodları destekleyen abstract class'ı kullanma kararı aldım.
abstract class VeritabaniBaglanti
{
protected OleDbConnection con; //Data katmanındaki diğer classlar için ortak olarak kullanılacak olan değişkenlerini
//bu classta tanımlıyorum. Bu sayede kod tekrarını azaltmış oluyoruz.
protected OleDbDataAdapter da;
protected OleDbCommand cmd; //değişkenleri sadece bu classın metotları ve bu classtan kalıtım alan diğer classlar
//ulaşabilsin diye protected olarak tanımladım
protected string query;
protected string constring;
public VeritabaniBaglanti()
{
//Environment.UserName ifadesi windowsa login olmuş olan kullanıcının adını veriyor
constring = "C:\\Users\\"+Environment.UserName+"\\AppData\\Roaming\\Kutuphane\\Kutuphane.accdb";
//Veritabanı bağlantımızı gerçekleştirmek için connectionstringimizi hazırlıyoruz.
con = new OleDbConnection("Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + constring);
}
~VeritabaniBaglanti()
{
con.Dispose(); //Dispose() metodu ile con değişkenini imha ediyor ve ramde kapladığı alanı serbest bırakıyoruz.
}
}
}
| 51.526316 | 124 | 0.704801 | [
"MIT"
] | durmazoguzhan/library | Kutuphane/Data/VeritabaniBaglanti.cs | 2,045 | C# |
using System;
using Verse;
using System.Xml;
using RimWorld;
namespace JecsTools
{
//Based on Verse.ThingCountClass
public sealed class StuffCategoryCountClass
{
public StuffCategoryDef stuffCatDef;
public int count;
public string Summary {
get {
return this.count + "x " + ((this.stuffCatDef == null) ? "null" : this.stuffCatDef.label);
}
}
public StuffCategoryCountClass()
{
}
public StuffCategoryCountClass(StuffCategoryDef stuffCatDef, int count)
{
this.stuffCatDef = stuffCatDef;
this.count = count;
}
public void LoadDataFromXmlCustom(XmlNode xmlRoot)
{
if (xmlRoot.ChildNodes.Count != 1) {
Log.Error("Misconfigured StuffCategoryCount: " + xmlRoot.OuterXml);
return;
}
DirectXmlCrossRefLoader.RegisterObjectWantsCrossRef(this, "stuffCatDef", xmlRoot.Name);
this.count = (int)ParseHelper.FromString(xmlRoot.FirstChild.Value, typeof(int));
}
public override string ToString()
{
return string.Concat(new object[]
{
"(",
this.count,
"x ",
(this.stuffCatDef == null) ? "null" : this.stuffCatDef.defName,
")"
});
}
public override int GetHashCode()
{
return (int)this.stuffCatDef.shortHash + this.count << 16;
}
}
}
| 26.745763 | 106 | 0.536122 | [
"MIT"
] | RimWorld-CCL-Reborn/JecsTools | Source/AllModdingComponents/JecsTools/StuffCategoryCountClass.cs | 1,580 | C# |
using System;
using Bard.Configuration;
using Grpc.Core;
namespace Bard.gRPC
{
/// <summary>
/// ScenarioOptions supplies all the necessary configuration
/// necessary to customize and bootstrap a working
/// gRPC Scenario
/// </summary>
public class GrpcScenarioOptions<TGrpcClient> : ScenarioOptions where TGrpcClient : ClientBase<TGrpcClient>
{
/// <summary>
/// The function to create a gRPC client
/// </summary>
public Func<CallInvoker, TGrpcClient>? GrpcClient { get; set; }
}
/// <summary>
/// ScenarioOptions supplies all the necessary configuration
/// necessary to customize and bootstrap a working
/// gRPC Scenario with StoryBook
/// </summary>
public class GrpcScenarioOptions<TGrpcClient, TStoryBook> : GrpcScenarioOptions<TGrpcClient>
where TGrpcClient : ClientBase<TGrpcClient> where TStoryBook : new()
{
internal GrpcScenarioOptions()
{
Story = new TStoryBook();
}
internal TStoryBook Story { get; }
}
} | 31.457143 | 111 | 0.637602 | [
"MIT"
] | FaithLV/Bard | src/Bard.gRPC/GrpcScenarioOptions.cs | 1,103 | C# |
using SkiaSharp;
using System.Windows;
namespace PaunPacker.GUI.Views
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public MainWindow()
{
InitializeComponent();
}
}
}
| 18.529412 | 46 | 0.555556 | [
"MIT"
] | pdokoupil/PaunPacker | PaunPacker.GUI/Views/MainWindow.xaml.cs | 317 | C# |
using Database.Models.MedievalBattleModels;
using Microsoft.EntityFrameworkCore;
namespace Database.Models
{
public class DatabaseContext : DbContext
{
public DatabaseContext()
{
}
public DatabaseContext(DbContextOptions options) : base(options)
{
}
//public DbSet<Unit> Units { get; set; }
//public DbSet<UnitClasses> UnitClasses { get; set; }
//public DbSet<MapPositioning> MapPositionings { get; set; }
//public DbSet<Position> Positions { get; set; }
//public DbSet<Player> Players { get; set; }
//public DbSet<MedievalBattle> MedievalBattles { get; set; }
public DbSet<MedievalBattleStats> MedievalBattleStats { get; set; }
public DbSet<SessionMedievalBattle> SessionMedievalBattles { get; set; }
public DbSet<User> Users { get; set; }
public DbSet<UserStatistics> UserStatistics { get; set; }
public DbSet<UsersSessionsMedievalBattle> UsersSessionsMedievalBattle { get; set; }
// MEDIEVAL BATTLE DB
public DbSet<AbstractField> AbstractFields { get; set; }
public DbSet<GameController> GameControllers { get; set; }
public DbSet<Unit> Units { get; set; }
public DbSet<Archer> Archers { get; set; }
public DbSet<Fighter> Fighters { get; set; }
public DbSet<Flank> Flanks { get; set; }
public DbSet<Coin> Coins { get; set; }
public DbSet<AliveField> aliveFieldsCount { get; set; }
protected override void OnConfiguring(DbContextOptionsBuilder optionsBuilder)
{
if (!optionsBuilder.IsConfigured)
{
#warning To protect potentially sensitive information in your connection string, you should move it out of source code. See http://go.microsoft.com/fwlink/?LinkId=723263 for guidance on storing connection strings.
optionsBuilder.UseSqlServer("Server=25.98.56.253;Database=MGP;MultipleActiveResultSets=true;User ID=sa;Password=OKTyaBRSkOE123;");
}
}
}
}
| 41.14 | 213 | 0.660671 | [
"MIT"
] | liquiz0v/MessengerGamingPlatform | Backend-dotnet/MessengerGamingPlatform/Database/Data/DatabaseContext.cs | 2,059 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using workIT.Models.Common;
namespace workIT.Models.API
{
public class FinancialAssistanceProfile
{
public FinancialAssistanceProfile()
{
CTDLTypeLabel = "Financial Assistance Profile";
}
public string CTDLTypeLabel { get; set; }
public int? Id { get; set; }
/// <summary>
/// name
/// </summary>
public string Name { get; set; }
public string Description { get; set; }
/// <summary>
/// SubjectWebpage - URI
/// </summary>
public string SubjectWebpage { get; set; }
public List<LabelLink> FinancialAssistanceType { get; set; } = new List<LabelLink>();
public List<string> FinancialAssistanceValue { get; set; }
public List<QuantitativeValue> FinancialAssistanceValue2 { get; set; }
}
}
| 23.054054 | 87 | 0.701055 | [
"Apache-2.0"
] | CredentialEngine/Import_From_Registry | src/workIT.Models/API/FinancialAssistanceProfile.cs | 855 | C# |
using System;
using MediatR;
namespace Gear.ProjectManagement.Manager.Domain.ActivityCheckList.Commands.DeleteCheckItem
{
public class DeleteCheckItemCommand : IRequest
{
public Guid CheckItemId { get; set; }
}
}
| 21.363636 | 90 | 0.740426 | [
"MIT"
] | indrivo/bizon360_pm | IndrivoPM/Gear.ProjectManagement.Application/Domain/ActivityCheckList/Commands/DeleteCheckItem/DeleteCheckItemCommand.cs | 237 | C# |
using DG.Tweening;
using UnityEngine;
public class CompatibilityTest : MonoBehaviour
{
public Transform cubeCont;
public Transform[] cubes;
public GUITexture logo;
Tween twSuccess;
bool success;
Color logoCol;
void Start()
{
DOTween.Init(true);
Color c = logoCol = logo.color;
c.a = 0;
logo.color = c;
// Create sequence
Sequence seq = DOTween.Sequence()
.SetLoops(-1, LoopType.Restart)
.OnStepComplete(Success);
seq.Append(cubeCont.DORotate(new Vector3(0, 720, 360), 2.25f).SetRelative().SetEase(Ease.Linear));
foreach (Transform trans in cubes) {
Transform t = trans;
seq.Insert(0, t.DOScale(Vector3.one * 0.5f, 1f));
seq.Insert(0, t.DOLocalMove(t.position * 8, 1f).SetEase(Ease.InQuint));
seq.Insert(1, t.DOScale(Vector3.one * 0.5f, 1f));
seq.Insert(1, t.DOLocalMove(t.position, 1f).SetEase(Ease.OutQuint));
}
// Create success tween
twSuccess = DOTween.To(()=> logo.color, x => logo.color = x, logoCol, 1.25f).Pause();
}
void Success()
{
if (success) return;
success = true;
twSuccess.Play();
}
} | 23.733333 | 100 | 0.678839 | [
"Unlicense"
] | HelloWindows/AccountBook | client/framework/dotween-develop/UnityCompatibilityTests.Unity35/Assets/CompatibilityTest.cs | 1,068 | 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.VMware.Cmdlets
{
using static Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Extensions;
using System;
/// <summary>List clusters in a private cloud</summary>
/// <remarks>
/// [OpenAPI] List=>GET:"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.AVS/privateClouds/{privateCloudName}/clusters"
/// </remarks>
[global::System.Management.Automation.Cmdlet(global::System.Management.Automation.VerbsCommon.Get, @"AzVMwareCluster_List")]
[global::System.Management.Automation.OutputType(typeof(Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20210601.ICluster))]
[global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Description(@"List clusters in a private cloud")]
[global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Generated]
public partial class GetAzVMwareCluster_List : global::System.Management.Automation.PSCmdlet,
Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener
{
/// <summary>A unique id generatd for the this cmdlet when it is instantiated.</summary>
private string __correlationId = System.Guid.NewGuid().ToString();
/// <summary>A copy of the Invocation Info (necessary to allow asJob to clone this cmdlet)</summary>
private global::System.Management.Automation.InvocationInfo __invocationInfo;
/// <summary>A unique id generatd for the this cmdlet when ProcessRecord() is called.</summary>
private string __processRecordId;
/// <summary>
/// The <see cref="global::System.Threading.CancellationTokenSource" /> for this operation.
/// </summary>
private global::System.Threading.CancellationTokenSource _cancellationTokenSource = new global::System.Threading.CancellationTokenSource();
/// <summary>Wait for .NET debugger to attach</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Wait for .NET debugger to attach")]
[global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter Break { get; set; }
/// <summary>The reference to the client API class.</summary>
public Microsoft.Azure.PowerShell.Cmdlets.VMware.VMware Client => Microsoft.Azure.PowerShell.Cmdlets.VMware.Module.Instance.ClientAPI;
/// <summary>
/// The credentials, account, tenant, and subscription used for communication with Azure
/// </summary>
[global::System.Management.Automation.Parameter(Mandatory = false, HelpMessage = "The credentials, account, tenant, and subscription used for communication with Azure.")]
[global::System.Management.Automation.ValidateNotNull]
[global::System.Management.Automation.Alias("AzureRMContext", "AzureCredential")]
[global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Azure)]
public global::System.Management.Automation.PSObject DefaultProfile { get; set; }
/// <summary>SendAsync Pipeline Steps to be appended to the front of the pipeline</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be appended to the front of the pipeline")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Runtime)]
public Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.SendAsyncStep[] HttpPipelineAppend { get; set; }
/// <summary>SendAsync Pipeline Steps to be prepended to the front of the pipeline</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "SendAsync Pipeline Steps to be prepended to the front of the pipeline")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Runtime)]
public Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.SendAsyncStep[] HttpPipelinePrepend { get; set; }
/// <summary>Accessor for our copy of the InvocationInfo.</summary>
public global::System.Management.Automation.InvocationInfo InvocationInformation { get => __invocationInfo = __invocationInfo ?? this.MyInvocation ; set { __invocationInfo = value; } }
/// <summary>
/// <see cref="IEventListener" /> cancellation delegate. Stops the cmdlet when called.
/// </summary>
global::System.Action Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener.Cancel => _cancellationTokenSource.Cancel;
/// <summary><see cref="IEventListener" /> cancellation token.</summary>
global::System.Threading.CancellationToken Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener.Token => _cancellationTokenSource.Token;
/// <summary>
/// The instance of the <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.HttpPipeline" /> that the remote call will use.
/// </summary>
private Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.HttpPipeline Pipeline { get; set; }
/// <summary>Backing field for <see cref="PrivateCloudName" /> property.</summary>
private string _privateCloudName;
/// <summary>Name of the private cloud</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "Name of the private cloud")]
[Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"Name of the private cloud",
SerializedName = @"privateCloudName",
PossibleTypes = new [] { typeof(string) })]
[global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Path)]
public string PrivateCloudName { get => this._privateCloudName; set => this._privateCloudName = value; }
/// <summary>The URI for the proxy server to use</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "The URI for the proxy server to use")]
[global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Runtime)]
public global::System.Uri Proxy { get; set; }
/// <summary>Credentials for a proxy server to use for the remote call</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Credentials for a proxy server to use for the remote call")]
[global::System.Management.Automation.ValidateNotNull]
[global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Runtime)]
public global::System.Management.Automation.PSCredential ProxyCredential { get; set; }
/// <summary>Use the default credentials for the proxy</summary>
[global::System.Management.Automation.Parameter(Mandatory = false, DontShow = true, HelpMessage = "Use the default credentials for the proxy")]
[global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Runtime)]
public global::System.Management.Automation.SwitchParameter ProxyUseDefaultCredentials { get; set; }
/// <summary>Backing field for <see cref="ResourceGroupName" /> property.</summary>
private string _resourceGroupName;
/// <summary>The name of the resource group. The name is case insensitive.</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The name of the resource group. The name is case insensitive.")]
[Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The name of the resource group. The name is case insensitive.",
SerializedName = @"resourceGroupName",
PossibleTypes = new [] { typeof(string) })]
[global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Path)]
public string ResourceGroupName { get => this._resourceGroupName; set => this._resourceGroupName = value; }
/// <summary>Backing field for <see cref="SubscriptionId" /> property.</summary>
private string[] _subscriptionId;
/// <summary>The ID of the target subscription.</summary>
[global::System.Management.Automation.Parameter(Mandatory = true, HelpMessage = "The ID of the target subscription.")]
[Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Info(
Required = true,
ReadOnly = false,
Description = @"The ID of the target subscription.",
SerializedName = @"subscriptionId",
PossibleTypes = new [] { typeof(string) })]
[Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.DefaultInfo(
Name = @"",
Description =@"",
Script = @"(Get-AzContext).Subscription.Id")]
[global::Microsoft.Azure.PowerShell.Cmdlets.VMware.Category(global::Microsoft.Azure.PowerShell.Cmdlets.VMware.ParameterCategory.Path)]
public string[] SubscriptionId { get => this._subscriptionId; set => this._subscriptionId = value; }
/// <summary>
/// <c>overrideOnDefault</c> will be called before the regular onDefault has been processed, allowing customization of what
/// happens on that response. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20210601.ICloudError"
/// /> from the remote call</param>
/// <param name="returnNow">/// Determines if the rest of the onDefault method should be processed, or if the method should
/// return immediately (set to true to skip further processing )</param>
partial void overrideOnDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20210601.ICloudError> response, ref global::System.Threading.Tasks.Task<bool> returnNow);
/// <summary>
/// <c>overrideOnOk</c> will be called before the regular onOk has been processed, allowing customization of what happens
/// on that response. Implement this method in a partial class to enable this behavior
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20210601.IClusterList"
/// /> from the remote call</param>
/// <param name="returnNow">/// Determines if the rest of the onOk method should be processed, or if the method should return
/// immediately (set to true to skip further processing )</param>
partial void overrideOnOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20210601.IClusterList> response, ref global::System.Threading.Tasks.Task<bool> returnNow);
/// <summary>
/// (overrides the default BeginProcessing method in global::System.Management.Automation.PSCmdlet)
/// </summary>
protected override void BeginProcessing()
{
Module.Instance.SetProxyConfiguration(Proxy, ProxyCredential, ProxyUseDefaultCredentials);
if (Break)
{
Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.AttachDebugger.Break();
}
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletBeginProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
/// <summary>Performs clean-up after the command execution</summary>
protected override void EndProcessing()
{
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletEndProcessing).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
/// <summary>
/// Intializes a new instance of the <see cref="GetAzVMwareCluster_List" /> cmdlet class.
/// </summary>
public GetAzVMwareCluster_List()
{
}
/// <summary>Handles/Dispatches events during the call to the REST service.</summary>
/// <param name="id">The message id</param>
/// <param name="token">The message cancellation token. When this call is cancelled, this should be <c>true</c></param>
/// <param name="messageData">Detailed message data for the message event.</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the message is completed.
/// </returns>
async global::System.Threading.Tasks.Task Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener.Signal(string id, global::System.Threading.CancellationToken token, global::System.Func<Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.EventData> messageData)
{
using( NoSynchronizationContext )
{
if (token.IsCancellationRequested)
{
return ;
}
switch ( id )
{
case Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.Verbose:
{
WriteVerbose($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.Warning:
{
WriteWarning($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.Information:
{
var data = messageData();
WriteInformation(data.Message, new string[]{});
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.Debug:
{
WriteDebug($"{(messageData().Message ?? global::System.String.Empty)}");
return ;
}
case Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.Error:
{
WriteError(new global::System.Management.Automation.ErrorRecord( new global::System.Exception(messageData().Message), string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null ) );
return ;
}
}
await Microsoft.Azure.PowerShell.Cmdlets.VMware.Module.Instance.Signal(id, token, messageData, (i,t,m) => ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(i,t,()=> Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.EventDataConverter.ConvertFrom( m() ) as Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.EventData ), InvocationInformation, this.ParameterSetName, __correlationId, __processRecordId, null );
if (token.IsCancellationRequested)
{
return ;
}
WriteDebug($"{id}: {(messageData().Message ?? global::System.String.Empty)}");
}
}
/// <summary>Performs execution of the command.</summary>
protected override void ProcessRecord()
{
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletProcessRecordStart).Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
__processRecordId = System.Guid.NewGuid().ToString();
try
{
// work
using( var asyncCommandRuntime = new Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.PowerShell.AsyncCommandRuntime(this, ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token) )
{
asyncCommandRuntime.Wait( ProcessRecordAsync(),((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token);
}
}
catch (global::System.AggregateException aggregateException)
{
// unroll the inner exceptions to get the root cause
foreach( var innerException in aggregateException.Flatten().InnerExceptions )
{
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletException, $"{innerException.GetType().Name} - {innerException.Message} : {innerException.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
// Write exception out to error channel.
WriteError( new global::System.Management.Automation.ErrorRecord(innerException,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) );
}
}
catch (global::System.Exception exception) when ((exception as System.Management.Automation.PipelineStoppedException)== null || (exception as System.Management.Automation.PipelineStoppedException).InnerException != null)
{
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletException, $"{exception.GetType().Name} - {exception.Message} : {exception.StackTrace}").Wait(); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
// Write exception out to error channel.
WriteError( new global::System.Management.Automation.ErrorRecord(exception,string.Empty, global::System.Management.Automation.ErrorCategory.NotSpecified, null) );
}
finally
{
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletProcessRecordEnd).Wait();
}
}
/// <summary>Performs execution of the command, working asynchronously if required.</summary>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
protected async global::System.Threading.Tasks.Task ProcessRecordAsync()
{
using( NoSynchronizationContext )
{
await ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletProcessRecordAsyncStart); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
await ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletGetPipeline); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
Pipeline = Microsoft.Azure.PowerShell.Cmdlets.VMware.Module.Instance.CreatePipeline(InvocationInformation, __correlationId, __processRecordId, this.ParameterSetName);
if (null != HttpPipelinePrepend)
{
Pipeline.Prepend((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelinePrepend) ?? HttpPipelinePrepend);
}
if (null != HttpPipelineAppend)
{
Pipeline.Append((this.CommandRuntime as Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.PowerShell.IAsyncCommandRuntimeExtensions)?.Wrap(HttpPipelineAppend) ?? HttpPipelineAppend);
}
// get the client instance
try
{
foreach( var SubscriptionId in this.SubscriptionId )
{
await ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletBeforeAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
await this.Client.ClustersList(SubscriptionId, ResourceGroupName, PrivateCloudName, onOk, onDefault, this, Pipeline);
await ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletAfterAPICall); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
}
}
catch (Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.UndeclaredResponseException urexception)
{
WriteError(new global::System.Management.Automation.ErrorRecord(urexception, urexception.StatusCode.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId,ResourceGroupName=ResourceGroupName,PrivateCloudName=PrivateCloudName})
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(urexception.Message) { RecommendedAction = urexception.Action }
});
}
finally
{
await ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.CmdletProcessRecordAsyncEnd);
}
}
}
/// <summary>Interrupts currently running code within the command.</summary>
protected override void StopProcessing()
{
((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Cancel();
base.StopProcessing();
}
/// <summary>
/// a delegate that is called when the remote service returns default (any response code not handled elsewhere).
/// </summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20210601.ICloudError"
/// /> from the remote call</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
private async global::System.Threading.Tasks.Task onDefault(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20210601.ICloudError> response)
{
using( NoSynchronizationContext )
{
var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false);
overrideOnDefault(responseMessage, response, ref _returnNow);
// if overrideOnDefault has returned true, then return right away.
if ((null != _returnNow && await _returnNow))
{
return ;
}
// Error Response : default
var code = (await response)?.Code;
var message = (await response)?.Message;
if ((null == code || null == message))
{
// Unrecognized Response. Create an error record based on what we have.
var ex = new Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.RestException<Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20210601.ICloudError>(responseMessage, await response);
WriteError( new global::System.Management.Automation.ErrorRecord(ex, ex.Code, global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, PrivateCloudName=PrivateCloudName })
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(ex.Message) { RecommendedAction = ex.Action }
});
}
else
{
WriteError( new global::System.Management.Automation.ErrorRecord(new global::System.Exception($"[{code}] : {message}"), code?.ToString(), global::System.Management.Automation.ErrorCategory.InvalidOperation, new { SubscriptionId=SubscriptionId, ResourceGroupName=ResourceGroupName, PrivateCloudName=PrivateCloudName })
{
ErrorDetails = new global::System.Management.Automation.ErrorDetails(message) { RecommendedAction = global::System.String.Empty }
});
}
}
}
/// <summary>a delegate that is called when the remote service returns 200 (OK).</summary>
/// <param name="responseMessage">the raw response message as an global::System.Net.Http.HttpResponseMessage.</param>
/// <param name="response">the body result as a <see cref="Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20210601.IClusterList"
/// /> from the remote call</param>
/// <returns>
/// A <see cref="global::System.Threading.Tasks.Task" /> that will be complete when handling of the method is completed.
/// </returns>
private async global::System.Threading.Tasks.Task onOk(global::System.Net.Http.HttpResponseMessage responseMessage, global::System.Threading.Tasks.Task<Microsoft.Azure.PowerShell.Cmdlets.VMware.Models.Api20210601.IClusterList> response)
{
using( NoSynchronizationContext )
{
var _returnNow = global::System.Threading.Tasks.Task<bool>.FromResult(false);
overrideOnOk(responseMessage, response, ref _returnNow);
// if overrideOnOk has returned true, then return right away.
if ((null != _returnNow && await _returnNow))
{
return ;
}
// onOk - response for 200 / application/json
// response should be returning an array of some kind. +Pageable
// pageable / value / nextLink
var result = await response;
WriteObject(result.Value,true);
if (result.NextLink != null)
{
if (responseMessage.RequestMessage is System.Net.Http.HttpRequestMessage requestMessage )
{
requestMessage = requestMessage.Clone(new global::System.Uri( result.NextLink ),Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Method.Get );
await ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Signal(Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.Events.FollowingNextLink); if( ((Microsoft.Azure.PowerShell.Cmdlets.VMware.Runtime.IEventListener)this).Token.IsCancellationRequested ) { return; }
await this.Client.ClustersList_Call(requestMessage, onOk, onDefault, this, Pipeline);
}
}
}
}
}
} | 72.417073 | 455 | 0.665656 | [
"MIT"
] | Amrinder-Singh29/azure-powershell | src/VMware/generated/cmdlets/GetAzVMwareCluster_List.cs | 29,282 | C# |
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// <auto-generated/>
#nullable disable
using System;
using System.Linq;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;
using Azure.ResourceManager.Core;
using Azure.ResourceManager.Sql.Models;
namespace Azure.ResourceManager.Sql
{
/// <summary> A class to add extension methods to ResourceGroup. </summary>
internal partial class ResourceGroupExtensionClient : ArmResource
{
private ClientDiagnostics _longTermRetentionBackupsClientDiagnostics;
private LongTermRetentionBackupsRestOperations _longTermRetentionBackupsRestClient;
private ClientDiagnostics _longTermRetentionManagedInstanceBackupsClientDiagnostics;
private LongTermRetentionManagedInstanceBackupsRestOperations _longTermRetentionManagedInstanceBackupsRestClient;
/// <summary> Initializes a new instance of the <see cref="ResourceGroupExtensionClient"/> class for mocking. </summary>
protected ResourceGroupExtensionClient()
{
}
/// <summary> Initializes a new instance of the <see cref="ResourceGroupExtensionClient"/> class. </summary>
/// <param name="client"> The client parameters to use in these operations. </param>
/// <param name="id"> The identifier of the resource that is the target of operations. </param>
internal ResourceGroupExtensionClient(ArmClient client, ResourceIdentifier id) : base(client, id)
{
}
private ClientDiagnostics LongTermRetentionBackupsClientDiagnostics => _longTermRetentionBackupsClientDiagnostics ??= new ClientDiagnostics("Azure.ResourceManager.Sql", ProviderConstants.DefaultProviderNamespace, DiagnosticOptions);
private LongTermRetentionBackupsRestOperations LongTermRetentionBackupsRestClient => _longTermRetentionBackupsRestClient ??= new LongTermRetentionBackupsRestOperations(Pipeline, DiagnosticOptions.ApplicationId, BaseUri);
private ClientDiagnostics LongTermRetentionManagedInstanceBackupsClientDiagnostics => _longTermRetentionManagedInstanceBackupsClientDiagnostics ??= new ClientDiagnostics("Azure.ResourceManager.Sql", ProviderConstants.DefaultProviderNamespace, DiagnosticOptions);
private LongTermRetentionManagedInstanceBackupsRestOperations LongTermRetentionManagedInstanceBackupsRestClient => _longTermRetentionManagedInstanceBackupsRestClient ??= new LongTermRetentionManagedInstanceBackupsRestOperations(Pipeline, DiagnosticOptions.ApplicationId, BaseUri);
private string GetApiVersionOrNull(ResourceType resourceType)
{
TryGetApiVersion(resourceType, out string apiVersion);
return apiVersion;
}
/// <summary> Gets a collection of InstanceFailoverGroups in the InstanceFailoverGroup. </summary>
/// <param name="locationName"> The name of the region where the resource is located. </param>
/// <returns> An object representing collection of InstanceFailoverGroups and their operations over a InstanceFailoverGroup. </returns>
public virtual InstanceFailoverGroupCollection GetInstanceFailoverGroups(string locationName)
{
return new InstanceFailoverGroupCollection(Client, Id, locationName);
}
/// <summary> Gets a collection of InstancePools in the InstancePool. </summary>
/// <returns> An object representing collection of InstancePools and their operations over a InstancePool. </returns>
public virtual InstancePoolCollection GetInstancePools()
{
return GetCachedClient(Client => new InstancePoolCollection(Client, Id));
}
/// <summary> Gets a collection of ResourceGroupLongTermRetentionBackups in the ResourceGroupLongTermRetentionBackup. </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="longTermRetentionDatabaseName"> The name of the database. </param>
/// <returns> An object representing collection of ResourceGroupLongTermRetentionBackups and their operations over a ResourceGroupLongTermRetentionBackup. </returns>
public virtual ResourceGroupLongTermRetentionBackupCollection GetResourceGroupLongTermRetentionBackups(string locationName, string longTermRetentionServerName, string longTermRetentionDatabaseName)
{
return new ResourceGroupLongTermRetentionBackupCollection(Client, Id, locationName, longTermRetentionServerName, longTermRetentionDatabaseName);
}
/// <summary> Gets a collection of ResourceGroupLongTermRetentionManagedInstanceBackups in the ResourceGroupLongTermRetentionManagedInstanceBackup. </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="managedInstanceName"> The name of the managed instance. </param>
/// <param name="databaseName"> The name of the managed database. </param>
/// <returns> An object representing collection of ResourceGroupLongTermRetentionManagedInstanceBackups and their operations over a ResourceGroupLongTermRetentionManagedInstanceBackup. </returns>
public virtual ResourceGroupLongTermRetentionManagedInstanceBackupCollection GetResourceGroupLongTermRetentionManagedInstanceBackups(string locationName, string managedInstanceName, string databaseName)
{
return new ResourceGroupLongTermRetentionManagedInstanceBackupCollection(Client, Id, locationName, managedInstanceName, databaseName);
}
/// <summary> Gets a collection of ManagedInstances in the ManagedInstance. </summary>
/// <returns> An object representing collection of ManagedInstances and their operations over a ManagedInstance. </returns>
public virtual ManagedInstanceCollection GetManagedInstances()
{
return GetCachedClient(Client => new ManagedInstanceCollection(Client, Id));
}
/// <summary> Gets a collection of ServerTrustGroups in the ServerTrustGroup. </summary>
/// <param name="locationName"> The name of the region where the resource is located. </param>
/// <returns> An object representing collection of ServerTrustGroups and their operations over a ServerTrustGroup. </returns>
public virtual ServerTrustGroupCollection GetServerTrustGroups(string locationName)
{
return new ServerTrustGroupCollection(Client, Id, locationName);
}
/// <summary> Gets a collection of VirtualClusters in the VirtualCluster. </summary>
/// <returns> An object representing collection of VirtualClusters and their operations over a VirtualCluster. </returns>
public virtual VirtualClusterCollection GetVirtualClusters()
{
return GetCachedClient(Client => new VirtualClusterCollection(Client, Id));
}
/// <summary> Gets a collection of SqlServers in the SqlServer. </summary>
/// <returns> An object representing collection of SqlServers and their operations over a SqlServer. </returns>
public virtual SqlServerCollection GetSqlServers()
{
return GetCachedClient(Client => new SqlServerCollection(Client, Id));
}
/// <summary>
/// Lists the long term retention backups for a given location.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionBackups
/// Operation Id: LongTermRetentionBackups_ListByResourceGroupLocation
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="SubscriptionLongTermRetentionBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<SubscriptionLongTermRetentionBackup> GetLongTermRetentionBackupsByResourceGroupLocationAsync(string locationName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
async Task<Page<SubscriptionLongTermRetentionBackup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = await LongTermRetentionBackupsRestClient.ListByResourceGroupLocationAsync(Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<SubscriptionLongTermRetentionBackup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = await LongTermRetentionBackupsRestClient.ListByResourceGroupLocationNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists the long term retention backups for a given location.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionBackups
/// Operation Id: LongTermRetentionBackups_ListByResourceGroupLocation
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="SubscriptionLongTermRetentionBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<SubscriptionLongTermRetentionBackup> GetLongTermRetentionBackupsByResourceGroupLocation(string locationName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
Page<SubscriptionLongTermRetentionBackup> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = LongTermRetentionBackupsRestClient.ListByResourceGroupLocation(Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<SubscriptionLongTermRetentionBackup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = LongTermRetentionBackupsRestClient.ListByResourceGroupLocationNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists the long term retention backups for a given server.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionServers/{longTermRetentionServerName}/longTermRetentionBackups
/// Operation Id: LongTermRetentionBackups_ListByResourceGroupServer
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="SubscriptionLongTermRetentionBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<SubscriptionLongTermRetentionBackup> GetLongTermRetentionBackupsByResourceGroupServerAsync(string locationName, string longTermRetentionServerName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
async Task<Page<SubscriptionLongTermRetentionBackup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupServer");
scope.Start();
try
{
var response = await LongTermRetentionBackupsRestClient.ListByResourceGroupServerAsync(Id.SubscriptionId, Id.ResourceGroupName, locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<SubscriptionLongTermRetentionBackup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupServer");
scope.Start();
try
{
var response = await LongTermRetentionBackupsRestClient.ListByResourceGroupServerNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists the long term retention backups for a given server.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionServers/{longTermRetentionServerName}/longTermRetentionBackups
/// Operation Id: LongTermRetentionBackups_ListByResourceGroupServer
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="longTermRetentionServerName"> The name of the server. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="SubscriptionLongTermRetentionBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<SubscriptionLongTermRetentionBackup> GetLongTermRetentionBackupsByResourceGroupServer(string locationName, string longTermRetentionServerName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
Page<SubscriptionLongTermRetentionBackup> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupServer");
scope.Start();
try
{
var response = LongTermRetentionBackupsRestClient.ListByResourceGroupServer(Id.SubscriptionId, Id.ResourceGroupName, locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<SubscriptionLongTermRetentionBackup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionBackupsByResourceGroupServer");
scope.Start();
try
{
var response = LongTermRetentionBackupsRestClient.ListByResourceGroupServerNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, longTermRetentionServerName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists the long term retention backups for a given managed instance.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstances/{managedInstanceName}/longTermRetentionManagedInstanceBackups
/// Operation Id: LongTermRetentionManagedInstanceBackups_ListByResourceGroupInstance
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="managedInstanceName"> The name of the managed instance. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="SubscriptionLongTermRetentionManagedInstanceBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<SubscriptionLongTermRetentionManagedInstanceBackup> GetLongTermRetentionManagedInstanceBackupsByResourceGroupInstanceAsync(string locationName, string managedInstanceName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
async Task<Page<SubscriptionLongTermRetentionManagedInstanceBackup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupInstance");
scope.Start();
try
{
var response = await LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupInstanceAsync(Id.SubscriptionId, Id.ResourceGroupName, locationName, managedInstanceName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<SubscriptionLongTermRetentionManagedInstanceBackup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupInstance");
scope.Start();
try
{
var response = await LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupInstanceNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, managedInstanceName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists the long term retention backups for a given managed instance.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstances/{managedInstanceName}/longTermRetentionManagedInstanceBackups
/// Operation Id: LongTermRetentionManagedInstanceBackups_ListByResourceGroupInstance
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="managedInstanceName"> The name of the managed instance. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="SubscriptionLongTermRetentionManagedInstanceBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<SubscriptionLongTermRetentionManagedInstanceBackup> GetLongTermRetentionManagedInstanceBackupsByResourceGroupInstance(string locationName, string managedInstanceName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
Page<SubscriptionLongTermRetentionManagedInstanceBackup> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupInstance");
scope.Start();
try
{
var response = LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupInstance(Id.SubscriptionId, Id.ResourceGroupName, locationName, managedInstanceName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<SubscriptionLongTermRetentionManagedInstanceBackup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupInstance");
scope.Start();
try
{
var response = LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupInstanceNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, managedInstanceName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists the long term retention backups for managed databases in a given location.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstanceBackups
/// Operation Id: LongTermRetentionManagedInstanceBackups_ListByResourceGroupLocation
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> An async collection of <see cref="SubscriptionLongTermRetentionManagedInstanceBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual AsyncPageable<SubscriptionLongTermRetentionManagedInstanceBackup> GetLongTermRetentionManagedInstanceBackupsByResourceGroupLocationAsync(string locationName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
async Task<Page<SubscriptionLongTermRetentionManagedInstanceBackup>> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = await LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupLocationAsync(Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
async Task<Page<SubscriptionLongTermRetentionManagedInstanceBackup>> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = await LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupLocationNextPageAsync(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken).ConfigureAwait(false);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateAsyncEnumerable(FirstPageFunc, NextPageFunc);
}
/// <summary>
/// Lists the long term retention backups for managed databases in a given location.
/// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/locations/{locationName}/longTermRetentionManagedInstanceBackups
/// Operation Id: LongTermRetentionManagedInstanceBackups_ListByResourceGroupLocation
/// </summary>
/// <param name="locationName"> The location of the database. </param>
/// <param name="onlyLatestPerDatabase"> Whether or not to only get the latest backup for each database. </param>
/// <param name="databaseState"> Whether to query against just live databases, just deleted databases, or all databases. </param>
/// <param name="cancellationToken"> The cancellation token to use. </param>
/// <returns> A collection of <see cref="SubscriptionLongTermRetentionManagedInstanceBackup" /> that may take multiple service requests to iterate over. </returns>
public virtual Pageable<SubscriptionLongTermRetentionManagedInstanceBackup> GetLongTermRetentionManagedInstanceBackupsByResourceGroupLocation(string locationName, bool? onlyLatestPerDatabase = null, DatabaseState? databaseState = null, CancellationToken cancellationToken = default)
{
Page<SubscriptionLongTermRetentionManagedInstanceBackup> FirstPageFunc(int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupLocation(Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
Page<SubscriptionLongTermRetentionManagedInstanceBackup> NextPageFunc(string nextLink, int? pageSizeHint)
{
using var scope = LongTermRetentionManagedInstanceBackupsClientDiagnostics.CreateScope("ResourceGroupExtensionClient.GetLongTermRetentionManagedInstanceBackupsByResourceGroupLocation");
scope.Start();
try
{
var response = LongTermRetentionManagedInstanceBackupsRestClient.ListByResourceGroupLocationNextPage(nextLink, Id.SubscriptionId, Id.ResourceGroupName, locationName, onlyLatestPerDatabase, databaseState, cancellationToken: cancellationToken);
return Page.FromValues(response.Value.Value.Select(value => new SubscriptionLongTermRetentionManagedInstanceBackup(Client, value)), response.Value.NextLink, response.GetRawResponse());
}
catch (Exception e)
{
scope.Failed(e);
throw;
}
}
return PageableHelpers.CreateEnumerable(FirstPageFunc, NextPageFunc);
}
}
}
| 73.461538 | 328 | 0.703722 | [
"MIT"
] | Ramananaidu/dotnet-sonarqube | sdk/sqlmanagement/Azure.ResourceManager.Sql/src/Generated/Extensions/ResourceGroupExtensionClient.cs | 35,335 | C# |
namespace FuncWorks.XNA.XTiled
{
/// <summary>
/// Terrain data for a tile.
/// </summary>
public class TerrainData
{
/// <summary>
/// Terrain associated with the tile's top-left corner.
/// </summary>
public readonly Terrain TopLeft;
/// <summary>
/// Terrain associated with the tile's top-right corner.
/// </summary>
public readonly Terrain TopRight;
/// <summary>
/// Terrain associated with the tile's bottom-left corner.
/// </summary>
public readonly Terrain BottomLeft;
/// <summary>
/// Terrain associated with the tile's bottom-right corner.
/// </summary>
public readonly Terrain BottomRight;
public TerrainData(Terrain topLeft, Terrain topRight, Terrain bottomLeft, Terrain bottomRight)
{
TopLeft = topLeft;
TopRight = topRight;
BottomLeft = bottomLeft;
BottomRight = bottomRight;
}
}
}
| 30.205882 | 102 | 0.571568 | [
"Unlicense"
] | jvlppm/xtiled | XTiled/TerrainData.cs | 1,029 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Net;
using System.Net.Http;
using System.Threading;
using System.Threading.Tasks;
using Kmd.Logic.Audit.Client.SerilogSeq;
using Serilog.Context;
using Serilog.Events;
using Xunit;
using Xunit.Abstractions;
namespace Kmd.Logic.Audit.Client.Tests
{
public class SerilogSeqAuditClientTests
{
private readonly ITestOutputHelper output;
public SerilogSeqAuditClientTests(ITestOutputHelper output)
{
this.output = output;
}
private class CustomHttpMessageHandler : HttpMessageHandler
{
private readonly Func<HttpRequestMessage, Task<HttpResponseMessage>> handler;
public CustomHttpMessageHandler(Func<HttpRequestMessage, Task<HttpResponseMessage>> handler)
{
this.handler = handler;
}
protected override Task<HttpResponseMessage> SendAsync(HttpRequestMessage request, CancellationToken cancellationToken)
{
return this.handler(request);
}
}
[Fact]
public async Task SendsAPostHttpRequestWithTheCorrectCompactJsonDataImmediately()
{
HttpRequestMessage receivedHttpRequest = null;
var messageHandler = new CustomHttpMessageHandler(request =>
{
receivedHttpRequest = request;
return Task.FromResult(new HttpResponseMessage(HttpStatusCode.Created));
});
var client = new SerilogSeqAuditClient(
new SerilogSeqAuditClientConfiguration
{
ServerUrl = new Uri("http://localhost:5341/"),
ApiKey = null,
EnrichFromLogContext = true,
}, messageHandler: messageHandler);
using (LogContext.PushProperty("LogContext", "success"))
{
client
.ForContext("ForContext", "success")
.Write("Hey hey, from {Source}", nameof(AuditTests));
}
Assert.NotNull(receivedHttpRequest);
Assert.Equal(HttpMethod.Post, receivedHttpRequest.Method);
Assert.Equal(new Uri("http://localhost:5341/api/events/raw"), receivedHttpRequest.RequestUri);
var requestBodyContent = await receivedHttpRequest.Content.ReadAsStringAsync().ConfigureAwait(false);
this.output.WriteLine(requestBodyContent);
using (var clefReader =
new Serilog.Formatting.Compact.Reader.LogEventReader(new StringReader(requestBodyContent)))
{
var didRead = clefReader.TryRead(out var deserializedEvent);
Assert.True(didRead);
Assert.Equal(LogEventLevel.Information, deserializedEvent.Level);
Assert.Null(deserializedEvent.Exception);
Assert.Equal("Hey hey, from {Source}", deserializedEvent.MessageTemplate.Text);
Assert.Collection(
deserializedEvent.Properties,
item => Assert.Equal("Source", item.Key),
item => Assert.Equal("ForContext", item.Key),
item => Assert.Equal("LogContext", item.Key));
}
}
}
}
| 36.966667 | 131 | 0.613766 | [
"MIT"
] | avin101/kmd-logic-audit-client | test/Kmd.Logic.Audit.Client.Tests/SerilogSeqAuditClientTests.cs | 3,327 | C# |
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.
using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.Data.DataView;
using Microsoft.ML;
using Microsoft.ML.CommandLine;
using Microsoft.ML.Data;
using Microsoft.ML.Internal.Utilities;
using Microsoft.ML.Runtime;
using Microsoft.ML.Sweeper;
using Microsoft.ML.Sweeper.Algorithms;
using Microsoft.ML.Trainers.FastTree;
[assembly: LoadableClass(typeof(SmacSweeper), typeof(SmacSweeper.Options), typeof(SignatureSweeper),
"SMAC Sweeper", "SMACSweeper", "SMAC")]
namespace Microsoft.ML.Sweeper
{
//REVIEW: Figure out better way to do this. could introduce a base class for all smart sweepers,
//encapsulating common functionality. This seems like a good plan to persue.
public sealed class SmacSweeper : ISweeper
{
public sealed class Options
{
[Argument(ArgumentType.Multiple | ArgumentType.Required, HelpText = "Swept parameters", ShortName = "p", SignatureType = typeof(SignatureSweeperParameter))]
public IComponentFactory<IValueGenerator>[] SweptParameters;
[Argument(ArgumentType.AtMostOnce, HelpText = "Seed for the random number generator for the first batch sweeper", ShortName = "seed")]
public int RandomSeed;
[Argument(ArgumentType.LastOccurenceWins, HelpText = "If iteration point is outside parameter definitions, should it be projected?", ShortName = "project")]
public bool ProjectInBounds = true;
[Argument(ArgumentType.LastOccurenceWins, HelpText = "Number of regression trees in forest", ShortName = "numtrees")]
public int NumOfTrees = 10;
[Argument(ArgumentType.LastOccurenceWins, HelpText = "Minimum number of data points required to be in a node if it is to be split further", ShortName = "nmin")]
public int NMinForSplit = 2;
[Argument(ArgumentType.LastOccurenceWins, HelpText = "Number of points to use for random initialization", ShortName = "nip")]
public int NumberInitialPopulation = 20;
[Argument(ArgumentType.LastOccurenceWins, HelpText = "Number of search parents to use for local search in maximizing EI acquisition function", ShortName = "lsp")]
public int LocalSearchParentCount = 10;
[Argument(ArgumentType.LastOccurenceWins, HelpText = "Number of random configurations when maximizing EI acquisition function", ShortName = "nrcan")]
public int NumRandomEISearchConfigurations = 10000;
[Argument(ArgumentType.LastOccurenceWins, HelpText = "Fraction of eligible dimensions to split on (i.e., split ratio)", ShortName = "sr")]
public float SplitRatio = (float)0.8;
[Argument(ArgumentType.LastOccurenceWins, HelpText = "Epsilon threshold for ending local searches", ShortName = "eps")]
public float Epsilon = (float)0.00001;
[Argument(ArgumentType.LastOccurenceWins, HelpText = "Number of neighbors to sample for locally searching each numerical parameter", ShortName = "nnnp")]
public int NumNeighborsForNumericalParams = 4;
}
private readonly ISweeper _randomSweeper;
private readonly Options _args;
private readonly IHost _host;
private readonly IValueGenerator[] _sweepParameters;
public SmacSweeper(IHostEnvironment env, Options options)
{
Contracts.CheckValue(env, nameof(env));
_host = env.Register("Sweeper");
_host.CheckUserArg(options.NumOfTrees > 0, nameof(options.NumOfTrees), "parameter must be greater than 0");
_host.CheckUserArg(options.NMinForSplit > 1, nameof(options.NMinForSplit), "parameter must be greater than 1");
_host.CheckUserArg(options.SplitRatio > 0 && options.SplitRatio <= 1, nameof(options.SplitRatio), "parameter must be in range (0,1].");
_host.CheckUserArg(options.NumberInitialPopulation > 1, nameof(options.NumberInitialPopulation), "parameter must be greater than 1");
_host.CheckUserArg(options.LocalSearchParentCount > 0, nameof(options.LocalSearchParentCount), "parameter must be greater than 0");
_host.CheckUserArg(options.NumRandomEISearchConfigurations > 0, nameof(options.NumRandomEISearchConfigurations), "parameter must be greater than 0");
_host.CheckUserArg(options.NumNeighborsForNumericalParams > 0, nameof(options.NumNeighborsForNumericalParams), "parameter must be greater than 0");
_args = options;
_host.CheckUserArg(Utils.Size(options.SweptParameters) > 0, nameof(options.SweptParameters), "SMAC sweeper needs at least one parameter to sweep over");
_sweepParameters = options.SweptParameters.Select(p => p.CreateComponent(_host)).ToArray();
_randomSweeper = new UniformRandomSweeper(env, new SweeperBase.OptionsBase(), _sweepParameters);
}
public ParameterSet[] ProposeSweeps(int maxSweeps, IEnumerable<IRunResult> previousRuns = null)
{
int numOfCandidates = maxSweeps;
// Initialization: Will enter here on first iteration and use the default (random)
// sweeper to generate initial candidates.
int numRuns = previousRuns == null ? 0 : previousRuns.Count();
if (numRuns < _args.NumberInitialPopulation)
return _randomSweeper.ProposeSweeps(Math.Min(numOfCandidates, _args.NumberInitialPopulation - numRuns), previousRuns);
// Only retain viable runs
List<IRunResult> viableRuns = new List<IRunResult>();
foreach (RunResult run in previousRuns)
{
if (run != null && run.HasMetricValue)
viableRuns.Add(run);
}
// Fit Random Forest Model on previous run data.
FastForestRegressionModelParameters forestPredictor = FitModel(viableRuns);
// Using acquisition function and current best, get candidate configuration(s).
return GenerateCandidateConfigurations(numOfCandidates, viableRuns, forestPredictor);
}
private FastForestRegressionModelParameters FitModel(IEnumerable<IRunResult> previousRuns)
{
Single[] targets = new Single[previousRuns.Count()];
Single[][] features = new Single[previousRuns.Count()][];
int i = 0;
foreach (RunResult r in previousRuns)
{
features[i] = SweeperProbabilityUtils.ParameterSetAsFloatArray(_host, _sweepParameters, r.ParameterSet, true);
targets[i] = (float)r.MetricValue;
i++;
}
ArrayDataViewBuilder dvBuilder = new ArrayDataViewBuilder(_host);
dvBuilder.AddColumn(DefaultColumnNames.Label, NumberDataViewType.Single, targets);
dvBuilder.AddColumn(DefaultColumnNames.Features, NumberDataViewType.Single, features);
IDataView view = dvBuilder.GetDataView();
_host.Assert(view.GetRowCount() == targets.Length, "This data view will have as many rows as there have been evaluations");
using (IChannel ch = _host.Start("Single training"))
{
// Set relevant random forest arguments.
// Train random forest.
var trainer = new FastForestRegressionTrainer(_host,
new FastForestRegressionTrainer.Options
{
FeatureFraction = _args.SplitRatio,
NumberOfTrees = _args.NumOfTrees,
MinimumExampleCountPerLeaf = _args.NMinForSplit,
LabelColumnName = DefaultColumnNames.Label,
FeatureColumnName = DefaultColumnNames.Features,
});
var predictor = trainer.Fit(view);
// Return random forest predictor.
return predictor.Model;
}
}
/// <summary>
/// Generates a set of candidate configurations to sweep through, based on a combination of random and local
/// search, as outlined in Hutter et al - Sequential Model-Based Optimization for General Algorithm Configuration.
/// Makes use of class private members which determine how many candidates are returned. This number will include
/// random configurations interleaved (per the paper), and thus will be double the specified value.
/// </summary>
/// <param name="numOfCandidates">Number of candidate solutions to return.</param>
/// <param name="previousRuns">History of previously evaluated points, with their emprical performance values.</param>
/// <param name="forest">Trained random forest ensemble. Used in evaluating the candidates.</param>
/// <returns>An array of ParamaterSets which are the candidate configurations to sweep.</returns>
private ParameterSet[] GenerateCandidateConfigurations(int numOfCandidates, IEnumerable<IRunResult> previousRuns, FastForestRegressionModelParameters forest)
{
// Get k best previous runs ParameterSets.
ParameterSet[] bestKParamSets = GetKBestConfigurations(previousRuns, forest, _args.LocalSearchParentCount);
// Perform local searches using the k best previous run configurations.
ParameterSet[] eiChallengers = GreedyPlusRandomSearch(bestKParamSets, forest, (int)Math.Ceiling(numOfCandidates / 2.0F), previousRuns);
// Generate another set of random configurations to interleave.
ParameterSet[] randomChallengers = _randomSweeper.ProposeSweeps(numOfCandidates - eiChallengers.Length, previousRuns);
// Return interleaved challenger candidates with random candidates. Since the number of candidates from either can be less than
// the number asked for, since we only generate unique candidates, and the number from either method may vary considerably.
ParameterSet[] configs = new ParameterSet[eiChallengers.Length + randomChallengers.Length];
Array.Copy(eiChallengers, 0, configs, 0, eiChallengers.Length);
Array.Copy(randomChallengers, 0, configs, eiChallengers.Length, randomChallengers.Length);
return configs;
}
/// <summary>
/// Does a mix of greedy local search around best performing parameter sets, while throwing random parameter sets into the mix.
/// </summary>
/// <param name="parents">Beginning locations for local greedy search.</param>
/// <param name="forest">Trained random forest, used later for evaluating parameters.</param>
/// <param name="numOfCandidates">Number of candidate configurations returned by the method (top K).</param>
/// <param name="previousRuns">Historical run results.</param>
/// <returns>Array of parameter sets, which will then be evaluated.</returns>
private ParameterSet[] GreedyPlusRandomSearch(ParameterSet[] parents, FastForestRegressionModelParameters forest, int numOfCandidates, IEnumerable<IRunResult> previousRuns)
{
// REVIEW: The IsMetricMaximizing flag affects the comparator, so that
// performing Max() should get the best, regardless of if it is maximizing or
// minimizing.
RunResult bestRun = (RunResult)previousRuns.Max();
RunResult worstRun = (RunResult)previousRuns.Min();
double bestVal = bestRun.IsMetricMaximizing ? bestRun.MetricValue : worstRun.MetricValue - bestRun.MetricValue;
HashSet<Tuple<double, ParameterSet>> configurations = new HashSet<Tuple<double, ParameterSet>>();
// Perform local search.
foreach (ParameterSet c in parents)
{
Tuple<double, ParameterSet> bestChildKvp = LocalSearch(c, forest, bestVal, _args.Epsilon);
configurations.Add(bestChildKvp);
}
// Additional set of random configurations to choose from during local search.
ParameterSet[] randomConfigs = _randomSweeper.ProposeSweeps(_args.NumRandomEISearchConfigurations, previousRuns);
double[] randomEIs = EvaluateConfigurationsByEI(forest, bestVal, randomConfigs);
_host.Assert(randomConfigs.Length == randomEIs.Length);
for (int i = 0; i < randomConfigs.Length; i++)
configurations.Add(new Tuple<double, ParameterSet>(randomEIs[i], randomConfigs[i]));
HashSet<ParameterSet> retainedConfigs = new HashSet<ParameterSet>();
IOrderedEnumerable<Tuple<double, ParameterSet>> bestConfigurations = configurations.OrderByDescending(x => x.Item1);
foreach (Tuple<double, ParameterSet> t in bestConfigurations.Take(numOfCandidates))
retainedConfigs.Add(t.Item2);
return retainedConfigs.ToArray();
}
/// <summary>
/// Performs a local one-mutation neighborhood greedy search.
/// </summary>
/// <param name="parent">Starting parameter set configuration.</param>
/// <param name="forest">Trained forest, for evaluation of points.</param>
/// <param name="bestVal">Best performance seen thus far.</param>
/// <param name="epsilon">Threshold for when to stop the local search.</param>
/// <returns></returns>
private Tuple<double, ParameterSet> LocalSearch(ParameterSet parent, FastForestRegressionModelParameters forest, double bestVal, double epsilon)
{
try
{
double currentBestEI = EvaluateConfigurationsByEI(forest, bestVal, new ParameterSet[] { parent })[0];
ParameterSet currentBestConfig = parent;
for (; ; )
{
ParameterSet[] neighborhood = GetOneMutationNeighborhood(currentBestConfig);
double[] eis = EvaluateConfigurationsByEI(forest, bestVal, neighborhood);
int bestIndex = eis.ArgMax();
if (eis[bestIndex] - currentBestEI < _args.Epsilon)
break;
else
{
currentBestConfig = neighborhood[bestIndex];
currentBestEI = eis[bestIndex];
}
}
return new Tuple<double, ParameterSet>(currentBestEI, currentBestConfig);
}
catch (Exception e)
{
throw _host.Except(e, "SMAC sweeper localSearch threw exception");
}
}
/// <summary>
/// Computes a single-mutation neighborhood (one param at a time) for a given configuration. For
/// numeric parameters, samples K mutations (i.e., creates K neighbors based on that paramater).
/// </summary>
/// <param name="parent">Starting configuration.</param>
/// <returns>A set of configurations that each differ from parent in exactly one parameter.</returns>
private ParameterSet[] GetOneMutationNeighborhood(ParameterSet parent)
{
List<ParameterSet> neighbors = new List<ParameterSet>();
SweeperProbabilityUtils spu = new SweeperProbabilityUtils(_host);
for (int i = 0; i < _sweepParameters.Length; i++)
{
// This allows us to query possible values of this parameter.
IValueGenerator sweepParam = _sweepParameters[i];
// This holds the actual value for this parameter, chosen in this parameter set.
IParameterValue pset = parent[sweepParam.Name];
_host.AssertValue(pset);
DiscreteValueGenerator parameterDiscrete = sweepParam as DiscreteValueGenerator;
if (parameterDiscrete != null)
{
// Create one neighbor for every discrete parameter.
float[] neighbor = SweeperProbabilityUtils.ParameterSetAsFloatArray(_host, _sweepParameters, parent, false);
int hotIndex = -1;
for (int j = 0; j < parameterDiscrete.Count; j++)
{
if (parameterDiscrete[j].Equals(pset))
{
hotIndex = j;
break;
}
}
_host.Assert(hotIndex >= 0);
Random r = new Random();
int randomIndex = r.Next(0, parameterDiscrete.Count - 1);
randomIndex += randomIndex >= hotIndex ? 1 : 0;
neighbor[i] = randomIndex;
neighbors.Add(SweeperProbabilityUtils.FloatArrayAsParameterSet(_host, _sweepParameters, neighbor, false));
}
else
{
INumericValueGenerator parameterNumeric = sweepParam as INumericValueGenerator;
_host.Check(parameterNumeric != null, "SMAC sweeper can only sweep over discrete and numeric parameters");
// Create k neighbors (typically 4) for every numerical parameter.
for (int j = 0; j < _args.NumNeighborsForNumericalParams; j++)
{
float[] neigh = SweeperProbabilityUtils.ParameterSetAsFloatArray(_host, _sweepParameters, parent, false);
double newVal = spu.NormalRVs(1, neigh[i], 0.2)[0];
while (newVal <= 0.0 || newVal >= 1.0)
newVal = spu.NormalRVs(1, neigh[i], 0.2)[0];
neigh[i] = (float)newVal;
ParameterSet neighbor = SweeperProbabilityUtils.FloatArrayAsParameterSet(_host, _sweepParameters, neigh, false);
neighbors.Add(neighbor);
}
}
}
return neighbors.ToArray();
}
/// <summary>
/// Goes through forest to extract the set of leaf values associated with filtering each configuration.
/// </summary>
/// <param name="forest">Trained forest predictor, used for filtering configs.</param>
/// <param name="configs">Parameter configurations.</param>
/// <returns>2D array where rows correspond to configurations, and columns to the predicted leaf values.</returns>
private double[][] GetForestRegressionLeafValues(FastForestRegressionModelParameters forest, ParameterSet[] configs)
{
List<double[]> datasetLeafValues = new List<double[]>();
var e = forest.TrainedEnsemble;
foreach (ParameterSet config in configs)
{
List<double> leafValues = new List<double>();
foreach (InternalRegressionTree t in e.Trees)
{
float[] transformedParams = SweeperProbabilityUtils.ParameterSetAsFloatArray(_host, _sweepParameters, config, true);
VBuffer<float> features = new VBuffer<float>(transformedParams.Length, transformedParams);
leafValues.Add((float)t.LeafValues[t.GetLeaf(in features)]);
}
datasetLeafValues.Add(leafValues.ToArray());
}
return datasetLeafValues.ToArray();
}
/// <summary>
/// Computes the empirical means and standard deviations for trees in the forest for each configuration.
/// </summary>
/// <param name="leafValues">The sets of leaf values from which the means and standard deviations are computed.</param>
/// <returns>A 2D array with one row per set of tree values, and the columns being mean and stddev, respectively.</returns>
private double[][] ComputeForestStats(double[][] leafValues)
{
// Computes the empirical mean and empirical std dev from the leaf prediction values.
double[][] meansAndStdDevs = new double[leafValues.Length][];
for (int i = 0; i < leafValues.Length; i++)
{
double[] row = new double[2];
row[0] = VectorUtils.GetMean(leafValues[i]);
row[1] = VectorUtils.GetStandardDeviation(leafValues[i]);
meansAndStdDevs[i] = row;
}
return meansAndStdDevs;
}
private double[] EvaluateConfigurationsByEI(FastForestRegressionModelParameters forest, double bestVal, ParameterSet[] configs)
{
double[][] leafPredictions = GetForestRegressionLeafValues(forest, configs);
double[][] forestStatistics = ComputeForestStats(leafPredictions);
return ComputeEIs(bestVal, forestStatistics);
}
private ParameterSet[] GetKBestConfigurations(IEnumerable<IRunResult> previousRuns, FastForestRegressionModelParameters forest, int k = 10)
{
// NOTE: Should we change this to rank according to EI (using forest), instead of observed performance?
SortedSet<RunResult> bestK = new SortedSet<RunResult>();
foreach (RunResult r in previousRuns)
{
RunResult worst = bestK.Min();
if (bestK.Count < k || r.CompareTo(worst) > 0)
bestK.Add(r);
if (bestK.Count > k)
bestK.Remove(worst);
}
// Extract the ParamaterSets and return.
List<ParameterSet> outSet = new List<ParameterSet>();
foreach (RunResult r in bestK)
outSet.Add(r.ParameterSet);
return outSet.ToArray();
}
private double ComputeEI(double bestVal, double[] forestStatistics)
{
double empMean = forestStatistics[0];
double empStdDev = forestStatistics[1];
double centered = empMean - bestVal;
double ztrans = centered / empStdDev;
return centered * SweeperProbabilityUtils.StdNormalCdf(ztrans) + empStdDev * SweeperProbabilityUtils.StdNormalPdf(ztrans);
}
private double[] ComputeEIs(double bestVal, double[][] forestStatistics)
{
double[] eis = new double[forestStatistics.Length];
for (int i = 0; i < forestStatistics.Length; i++)
eis[i] = ComputeEI(bestVal, forestStatistics[i]);
return eis;
}
// *********** Utility Functions *******************
private ParameterSet UpdateParameterSet(ParameterSet original, IParameterValue newParam)
{
List<IParameterValue> parameters = new List<IParameterValue>();
for (int i = 0; i < _sweepParameters.Length; i++)
{
if (_sweepParameters[i].Name.Equals(newParam.Name))
parameters.Add(newParam);
else
{
parameters.Add(original[_sweepParameters[i].Name]);
}
}
return new ParameterSet(parameters);
}
private float ParameterAsFloat(ParameterSet parameterSet, int index)
{
_host.Assert(parameterSet.Count == _sweepParameters.Length);
_host.Assert(index >= 0 && index <= _sweepParameters.Length);
var sweepParam = _sweepParameters[index];
var pset = parameterSet[sweepParam.Name];
_host.AssertValue(pset);
var parameterDiscrete = sweepParam as DiscreteValueGenerator;
if (parameterDiscrete != null)
{
int hotIndex = -1;
for (int j = 0; j < parameterDiscrete.Count; j++)
{
if (parameterDiscrete[j].Equals(pset))
{
hotIndex = j;
break;
}
}
_host.Assert(hotIndex >= 0);
return hotIndex;
}
else
{
var parameterNumeric = sweepParam as INumericValueGenerator;
_host.Check(parameterNumeric != null, "SMAC sweeper can only sweep over discrete and numeric parameters");
// Normalizing all numeric parameters to [0,1] range.
return parameterNumeric.NormalizeValue(pset);
}
}
}
}
| 51.888186 | 180 | 0.624477 | [
"MIT"
] | taleebanwar/machinelearning | src/Microsoft.ML.Sweeper/Algorithms/SmacSweeper.cs | 24,597 | C# |
using System.Threading.Tasks;
using NBitcoin;
using Stratis.Bitcoin.Consensus;
using Stratis.Bitcoin.Consensus.Rules;
using Stratis.Bitcoin.Features.MemoryPool;
using Stratis.SmartContracts.Core;
namespace Stratis.Bitcoin.Features.SmartContracts.Rules
{
/// <summary>
/// Enforces that only certain script types are used on the network.
/// </summary>
public class AllowedScriptTypeRule : PartialValidationConsensusRule, ISmartContractMempoolRule
{
public override Task RunAsync(RuleContext context)
{
Block block = context.ValidationContext.BlockToValidate;
foreach (Transaction transaction in block.Transactions)
{
this.CheckTransaction(transaction);
}
return Task.CompletedTask;
}
public void CheckTransaction(MempoolValidationContext context)
{
this.CheckTransaction(context.Transaction);
}
private void CheckTransaction(Transaction transaction)
{
// Why dodge coinbase?
// 1) Coinbase can only be written by Authority nodes anyhow.
// 2) Coinbase inputs look weird, are tough to validate.
if (!transaction.IsCoinBase)
{
foreach (TxOut output in transaction.Outputs)
{
this.CheckOutput(output);
}
foreach (TxIn input in transaction.Inputs)
{
this.CheckInput(input);
}
}
}
private void CheckOutput(TxOut output)
{
if (output.ScriptPubKey.IsSmartContractExec())
return;
if (output.ScriptPubKey.IsSmartContractInternalCall())
return;
if (PayToPubkeyHashTemplate.Instance.CheckScriptPubKey(output.ScriptPubKey))
return;
// For cross-chain transfers
if (PayToScriptHashTemplate.Instance.CheckScriptPubKey(output.ScriptPubKey))
return;
// For cross-chain transfers
if (PayToMultiSigTemplate.Instance.CheckScriptPubKey(output.ScriptPubKey))
return;
// For cross-chain transfers
if (TxNullDataTemplate.Instance.CheckScriptPubKey(output.ScriptPubKey))
return;
new ConsensusError("disallowed-output-script", "Only the following script types are allowed on smart contracts network: P2PKH, P2SH, P2MultiSig, OP_RETURN and smart contracts").Throw();
}
private void CheckInput(TxIn input)
{
if (input.ScriptSig.IsSmartContractSpend())
return;
if (PayToPubkeyHashTemplate.Instance.CheckScriptSig(this.Parent.Network, input.ScriptSig))
return;
// Currently necessary to spend premine. Could be stricter.
if (PayToPubkeyTemplate.Instance.CheckScriptSig(this.Parent.Network, input.ScriptSig, null))
return;
if (PayToScriptHashTemplate.Instance.CheckScriptSig(this.Parent.Network, input.ScriptSig, null))
return;
// For cross-chain transfers
if (PayToMultiSigTemplate.Instance.CheckScriptSig(this.Parent.Network, input.ScriptSig, null))
return;
new ConsensusError("disallowed-input-script", "Only the following script types are allowed on smart contracts network: P2PKH, P2SH, P2MultiSig, OP_RETURN and smart contracts").Throw();
}
}
}
| 35.73 | 197 | 0.620207 | [
"MIT"
] | AequitasCoinProject/AequitasFullNode | src/Stratis.Bitcoin.Features.SmartContracts/Rules/AllowedScriptTypeRule.cs | 3,575 | C# |
//===================================================
// Copyright @ fallstar0@qq.com 2016
// 作者:Fallstar
// 时间:2016-10-12 17:48:21
// 说明:一个用于提供基本功能的实现类
//===================================================
using System;
using System.Collections.Generic;
using System.Data;
using System.Data.Common;
using System.Linq;
using System.Text;
namespace FS.DBAccess
{
/// <summary>
/// 一个用于提供基本功能的实现类
/// </summary>
class DbProviderImpl : DbProvider
{
/// <summary>
/// 以连接字符串方式来初始化
/// </summary>
/// <param name="factory"></param>
/// <param name="conString"></param>
internal DbProviderImpl(DbProviderFactory factory, string conString) : base(factory, conString)
{
}
public override bool BatchUpdate(DataTable dt)
{
throw new NotImplementedException();
}
protected override string CreateConnectionString(string address, ushort port, string dbName, string userName, string password)
{
throw new NotImplementedException();
}
}
}
| 26.634146 | 134 | 0.56044 | [
"Apache-2.0"
] | FallStar0/DbModelTool | FS.DBAccess/DbProviderImpl.cs | 1,192 | C# |
using System;
using System.Collections.Generic;
using FairyGUI.Utils;
using CryEngine;
namespace FairyGUI
{
/// <summary>
///
/// </summary>
public class PixelHitTestData
{
public int pixelWidth;
public float scale;
public byte[] pixels;
public void Load(ByteBuffer ba)
{
ba.ReadInt();
pixelWidth = ba.ReadInt();
scale = 1.0f / ba.ReadByte();
int len = ba.ReadInt();
pixels = new byte[len];
for (int i = 0; i < len; i++)
pixels[i] = ba.ReadByte();
}
}
/// <summary>
///
/// </summary>
public class PixelHitTest : IHitTest
{
public int offsetX;
public int offsetY;
public float scaleX;
public float scaleY;
PixelHitTestData _data;
/// <summary>
///
/// </summary>
/// <param name="data"></param>
/// <param name="offsetX"></param>
/// <param name="offsetY"></param>
public PixelHitTest(PixelHitTestData data, int offsetX, int offsetY)
{
_data = data;
this.offsetX = offsetX;
this.offsetY = offsetY;
scaleX = 1;
scaleY = 1;
}
public void SetEnabled(bool value)
{
}
public bool HitTest(Container container, ref Vector2 localPoint)
{
localPoint = container.GlobalToLocal(HitTestContext.screenPoint);
int x = (int)Math.Floor((localPoint.x / scaleX - offsetX) * _data.scale);
int y = (int)Math.Floor((localPoint.y / scaleY - offsetY) * _data.scale);
if (x < 0 || y < 0 || x >= _data.pixelWidth)
return false;
int pos = y * _data.pixelWidth + x;
int pos2 = pos / 8;
int pos3 = pos % 8;
if (pos2 >= 0 && pos2 < _data.pixels.Length)
return ((_data.pixels[pos2] >> pos3) & 0x1) > 0;
else
return false;
}
}
}
| 21.395062 | 77 | 0.593191 | [
"MIT"
] | fairygui/FairyGUI-cryengine | FairyGUI/Scripts/Core/HitTest/PixelHitTest.cs | 1,735 | C# |
using System;
using System.Collections.Generic;
using System.IO;
using System.Text.RegularExpressions;
using System.Timers;
using System.Windows.Forms;
using AS3Context.Compiler;
using ASCompletion.Completion;
using ASCompletion.Context;
using ASCompletion.Model;
using PluginCore;
using PluginCore.Controls;
using PluginCore.Helpers;
using PluginCore.Localization;
using PluginCore.Managers;
using ScintillaNet;
using ScintillaNet.Enums;
using SwfOp;
using Timer = System.Timers.Timer;
using System.Linq;
namespace AS3Context
{
public class Context : AS2Context.Context
{
static readonly protected Regex re_genericType =
new Regex("(?<gen>[^<]+)\\.<(?<type>.+)>$", RegexOptions.Compiled | RegexOptions.IgnoreCase);
// C:\path\to\Main.as$raw$:31: col: 1: Error #1084: Syntax error: expecting rightbrace before end of program.
static readonly protected Regex re_syntaxError =
new Regex("(?<filename>.*)\\$raw\\$:(?<line>[0-9]+): col: (?<col>[0-9]+):(?<desc>.*)", RegexOptions.Compiled);
static readonly protected Regex re_customAPI =
new Regex("[/\\\\](playerglobal|airglobal|builtin)\\.swc", RegexOptions.Compiled | RegexOptions.IgnoreCase);
#region initialization
private AS3Settings as3settings;
private bool hasAIRSupport;
private bool hasMobileSupport;
private MxmlFilterContext mxmlFilterContext; // extract inlined AS3 ranges & MXML tags
private Timer timerCheck;
private string fileWithSquiggles;
protected bool mxmlEnabled;
/// <summary>
/// Do not call directly
/// </summary>
public Context()
{
}
public Context(AS3Settings initSettings)
{
as3settings = initSettings;
/* AS-LIKE OPTIONS */
hasLevels = false;
docType = "flash.display.MovieClip";
/* DESCRIBE LANGUAGE FEATURES */
mxmlEnabled = true;
// language constructs
features.hasPackages = true;
features.hasNamespaces = true;
features.hasImports = true;
features.hasImportsWildcard = true;
features.hasClasses = true;
features.hasExtends = true;
features.hasImplements = true;
features.hasInterfaces = true;
features.hasEnums = false;
features.hasGenerics = true;
features.hasEcmaTyping = true;
features.hasVars = true;
features.hasConsts = true;
features.hasMethods = true;
features.hasStatics = true;
features.hasOverride = true;
features.hasTryCatch = true;
features.hasE4X = true;
features.hasStaticInheritance = true;
features.checkFileName = true;
// allowed declarations access modifiers
Visibility all = Visibility.Public | Visibility.Internal | Visibility.Protected | Visibility.Private;
features.classModifiers = all;
features.varModifiers = all;
features.constModifiers = all;
features.methodModifiers = all;
// default declarations access modifiers
features.classModifierDefault = Visibility.Internal;
features.varModifierDefault = Visibility.Internal;
features.methodModifierDefault = Visibility.Internal;
// keywords
features.dot = ".";
features.voidKey = "void";
features.objectKey = "Object";
features.booleanKey = "Boolean";
features.numberKey = "Number";
features.stringKey = "String";
features.arrayKey = "Array";
features.dynamicKey = "*";
features.importKey = "import";
features.typesPreKeys = new string[] { "import", "new", "typeof", "is", "as", "extends", "implements" };
features.codeKeywords = new string[] {
"var", "function", "const", "new", "delete", "typeof", "is", "as", "return",
"break", "continue", "if", "else", "for", "each", "in", "while", "do", "switch", "case", "default", "with",
"null", "true", "false", "try", "catch", "finally", "throw", "use", "namespace"
};
features.accessKeywords = new string[] {
"native", "dynamic", "final", "public", "private", "protected", "internal", "static", "override"
};
features.declKeywords = new string[] { "var", "function", "const", "namespace", "get", "set" };
features.typesKeywords = new string[] { "import", "class", "interface" };
features.varKey = "var";
features.constKey = "const";
features.functionKey = "function";
features.getKey = "get";
features.setKey = "set";
features.staticKey = "static";
features.finalKey = "final";
features.overrideKey = "override";
features.publicKey = "public";
features.internalKey = "internal";
features.protectedKey = "protected";
features.privateKey = "private";
features.intrinsicKey = "extern";
features.namespaceKey = "namespace";
features.ArithmeticOperators = new HashSet<char>{'+', '-', '*', '/', '%'};
features.IncrementDecrementOperators = new[] {"++", "--"};
features.OtherOperators = new HashSet<string> {"delete", "typeof", "new"};
/* INITIALIZATION */
settings = initSettings;
//BuildClassPath(); // defered to first use
// live syntax checking
timerCheck = new Timer(500);
timerCheck.SynchronizingObject = PluginBase.MainForm as Form;
timerCheck.AutoReset = false;
timerCheck.Elapsed += new ElapsedEventHandler(timerCheck_Elapsed);
FlexShells.SyntaxError += new SyntaxErrorHandler(FlexShell_SyntaxError);
}
#endregion
#region classpath management
/// <summary>
/// Classpathes & classes cache initialisation
/// </summary>
public override void BuildClassPath()
{
ReleaseClasspath();
started = true;
if (as3settings == null) throw new Exception("BuildClassPath() must be overridden");
if (contextSetup == null)
{
contextSetup = new ContextSetupInfos();
contextSetup.Lang = settings.LanguageId;
contextSetup.Platform = "Flash Player";
contextSetup.Version = as3settings.DefaultFlashVersion;
}
// external version definition
platform = contextSetup.Platform;
majorVersion = 10;
minorVersion = 0;
ParseVersion(contextSetup.Version, ref majorVersion, ref minorVersion);
hasAIRSupport = platform == "AIR" || platform == "AIR Mobile";
hasMobileSupport = platform == "AIR Mobile";
string cpCheck = contextSetup.Classpath != null ?
String.Join(";", contextSetup.Classpath).Replace('\\', '/') : "";
// check if CP contains a custom playerglobal.swc
bool hasCustomAPI = re_customAPI.IsMatch(cpCheck);
//
// Class pathes
//
classPath = new List<PathModel>();
MxmlFilter.ClearCatalogs();
MxmlFilter.AddProjectManifests();
// SDK
string compiler = PluginBase.CurrentProject != null
? PluginBase.CurrentProject.CurrentSDK
: as3settings.GetDefaultSDK().Path;
char S = Path.DirectorySeparatorChar;
if (compiler == null)
compiler = Path.Combine(PathHelper.ToolDir, "flexlibs");
string frameworks = compiler + S + "frameworks";
string sdkLibs = frameworks + S + "libs";
string sdkLocales = frameworks + S + "locale" + S + PluginBase.MainForm.Settings.LocaleVersion;
string fallbackLibs = PathHelper.ResolvePath(PathHelper.ToolDir + S + "flexlibs" + S + "frameworks" + S + "libs");
string fallbackLocale = PathHelper.ResolvePath(PathHelper.ToolDir + S + "flexlibs" + S + "frameworks" + S + "locale" + S + "en_US");
List<string> addLibs = new List<string>();
List<string> addLocales = new List<string>();
if (!Directory.Exists(sdkLibs) && !sdkLibs.StartsWith('$')) // fallback
{
sdkLibs = PathHelper.ResolvePath(PathHelper.ToolDir + S + "flexlibs" + S + "frameworks" + S + "libs" + S + "player");
}
if (majorVersion > 0 && !String.IsNullOrEmpty(sdkLibs) && Directory.Exists(sdkLibs))
{
// core API SWC
if (!hasCustomAPI)
if (hasAIRSupport)
{
addLibs.Add("air" + S + "airglobal.swc");
addLibs.Add("air" + S + "aircore.swc");
addLibs.Add("air" + S + "applicationupdater.swc");
}
else
{
bool swcPresent = false;
string playerglobal = MatchPlayerGlobalExact(majorVersion, minorVersion, sdkLibs);
if (playerglobal != null) swcPresent = true;
else playerglobal = MatchPlayerGlobalExact(majorVersion, minorVersion, fallbackLibs);
if (playerglobal == null) playerglobal = MatchPlayerGlobalAny(ref majorVersion, ref minorVersion, fallbackLibs);
if (playerglobal == null) playerglobal = MatchPlayerGlobalAny(ref majorVersion, ref minorVersion, sdkLibs);
if (playerglobal != null)
{
// add missing SWC in new SDKs
if (!swcPresent && sdkLibs.IndexOfOrdinal(S + "flexlibs") < 0 && Directory.Exists(compiler))
{
string swcDir = sdkLibs + S + "player" + S;
if (!Directory.Exists(swcDir + "9") && !Directory.Exists(swcDir + "10"))
swcDir += majorVersion + "." + minorVersion;
else
swcDir += majorVersion;
try
{
if (!File.Exists(swcDir + S + "playerglobal.swc"))
{
Directory.CreateDirectory(swcDir);
File.Copy(playerglobal, swcDir + S + "playerglobal.swc");
File.WriteAllText(swcDir + S + "FlashDevelopNotice.txt",
"This 'playerglobal.swc' was copied here automatically by FlashDevelop from:\r\n" + playerglobal);
}
playerglobal = swcDir + S + "playerglobal.swc";
}
catch { }
}
addLibs.Add(playerglobal);
}
}
addLocales.Add("playerglobal_rb.swc");
// framework SWCs
string as3Fmk = PathHelper.ResolvePath("Library" + S + "AS3" + S + "frameworks");
// Flex core - ie. (Bitmap|Font|ByteArray|...)Asset / Flex(Sprite|MobieClip|Loader...)
addLibs.Add("flex.swc");
addLibs.Add("core.swc");
// Flex framework
if (cpCheck.IndexOf("Library/AS3/frameworks/Flex", StringComparison.OrdinalIgnoreCase) >= 0)
{
bool isFlexJS = cpCheck.IndexOf("Library/AS3/frameworks/FlexJS", StringComparison.OrdinalIgnoreCase) >= 0;
if (!isFlexJS)
{
addLibs.Add("framework.swc");
addLibs.Add("mx/mx.swc");
addLibs.Add("rpc.swc");
addLibs.Add("datavisualization.swc");
addLibs.Add("flash-integration.swc");
addLocales.Add("framework_rb.swc");
addLocales.Add("mx_rb.swc");
addLocales.Add("rpc_rb.swc");
addLocales.Add("datavisualization_rb.swc");
addLocales.Add("flash-integration_rb.swc");
}
if (hasAIRSupport)
{
addLibs.Add("air" + S + "airframework.swc");
addLocales.Add("airframework_rb.swc");
}
if (isFlexJS)
{
string flexJsLibs = frameworks + S + "as" + S + "libs";
addLibs.Add(flexJsLibs + S + "FlexJSUI.swc");
//addLibs.Add(flexJsLibs + S + "FlexJSJX.swc");
MxmlFilter.AddManifest("http://ns.adobe.com/mxml/2009", as3Fmk + S + "FlexJS" + S + "manifest.xml");
}
else if (cpCheck.IndexOf("Library/AS3/frameworks/Flex4", StringComparison.OrdinalIgnoreCase) >= 0)
{
addLibs.Add("spark.swc");
addLibs.Add("spark_dmv.swc");
addLibs.Add("sparkskins.swc");
//addLibs.Add("textLayout.swc");
addLibs.Add("osmf.swc");
addLocales.Add("spark_rb.swc");
//addLocales.Add("textLayout_rb.swc");
addLocales.Add("osmf_rb.swc");
if (hasAIRSupport)
{
addLibs.Add("air" + S + "airspark.swc");
addLocales.Add("airspark_rb.swc");
if (hasMobileSupport)
{
addLibs.Add("mobile" + S + "mobilecomponents.swc");
addLocales.Add("mobilecomponents_rb.swc");
}
}
MxmlFilter.AddManifest("http://ns.adobe.com/mxml/2009", as3Fmk + S + "Flex4" + S + "manifest.xml");
}
else
{
MxmlFilter.AddManifest(MxmlFilter.OLD_MX, as3Fmk + S + "Flex3" + S + "manifest.xml");
}
}
}
foreach (string file in addLocales)
{
string swcItem = sdkLocales + S + file;
if (!File.Exists(swcItem)) swcItem = fallbackLocale + S + file;
AddPath(swcItem);
}
foreach (string file in addLibs)
{
if (File.Exists(file)) AddPath(file);
else AddPath(sdkLibs + S + file);
}
// intrinsics (deprecated, excepted for FP10 Vector.<T>)
// add from the highest version number (FP11 > FP10 > FP9)
string fp = as3settings.AS3ClassPath + S + "FP";
for (int i = majorVersion; i >= 9; i--)
{
AddPath(PathHelper.ResolvePath(fp + i));
}
// add external paths
List<PathModel> initCP = classPath;
classPath = new List<PathModel>();
if (contextSetup.Classpath != null)
{
foreach (string cpath in contextSetup.Classpath)
AddPath(cpath.Trim());
}
// add library
AddPath(PathHelper.LibraryDir + S + "AS3" + S + "classes");
// add user paths from settings
if (settings.UserClasspath != null && settings.UserClasspath.Length > 0)
{
foreach (string cpath in settings.UserClasspath) AddPath(cpath.Trim());
}
// add initial paths
foreach (PathModel mpath in initCP) AddPath(mpath);
// parse top-level elements
InitTopLevelElements();
if (cFile != null) UpdateTopLevelElements();
// add current temporary path
if (temporaryPath != null)
{
string tempPath = temporaryPath;
temporaryPath = null;
SetTemporaryPath(tempPath);
}
FinalizeClasspath();
}
/// <summary>
/// Find any playerglobal.swc
/// </summary>
private string MatchPlayerGlobalAny(ref int majorVersion, ref int minorVersion, string sdkLibs)
{
char S = Path.DirectorySeparatorChar;
string libPlayer = sdkLibs + S + "player";
for (int i = minorVersion; i >= 0; i--)
{
string version = majorVersion + "." + i;
if (Directory.Exists(libPlayer + S + version))
{
minorVersion = i;
return libPlayer + S + version + S + "playerglobal.swc";
}
}
string playerglobal = null;
if (Directory.Exists(libPlayer + S + majorVersion))
playerglobal = "player" + S + majorVersion + S + "playerglobal.swc";
if (playerglobal == null && majorVersion > 9)
{
int tempMajor = majorVersion - 1;
int tempMinor = 9;
playerglobal = MatchPlayerGlobalAny(ref tempMajor, ref tempMinor, sdkLibs);
if (playerglobal != null)
{
majorVersion = tempMajor;
minorVersion = tempMinor;
return playerglobal;
}
}
return playerglobal;
}
/// <summary>
/// Find version-matching playerglobal.swc
/// </summary>
private string MatchPlayerGlobalExact(int majorVersion, int minorVersion, string sdkLibs)
{
string playerglobal = null;
char S = Path.DirectorySeparatorChar;
string libPlayer = sdkLibs + S + "player";
if (Directory.Exists(libPlayer + S + majorVersion + "." + minorVersion))
playerglobal = libPlayer + S + majorVersion + "." + minorVersion + S + "playerglobal.swc";
if (minorVersion == 0 && Directory.Exists(libPlayer + S + majorVersion))
playerglobal = libPlayer + S + majorVersion + S + "playerglobal.swc";
return playerglobal;
}
/// <summary>
/// Build a list of file mask to explore the classpath
/// </summary>
public override string[] GetExplorerMask()
{
string[] mask = as3settings.AS3FileTypes;
if (mask == null || mask.Length == 0 || (mask.Length == 1 && mask[0] == ""))
{
as3settings.AS3FileTypes = mask = new string[] { "*.as", "*.mxml" };
return mask;
}
else
{
List<string> patterns = new List<string>();
for (int i = 0; i < mask.Length; i++)
{
string m = mask[i];
if (string.IsNullOrEmpty(m)) continue;
if (m[1] != '.' && m[0] != '.') m = '.' + m;
if (m[0] != '*') m = '*' + m;
patterns.Add(m);
}
return patterns.ToArray();
}
}
/// <summary>
/// Parse a packaged library file
/// </summary>
/// <param name="path">Models owner</param>
public override void ExploreVirtualPath(PathModel path)
{
if (path.WasExplored)
{
if (MxmlFilter.HasCatalog(path.Path)) MxmlFilter.AddCatalog(path.Path);
if (path.FilesCount != 0) // already parsed
return;
}
try
{
if (File.Exists(path.Path) && !path.WasExplored)
{
bool isRefresh = path.FilesCount > 0;
//TraceManager.AddAsync("parse " + path.Path);
lock (path)
{
path.WasExplored = true;
ContentParser parser = new ContentParser(path.Path);
parser.Run();
AbcConverter.Convert(parser, path, this);
}
// reset FCSH
if (isRefresh)
{
EventManager.DispatchEvent(this,
new DataEvent(EventType.Command, "ProjectManager.RestartFlexShell", path.Path));
}
}
}
catch (Exception ex)
{
string message = TextHelper.GetString("Info.ExceptionWhileParsing");
TraceManager.AddAsync(message + " " + path.Path);
TraceManager.AddAsync(ex.Message);
TraceManager.AddAsync(ex.StackTrace);
}
}
/// <summary>
/// Delete current class's cached file
/// </summary>
public override void RemoveClassCompilerCache()
{
// not implemented - is there any?
}
/// <summary>
/// Create a new file model without parsing file
/// </summary>
/// <param name="fileName">Full path</param>
/// <returns>File model</returns>
public override FileModel CreateFileModel(string fileName)
{
if (string.IsNullOrEmpty(fileName) || !File.Exists(fileName))
return new FileModel(fileName);
fileName = PathHelper.GetLongPathName(fileName);
if (mxmlEnabled && fileName.EndsWith(".mxml", StringComparison.OrdinalIgnoreCase))
{
FileModel nFile = new FileModel(fileName);
nFile.Context = this;
nFile.HasFiltering = true;
return nFile;
}
else return base.CreateFileModel(fileName);
}
private void GuessPackage(string fileName, FileModel nFile)
{
foreach(PathModel aPath in classPath)
if (fileName.StartsWith(aPath.Path, StringComparison.OrdinalIgnoreCase))
{
string local = fileName.Substring(aPath.Path.Length);
char sep = Path.DirectorySeparatorChar;
local = local.Substring(0, local.LastIndexOf(sep)).Replace(sep, '.');
nFile.Package = local.Length > 0 ? local.Substring(1) : "";
nFile.HasPackage = true;
}
}
/// <summary>
/// Build the file DOM
/// </summary>
/// <param name="filename">File path</param>
protected override void GetCurrentFileModel(string fileName)
{
base.GetCurrentFileModel(fileName);
}
/// <summary>
/// Refresh the file model
/// </summary>
/// <param name="updateUI">Update outline view</param>
public override void UpdateCurrentFile(bool updateUI)
{
if (mxmlEnabled && cFile != null && cFile != FileModel.Ignore
&& cFile.FileName.EndsWith(".mxml", StringComparison.OrdinalIgnoreCase))
cFile.HasFiltering = true;
base.UpdateCurrentFile(updateUI);
if (cFile.HasFiltering)
{
MxmlComplete.mxmlContext = mxmlFilterContext;
MxmlComplete.context = this;
}
}
/// <summary>
/// Update the class/member context for the given line number.
/// Be carefull to restore the context after calling it with a custom line number
/// </summary>
/// <param name="line"></param>
public override void UpdateContext(int line)
{
base.UpdateContext(line);
}
/// <summary>
/// Called if a FileModel needs filtering
/// - define inline AS3 ranges
/// </summary>
/// <param name="src"></param>
/// <returns></returns>
public override string FilterSource(string fileName, string src)
{
mxmlFilterContext = new MxmlFilterContext();
return MxmlFilter.FilterSource(Path.GetFileNameWithoutExtension(fileName), src, mxmlFilterContext);
}
/// <summary>
/// Called if a FileModel needs filtering
/// - modify parsed model
/// </summary>
/// <param name="model"></param>
/// <returns></returns>
public override void FilterSource(FileModel model)
{
GuessPackage(model.FileName, model);
if (mxmlFilterContext != null) MxmlFilter.FilterSource(model, mxmlFilterContext);
}
#endregion
#region syntax checking
internal void OnFileOperation(NotifyEvent e)
{
timerCheck.Stop();
foreach (ITabbedDocument doc in PluginBase.MainForm.Documents)
if (doc.FileName == fileWithSquiggles) ClearSquiggles(doc.SciControl);
}
public override void TrackTextChange(ScintillaControl sender, int position, int length, int linesAdded)
{
base.TrackTextChange(sender, position, length, linesAdded);
if (as3settings != null && !as3settings.DisableLiveChecking && IsFileValid)
{
timerCheck.Stop();
timerCheck.Start();
}
}
private void timerCheck_Elapsed(object sender, ElapsedEventArgs e)
{
BackgroundSyntaxCheck();
}
/// <summary>
/// Checking syntax of current file
/// </summary>
private void BackgroundSyntaxCheck()
{
if (!IsFileValid) return;
ScintillaControl sci = CurSciControl;
if (sci == null) return;
ClearSquiggles(sci);
string src = CurSciControl.Text;
string sdk = PluginBase.CurrentProject != null && PluginBase.CurrentProject.Language == "as3"
? PluginBase.CurrentProject.CurrentSDK
: as3settings.GetDefaultSDK().Path;
FlexShells.Instance.CheckAS3(CurrentFile, sdk, src);
}
private void AddSquiggles(ScintillaControl sci, int line, int start, int end)
{
if (sci == null) return;
fileWithSquiggles = CurrentFile;
int position = sci.PositionFromLine(line) + start;
sci.AddHighlight(2, (int)IndicatorStyle.Squiggle, 0x000000ff, position, end - start);
}
private void ClearSquiggles(ScintillaControl sci)
{
if (sci == null) return;
try
{
sci.RemoveHighlights(2);
}
finally
{
fileWithSquiggles = null;
}
}
private void FlexShell_SyntaxError(string error)
{
if (!IsFileValid) return;
Match m = re_syntaxError.Match(error);
if (!m.Success) return;
ITabbedDocument document = PluginBase.MainForm.CurrentDocument;
if (document == null || !document.IsEditable) return;
ScintillaControl sci = document.SplitSci1;
ScintillaControl sci2 = document.SplitSci2;
if (m.Groups["filename"].Value != CurrentFile) return;
try
{
int line = int.Parse(m.Groups["line"].Value) - 1;
if (sci.LineCount < line) return;
int start = MBSafeColumn(sci, line, int.Parse(m.Groups["col"].Value) - 1);
if (line == sci.LineCount && start == 0 && line > 0) start = -1;
AddSquiggles(sci, line, start, start + 1);
AddSquiggles(sci2, line, start, start + 1);
}
catch { }
}
/// <summary>
/// Convert multibyte column to byte length
/// </summary>
private int MBSafeColumn(ScintillaControl sci, int line, int length)
{
String text = sci.GetLine(line) ?? "";
length = Math.Min(length, text.Length);
return sci.MBSafeTextLength(text.Substring(0, length));
}
#endregion
#region class resolution
/// <summary>
/// Evaluates the visibility of one given type from another.
/// Caller is responsible of calling ResolveExtends() on 'inClass'
/// </summary>
/// <param name="inClass">Completion context</param>
/// <param name="withClass">Completion target</param>
/// <returns>Completion visibility</returns>
public override Visibility TypesAffinity(ClassModel inClass, ClassModel withClass)
{
if (inClass == null || withClass == null) return Visibility.Public;
// same file
if (inClass.InFile == withClass.InFile)
return Visibility.Public | Visibility.Internal | Visibility.Protected | Visibility.Private;
// same package
Visibility acc = Visibility.Public;
if (inClass.InFile.Package == withClass.InFile.Package) acc |= Visibility.Internal;
// inheritance affinity
ClassModel tmp = inClass;
while (!tmp.IsVoid())
{
if (tmp.Type == withClass.Type)
{
acc |= Visibility.Protected;
break;
}
tmp = tmp.Extends;
}
return acc;
}
/// <summary>
/// Return the full project classes list
/// </summary>
/// <returns></returns>
public override MemberList GetAllProjectClasses()
{
// from cache
if (!completionCache.IsDirty && completionCache.AllTypes != null)
return completionCache.AllTypes;
MemberList fullList = new MemberList();
ClassModel aClass;
MemberModel item;
// public & internal classes
string package = CurrentModel?.Package;
foreach (PathModel aPath in classPath) if (aPath.IsValid && !aPath.Updating)
{
aPath.ForeachFile((aFile) =>
{
if (!aFile.HasPackage)
return true; // skip
aClass = aFile.GetPublicClass();
if (!aClass.IsVoid() && aClass.IndexType == null)
{
if (aClass.Access == Visibility.Public
|| (aClass.Access == Visibility.Internal && aFile.Package == package))
{
item = aClass.ToMemberModel();
item.Name = item.Type;
fullList.Add(item);
}
}
if (aFile.Package.Length > 0 && aFile.Members.Count > 0)
{
foreach (MemberModel member in aFile.Members)
{
item = member.Clone() as MemberModel;
item.Name = aFile.Package + "." + item.Name;
fullList.Add(item);
}
}
else if (aFile.Members.Count > 0)
{
foreach (MemberModel member in aFile.Members)
{
item = member.Clone() as MemberModel;
fullList.Add(item);
}
}
return true;
});
}
// void
fullList.Add(new MemberModel(features.voidKey, features.voidKey, FlagType.Class | FlagType.Intrinsic, 0));
// private classes
fullList.Add(GetPrivateClasses());
// in cache
fullList.Sort();
completionCache.AllTypes = fullList;
return fullList;
}
public override bool OnCompletionInsert(ScintillaControl sci, int position, string text, char trigger)
{
if (text == "Vector")
{
string insert = null;
var line = sci.GetLine(sci.LineFromPosition(position));
var m = Regex.Match(line, @"\s*=\s*new");
if (m.Success)
{
var result = ASComplete.GetExpressionType(sci, sci.PositionFromLine(sci.LineFromPosition(position)) + m.Index);
if (result != null && !result.IsNull() && result.Member?.Type != null)
{
m = Regex.Match(result.Member.Type, @"(?<=<).+(?=>)");
if (m.Success) insert = $".<{m.Value}>";
}
}
if (insert == null)
{
if (trigger == '.' || trigger == '(') return true;
insert = ".<>";
sci.InsertText(position + text.Length, insert);
sci.CurrentPos = position + text.Length + 2;
sci.SetSel(sci.CurrentPos, sci.CurrentPos);
ASComplete.HandleAllClassesCompletion(sci, "", false, true);
return true;
}
if (trigger == '.')
{
sci.InsertText(position + text.Length, insert.Substring(1));
sci.CurrentPos = position + text.Length;
}
else
{
sci.InsertText(position + text.Length, insert);
sci.CurrentPos = position + text.Length + insert.Length;
}
sci.SetSel(sci.CurrentPos, sci.CurrentPos);
return true;
}
return text.StartsWithOrdinal("Vector.<");
}
/// <summary>
/// Check if a type is already in the file's imports
/// Throws an Exception if the type name is ambiguous
/// (ie. same name as an existing import located in another package)
/// </summary>
/// <param name="member">Element to search in imports</param>
/// <param name="atLine">Position in the file</param>
public override bool IsImported(MemberModel member, int atLine)
{
if (member == ClassModel.VoidClass) return false;
FileModel cFile = Context.CurrentModel;
// same package is auto-imported
string package = member.Type.Length > member.Name.Length
? member.Type.Substring(0, member.Type.Length - member.Name.Length - 1)
: "";
if (package == cFile.Package) return true;
return base.IsImported(member, atLine);
}
/// <summary>
/// Retrieves a class model from its name
/// </summary>
/// <param name="cname">Class (short or full) name</param>
/// <param name="inFile">Current file</param>
/// <returns>A parsed class or an empty ClassModel if the class is not found</returns>
public override ClassModel ResolveType(string cname, FileModel inFile)
{
// handle generic types
if (cname != null)
{
var index = cname.IndexOf('<');
if (index != -1)
{
if (index == 0)
{
//transform <T>[] to Vector.<T>
cname = Regex.Replace(cname, @">\[.*", ">");
cname = "Vector." + cname;
}
Match genType = re_genericType.Match(cname);
if (genType.Success) return ResolveGenericType(genType.Groups["gen"].Value, genType.Groups["type"].Value, inFile);
return ClassModel.VoidClass;
}
}
return base.ResolveType(cname, inFile);
}
public override ClassModel ResolveToken(string token, FileModel inFile)
{
if (token?.Length > 0)
{
if (token == "</>") return ResolveType("XML", inFile);
if (token.StartsWithOrdinal("0x")) return ResolveType("uint", inFile);
var first = token[0];
if (char.IsLetter(first))
{
var index = token.IndexOfOrdinal(" ");
if (index != -1)
{
var word = token.Substring(0, index);
if (word == "delete") return ResolveType(features.booleanKey, inFile);
if (word == "typeof") return ResolveType(features.stringKey, inFile);
if (word == "new" && token[token.Length - 1] == ')')
{
token = token.Substring(index + 1);
token = Regex.Replace(token, @"\(.*", string.Empty);
return ResolveType(token, inFile);
}
}
}
else if (first == '(' && token.Length >= 8/*"(v as T)".Length*/)
{
var m = Regex.Match(token, @"\((?<lv>.+)\s(?<op>as)\s+(?<rv>\w+)\)");
if (m.Success) return ResolveType(m.Groups["rv"].Value.Trim(), inFile);
if (Regex.IsMatch(token, @"\((?<lv>.+)\s(?<op>is)\s+(?<rv>\w+)\)")) return ResolveType(features.booleanKey, inFile);
}
}
return base.ResolveToken(token, inFile);
}
/// <summary>
/// Retrieve/build typed copies of generic types
/// </summary>
private ClassModel ResolveGenericType(string baseType, string indexType, FileModel inFile)
{
ClassModel originalClass = base.ResolveType(baseType, inFile);
if (originalClass.IsVoid()) return originalClass;
if (indexType == "*")
{
originalClass.IndexType = "*";
return originalClass;
}
ClassModel indexClass = ResolveType(indexType, inFile);
if (indexClass.IsVoid()) return originalClass;
indexType = indexClass.QualifiedName;
FileModel aFile = originalClass.InFile;
// is the type already cloned?
foreach (ClassModel otherClass in aFile.Classes)
if (otherClass.IndexType == indexType) return otherClass;
// clone the type
ClassModel aClass = originalClass.Clone() as ClassModel;
aClass.Name = baseType + ".<" + indexType + ">";
aClass.IndexType = indexType;
string typed = "<" + indexType + ">";
foreach (MemberModel member in aClass.Members)
{
if (member.Name == baseType) member.Name = baseType.Replace("<T>", typed);
if (member.Type != null && member.Type.IndexOf('T') >= 0)
{
if (member.Type == "T") member.Type = indexType;
else member.Type = member.Type.Replace("<T>", typed);
}
if (member.Parameters != null)
{
foreach (MemberModel param in member.Parameters)
{
if (param.Type != null && param.Type.IndexOf('T') >= 0)
{
if (param.Type == "T") param.Type = indexType;
else param.Type = param.Type.Replace("<T>", typed);
}
}
}
}
aFile.Classes.Add(aClass);
return aClass;
}
protected MemberList GetPrivateClasses()
{
MemberList list = new MemberList();
// private classes
if (cFile != null)
foreach (ClassModel model in cFile.Classes)
if (model.Access == Visibility.Private)
{
MemberModel item = model.ToMemberModel();
item.Type = item.Name;
item.Access = Visibility.Private;
list.Add(item);
}
// 'Class' members
if (cClass != null)
foreach (MemberModel member in cClass.Members)
if (member.Type == "Class") list.Add(member);
return list;
}
/// <summary>
/// Prepare AS3 intrinsic known vars/methods/classes
/// </summary>
protected override void InitTopLevelElements()
{
string filename = "toplevel.as";
topLevel = new FileModel(filename);
if (topLevel.Members.Search("this", 0, 0) == null)
topLevel.Members.Add(new MemberModel("this", "", FlagType.Variable | FlagType.Intrinsic, Visibility.Public));
if (topLevel.Members.Search("super", 0, 0) == null)
topLevel.Members.Add(new MemberModel("super", "", FlagType.Variable | FlagType.Intrinsic, Visibility.Public));
if (topLevel.Members.Search(features.voidKey, 0, 0) == null)
topLevel.Members.Add(new MemberModel(features.voidKey, "", FlagType.Intrinsic, Visibility.Public));
topLevel.Members.Sort();
}
public override string GetDefaultValue(string type)
{
if (string.IsNullOrEmpty(type) || type == features.voidKey) return null;
if (type == features.dynamicKey) return "undefined";
switch (type)
{
case "int":
case "uint": return "0";
case "Number": return "NaN";
case "Boolean": return "false";
default: return "null";
}
}
public override IEnumerable<string> DecomposeTypes(IEnumerable<string> types)
{
var characterClass = ScintillaControl.Configuration.GetLanguage("as3").characterclass.Characters;
var result = new HashSet<string>();
foreach (var type in types)
{
if (string.IsNullOrEmpty(type)) result.Add("*");
else if (type.Contains("<"))
{
var length = type.Length;
var pos = 0;
for (var i = 0; i < length; i++)
{
var c = type[i];
if (c == '.' || characterClass.Contains(c)) continue;
if (c == '<')
{
result.Add(type.Substring(pos, i - pos - 1));
pos = i + 1;
}
else if (c == '>')
{
result.Add(type.Substring(pos, i - pos));
break;
}
}
}
else result.Add(type);
}
return result;
}
#endregion
#region Command line compiler
/// <summary>
/// Retrieve the context's default compiler path
/// </summary>
public override string GetCompilerPath()
{
return as3settings.GetDefaultSDK().Path ?? "Tools\\flexsdk";
}
/// <summary>
/// Check current file's syntax
/// </summary>
public override void CheckSyntax()
{
if (IsFileValid && cFile.InlinedIn == null)
{
PluginBase.MainForm.CallCommand("Save", null);
string sdk = PluginBase.CurrentProject != null
? PluginBase.CurrentProject.CurrentSDK
: PathHelper.ResolvePath(as3settings.GetDefaultSDK().Path);
FlexShells.Instance.CheckAS3(cFile.FileName, sdk);
}
}
/// <summary>
/// Run MXMLC compiler in the current class's base folder with current classpath
/// </summary>
/// <param name="append">Additional comiler switches</param>
public override void RunCMD(string append)
{
if (!IsCompilationTarget())
{
MessageBar.ShowWarning(TextHelper.GetString("Info.InvalidClass"));
return;
}
string command = (append ?? "") + " -- " + CurrentFile;
FlexShells.Instance.RunMxmlc(command, as3settings.GetDefaultSDK().Path);
}
private bool IsCompilationTarget()
{
return (!MainForm.CurrentDocument.IsUntitled && CurrentModel.Version >= 3);
}
/// <summary>
/// Calls RunCMD with additional parameters taken from the classes @mxmlc doc tag
/// </summary>
public override bool BuildCMD(bool failSilently)
{
if (!IsCompilationTarget())
{
MessageBar.ShowWarning(TextHelper.GetString("Info.InvalidClass"));
return false;
}
MainForm.CallCommand("SaveAllModified", null);
string sdk = PluginBase.CurrentProject != null
? PluginBase.CurrentProject.CurrentSDK
: as3settings.GetDefaultSDK().Path;
FlexShells.Instance.QuickBuild(CurrentModel, sdk, failSilently, as3settings.PlayAfterBuild);
return true;
}
#endregion
}
}
| 40.970874 | 144 | 0.497113 | [
"MIT"
] | Chr0n0AP/flashdevelop | External/Plugins/AS3Context/Context.cs | 46,420 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using System.Threading.Tasks;
namespace Gooios.ImageService.Domain
{
public class ValueObject<TValueObject> : IEquatable<TValueObject>
where TValueObject : ValueObject<TValueObject>
{
#region IEquatable and Override Equals operators
/// <summary>
/// <see cref="M:System.Object.IEquatable{TValueObject}"/>
/// </summary>
/// <param name="other"><see cref="M:System.Object.IEquatable{TValueObject}"/></param>
/// <returns><see cref="M:System.Object.IEquatable{TValueObject}"/></returns>
public bool Equals(TValueObject other)
{
if ((object)other == null)
return false;
if (Object.ReferenceEquals(this, other))
return true;
//compare all public properties
PropertyInfo[] publicProperties = GetType().GetProperties();
if ((object)publicProperties != null
&&
publicProperties.Any())
{
return publicProperties.All(p =>
{
var left = p.GetValue(this, null);
var right = p.GetValue(other, null);
if (typeof(TValueObject).IsAssignableFrom(left.GetType()))
{
//check not self-references...
return Object.ReferenceEquals(left, right);
}
else
return left.Equals(right);
});
}
else
return true;
}
/// <summary>
/// <see cref="M:System.Object.Equals"/>
/// </summary>
/// <param name="obj"><see cref="M:System.Object.Equals"/></param>
/// <returns><see cref="M:System.Object.Equals"/></returns>
public override bool Equals(object obj)
{
if ((object)obj == null)
return false;
if (Object.ReferenceEquals(this, obj))
return true;
ValueObject<TValueObject> item = obj as ValueObject<TValueObject>;
if ((object)item != null)
return Equals((TValueObject)item);
else
return false;
}
/// <summary>
/// <see cref="M:System.Object.GetHashCode"/>
/// </summary>
/// <returns><see cref="M:System.Object.GetHashCode"/></returns>
public override int GetHashCode()
{
int hashCode = 31;
bool changeMultiplier = false;
int index = 1;
//compare all public properties
PropertyInfo[] publicProperties = this.GetType().GetProperties();
if ((object)publicProperties != null
&&
publicProperties.Any())
{
foreach (var item in publicProperties)
{
object value = item.GetValue(this, null);
if ((object)value != null)
{
hashCode = hashCode * ((changeMultiplier) ? 59 : 114) + value.GetHashCode();
changeMultiplier = !changeMultiplier;
}
else
hashCode = hashCode ^ (index * 13);//only for support {"a",null,null,"a"} <> {null,"a","a",null}
}
}
return hashCode;
}
public static bool operator ==(ValueObject<TValueObject> left, ValueObject<TValueObject> right)
{
if (Object.Equals(left, null))
return (Object.Equals(right, null)) ? true : false;
else
return left.Equals(right);
}
public static bool operator !=(ValueObject<TValueObject> left, ValueObject<TValueObject> right)
{
return !(left == right);
}
#endregion
}
}
| 31 | 120 | 0.501241 | [
"Apache-2.0"
] | hccoo/gooios | netcoremicroservices/Gooios.ImageService/Domains/ValueObject.cs | 4,032 | C# |
//*********************************************************
//
// Copyright (c) Microsoft. All rights reserved.
// THIS CODE IS PROVIDED *AS IS* WITHOUT WARRANTY OF
// ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING ANY
// IMPLIED WARRANTIES OF FITNESS FOR A PARTICULAR
// PURPOSE, MERCHANTABILITY, OR NON-INFRINGEMENT.
//
//*********************************************************
using SDKTemplate;
using System;
using System.Threading;
using System.Threading.Tasks;
using Windows.Devices.Geolocation;
using Windows.Foundation;
using Windows.ApplicationModel.Background;
using Windows.Storage;
using Windows.UI.Core;
using Windows.UI.Xaml;
using Windows.UI.Xaml.Controls;
using Windows.UI.Xaml.Navigation;
namespace Microsoft.Samples.Devices.Geolocation
{
/// <summary>
/// An empty page that can be used on its own or navigated to within a Frame.
/// </summary>
public sealed partial class Scenario3 : SDKTemplate.Common.LayoutAwarePage
{
// A pointer back to the main page. This is needed if you want to call methods in MainPage such
// as NotifyUser()
MainPage rootPage = MainPage.Current;
private IBackgroundTaskRegistration _geolocTask = null;
private CancellationTokenSource _cts = null;
private const string SampleBackgroundTaskName = "SampleLocationBackgroundTask";
private const string SampleBackgroundTaskEntryPoint = "BackgroundTask.LocationBackgroundTask";
public Scenario3()
{
this.InitializeComponent();
}
/// <summary>
/// Invoked when this page is about to be displayed in a Frame.
/// </summary>
/// <param name="e">Event data that describes how this page was reached. The Parameter
/// property is typically used to configure the page.</param>
protected override void OnNavigatedTo(NavigationEventArgs e)
{
BackgroundAccessStatus backgroundAccessStatus = BackgroundExecutionManager.GetAccessStatus();
// Loop through all background tasks to see if SampleBackgroundTaskName is already registered
foreach (var cur in BackgroundTaskRegistration.AllTasks)
{
if (cur.Value.Name == SampleBackgroundTaskName)
{
_geolocTask = cur.Value;
break;
}
}
if (_geolocTask != null)
{
// Associate an event handler with the existing background task
_geolocTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
switch (backgroundAccessStatus)
{
case BackgroundAccessStatus.Unspecified:
case BackgroundAccessStatus.Denied:
rootPage.NotifyUser("This application must be added to the lock screen before the background task will run.", NotifyType.ErrorMessage);
break;
default:
rootPage.NotifyUser("Background task is already registered. Waiting for next update...", NotifyType.ErrorMessage);
break;
}
RegisterBackgroundTaskButton.IsEnabled = false;
UnregisterBackgroundTaskButton.IsEnabled = true;
}
else
{
RegisterBackgroundTaskButton.IsEnabled = true;
UnregisterBackgroundTaskButton.IsEnabled = false;
}
}
/// <summary>
/// Invoked immediately before the Page is unloaded and is no longer the current source of a parent Frame.
/// </summary>
/// <param name="e">
/// Event data that can be examined by overriding code. The event data is representative
/// of the navigation that will unload the current Page unless canceled. The
/// navigation can potentially be canceled by setting e.Cancel to true.
/// </param>
protected override void OnNavigatingFrom(NavigatingCancelEventArgs e)
{
// Just in case the original GetGeopositionAsync call is still active
CancelGetGeoposition();
if (_geolocTask != null)
{
// Remove the event handler
_geolocTask.Completed -= new BackgroundTaskCompletedEventHandler(OnCompleted);
}
base.OnNavigatingFrom(e);
}
/// <summary>
/// This is the click handler for the 'Register' button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
async private void RegisterBackgroundTask(object sender, RoutedEventArgs e)
{
// Get permission for a background task from the user. If the user has already answered once,
// this does nothing and the user must manually update their preference via PC Settings.
BackgroundAccessStatus backgroundAccessStatus = await BackgroundExecutionManager.RequestAccessAsync();
// Regardless of the answer, register the background task. If the user later adds this application
// to the lock screen, the background task will be ready to run.
// Create a new background task builder
BackgroundTaskBuilder geolocTaskBuilder = new BackgroundTaskBuilder();
geolocTaskBuilder.Name = SampleBackgroundTaskName;
geolocTaskBuilder.TaskEntryPoint = SampleBackgroundTaskEntryPoint;
// Create a new timer triggering at a 15 minute interval
var trigger = new TimeTrigger(15, false);
// Associate the timer trigger with the background task builder
geolocTaskBuilder.SetTrigger(trigger);
// Register the background task
_geolocTask = geolocTaskBuilder.Register();
// Associate an event handler with the new background task
_geolocTask.Completed += new BackgroundTaskCompletedEventHandler(OnCompleted);
RegisterBackgroundTaskButton.IsEnabled = false;
UnregisterBackgroundTaskButton.IsEnabled = true;
switch (backgroundAccessStatus)
{
case BackgroundAccessStatus.Unspecified:
case BackgroundAccessStatus.Denied:
rootPage.NotifyUser("This application must be added to the lock screen before the background task will run.", NotifyType.ErrorMessage);
break;
default:
// Ensure we have presented the location consent prompt (by asynchronously getting the current
// position). This must be done here because the background task cannot display UI.
GetGeopositionAsync();
break;
}
}
/// <summary>
/// This is the click handler for the 'Unregister' button.
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void UnregisterBackgroundTask(object sender, RoutedEventArgs e)
{
// Remove the application from the lock screen
BackgroundExecutionManager.RemoveAccess();
// Unregister the background task
_geolocTask.Unregister(true);
_geolocTask = null;
rootPage.NotifyUser("Background task unregistered", NotifyType.StatusMessage);
ScenarioOutput_Latitude.Text = "No data";
ScenarioOutput_Longitude.Text = "No data";
ScenarioOutput_Accuracy.Text = "No data";
RegisterBackgroundTaskButton.IsEnabled = true;
UnregisterBackgroundTaskButton.IsEnabled = false;
}
/// <summary>
/// Helper method to invoke Geolocator.GetGeopositionAsync.
/// </summary>
async private void GetGeopositionAsync()
{
try
{
// Get cancellation token
_cts = new CancellationTokenSource();
CancellationToken token = _cts.Token;
// Get a geolocator object
Geolocator geolocator = new Geolocator();
rootPage.NotifyUser("Getting initial position...", NotifyType.StatusMessage);
// Carry out the operation
Geoposition pos = await geolocator.GetGeopositionAsync().AsTask(token);
rootPage.NotifyUser("Initial position. Waiting for update...", NotifyType.StatusMessage);
ScenarioOutput_Latitude.Text = pos.Coordinate.Latitude.ToString();
ScenarioOutput_Longitude.Text = pos.Coordinate.Longitude.ToString();
ScenarioOutput_Accuracy.Text = pos.Coordinate.Accuracy.ToString();
}
catch (UnauthorizedAccessException)
{
rootPage.NotifyUser("Disabled by user. Enable access through the settings charm to enable the background task.", NotifyType.StatusMessage);
ScenarioOutput_Latitude.Text = "No data";
ScenarioOutput_Longitude.Text = "No data";
ScenarioOutput_Accuracy.Text = "No data";
}
catch (TaskCanceledException)
{
rootPage.NotifyUser("Initial position operation canceled. Waiting for update...", NotifyType.StatusMessage);
}
finally
{
_cts = null;
}
}
/// <summary>
/// Helper method to cancel the GetGeopositionAsync request (if any).
/// </summary>
private void CancelGetGeoposition()
{
if (_cts != null)
{
_cts.Cancel();
_cts = null;
}
}
async private void OnCompleted(IBackgroundTaskRegistration sender, BackgroundTaskCompletedEventArgs e)
{
if (sender != null)
{
// Update the UI with progress reported by the background task
await Dispatcher.RunAsync(CoreDispatcherPriority.Normal, () =>
{
try
{
// If the background task threw an exception, display the exception in
// the error text box.
e.CheckResult();
// Update the UI with the completion status of the background task
// The Run method of the background task sets this status.
var settings = ApplicationData.Current.LocalSettings;
if (settings.Values["Status"] != null)
{
rootPage.NotifyUser(settings.Values["Status"].ToString(), NotifyType.StatusMessage);
}
// Extract and display Latitude
if (settings.Values["Latitude"] != null)
{
ScenarioOutput_Latitude.Text = settings.Values["Latitude"].ToString();
}
else
{
ScenarioOutput_Latitude.Text = "No data";
}
// Extract and display Longitude
if (settings.Values["Longitude"] != null)
{
ScenarioOutput_Longitude.Text = settings.Values["Longitude"].ToString();
}
else
{
ScenarioOutput_Longitude.Text = "No data";
}
// Extract and display Accuracy
if (settings.Values["Accuracy"] != null)
{
ScenarioOutput_Accuracy.Text = settings.Values["Accuracy"].ToString();
}
else
{
ScenarioOutput_Accuracy.Text = "No data";
}
}
catch (Exception ex)
{
// The background task had an error
rootPage.NotifyUser(ex.ToString(), NotifyType.ErrorMessage);
}
});
}
}
}
}
| 40.776316 | 155 | 0.565424 | [
"MIT"
] | Ranin26/msdn-code-gallery-microsoft | Official Windows Platform Sample/Windows 8 app samples/[C#]-Windows 8 app samples/C#/Windows 8 app samples/Geolocation sample (Windows 8)/C#/Scenario3_BackgroundTask.xaml.cs | 12,398 | C# |
using System;
using System.Diagnostics;
using System.Diagnostics.CodeAnalysis;
using System.Globalization;
namespace Octokit
{
/// <summary>
/// Represents updatable fields on a repository. Values that are null will not be sent in the request.
/// Use string.empty if you want to clear a value.
/// </summary>
[DebuggerDisplay("{DebuggerDisplay,nq}")]
public class RepositoryUpdate
{
/// <summary>
/// Creates an object that describes an update to a repository on GitHub.
/// </summary>
/// <param name="name">The name of the repository. This is the only required parameter.</param>
public RepositoryUpdate(string name)
{
Ensure.ArgumentNotNullOrEmptyString(name, "name");
Name = name;
}
/// <summary>
/// Required. Gets or sets the repository name.
/// </summary>
public string Name { get; set; }
/// <summary>
/// Optional. Gets or sets the repository description. The default is null (do not update)
/// </summary>
public string Description { get; set; }
/// <summary>
/// Optional. Gets or sets the repository homepage url. The default is null (do not update).
/// </summary>
public string Homepage { get; set; }
/// <summary>
/// Gets or sets whether to make the repository private. The default is null (do not update).
/// </summary>
public bool? Private { get; set; }
/// <summary>
/// Gets or sets whether to enable issues for the repository. The default is null (do not update).
/// </summary>
public bool? HasIssues { get; set; }
/// <summary>
/// Optional. Gets or sets whether to enable the wiki for the repository. The default is null (do not update).
/// </summary>
public bool? HasWiki { get; set; }
/// <summary>
/// Optional. Gets or sets whether to enable downloads for the repository. The default is null (do not update).
/// </summary>
public bool? HasDownloads { get; set; }
/// <summary>
/// Optional. Gets or sets the default branch. The default is null (do not update).
/// </summary>
public string DefaultBranch { get; set; }
/// <summary>
/// Optional. Allows the "Rebase and Merge" method to be used.
/// </summary>
public bool? AllowRebaseMerge { get; set; }
/// <summary>
/// Optional. Allows the "Squash Merge" merge method to be used.
/// </summary>
public bool? AllowSquashMerge { get; set; }
/// <summary>
/// Optional. Allows the "Create a merge commit" merge method to be used.
/// </summary>
public bool? AllowMergeCommit { get; set; }
[SuppressMessage("Microsoft.Performance", "CA1811:AvoidUncalledPrivateCode")]
internal string DebuggerDisplay
{
get { return string.Format(CultureInfo.CurrentCulture, "RepositoryUpdate: Name: {0}", Name); }
}
}
}
| 34.932584 | 119 | 0.589579 | [
"MIT"
] | cycotek/tcoctotesting | Octokit/Models/Request/RepositoryUpdate.cs | 3,111 | C# |
//
// Copyright (c) 2004-2021 Jaroslaw Kowalski <jaak@jkowalski.net>, Kim Christensen, Julian Verdurmen
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions
// are met:
//
// * Redistributions of source code must retain the above copyright notice,
// this list of conditions and the following disclaimer.
//
// * 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 Jaroslaw Kowalski nor the names of its
// contributors may be used to endorse or promote products derived from this
// software without specific prior written permission.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
// AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
// IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
// ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
// LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
// CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
// SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
// CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
// ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
// THE POSSIBILITY OF SUCH DAMAGE.
//
namespace NLog.LayoutRenderers
{
using System;
using System.Globalization;
using System.Text;
using NLog.Common;
using NLog.Config;
using NLog.Internal;
/// <summary>
/// Render environmental information related to logging events.
/// </summary>
[NLogConfigurationItem]
public abstract class LayoutRenderer : ISupportsInitialize, IRenderable
{
private const int MaxInitialRenderBufferLength = 16384;
private int _maxRenderedLength;
private bool _isInitialized;
private IValueFormatter _valueFormatter;
/// <summary>
/// Gets the logging configuration this target is part of.
/// </summary>
protected LoggingConfiguration LoggingConfiguration { get; private set; }
/// <summary>
/// Value formatter
/// </summary>
protected IValueFormatter ValueFormatter => _valueFormatter ?? (_valueFormatter = ResolveService<IValueFormatter>());
/// <summary>
/// Returns a <see cref="System.String"/> that represents this instance.
/// </summary>
/// <returns>
/// A <see cref="System.String"/> that represents this instance.
/// </returns>
public override string ToString()
{
var lra = GetType().GetFirstCustomAttribute<LayoutRendererAttribute>();
if (lra != null)
{
return $"Layout Renderer: ${{{lra.Name}}}";
}
return GetType().Name;
}
/// <summary>
/// Renders the the value of layout renderer in the context of the specified log event.
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <returns>String representation of a layout renderer.</returns>
public string Render(LogEventInfo logEvent)
{
int initialLength = _maxRenderedLength;
if (initialLength > MaxInitialRenderBufferLength)
{
initialLength = MaxInitialRenderBufferLength;
}
var builder = new StringBuilder(initialLength);
RenderAppendBuilder(logEvent, builder);
if (builder.Length > _maxRenderedLength)
{
_maxRenderedLength = builder.Length;
}
return builder.ToString();
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
void ISupportsInitialize.Initialize(LoggingConfiguration configuration)
{
Initialize(configuration);
}
/// <summary>
/// Closes this instance.
/// </summary>
void ISupportsInitialize.Close()
{
Close();
}
/// <summary>
/// Initializes this instance.
/// </summary>
/// <param name="configuration">The configuration.</param>
internal void Initialize(LoggingConfiguration configuration)
{
if (LoggingConfiguration is null)
LoggingConfiguration = configuration;
if (!_isInitialized)
{
_isInitialized = true;
Initialize();
}
}
private void Initialize()
{
try
{
PropertyHelper.CheckRequiredParameters(this);
InitializeLayoutRenderer();
}
catch (Exception ex)
{
InternalLogger.Error(ex, "Exception in layout renderer initialization.");
if (ex.MustBeRethrown())
{
throw;
}
}
}
/// <summary>
/// Closes this instance.
/// </summary>
internal void Close()
{
if (_isInitialized)
{
LoggingConfiguration = null;
_valueFormatter = null;
_isInitialized = false;
CloseLayoutRenderer();
}
}
/// <summary>
/// Renders the value of layout renderer in the context of the specified log event.
/// </summary>
/// <param name="logEvent">The log event.</param>
/// <param name="builder">The layout render output is appended to builder</param>
internal void RenderAppendBuilder(LogEventInfo logEvent, StringBuilder builder)
{
if (!_isInitialized)
{
_isInitialized = true;
Initialize();
}
try
{
Append(builder, logEvent);
}
catch (Exception exception)
{
InternalLogger.Warn(exception, "Exception in layout renderer.");
if (exception.MustBeRethrown())
{
throw;
}
}
}
/// <summary>
/// Renders the value of layout renderer in the context of the specified log event into <see cref="StringBuilder" />.
/// </summary>
/// <param name="builder">The <see cref="StringBuilder"/> to append the rendered data to.</param>
/// <param name="logEvent">Logging event.</param>
protected abstract void Append(StringBuilder builder, LogEventInfo logEvent);
/// <summary>
/// Initializes the layout renderer.
/// </summary>
protected virtual void InitializeLayoutRenderer()
{
}
/// <summary>
/// Closes the layout renderer.
/// </summary>
protected virtual void CloseLayoutRenderer()
{
}
/// <summary>
/// Get the <see cref="IFormatProvider"/> for rendering the messages to a <see cref="string"/>
/// </summary>
/// <param name="logEvent">LogEvent with culture</param>
/// <param name="layoutCulture">Culture in on Layout level</param>
/// <returns></returns>
protected IFormatProvider GetFormatProvider(LogEventInfo logEvent, IFormatProvider layoutCulture = null)
{
return logEvent.FormatProvider ?? layoutCulture ?? LoggingConfiguration?.DefaultCultureInfo;
}
/// <summary>
/// Get the <see cref="CultureInfo"/> for rendering the messages to a <see cref="string"/>, needed for date and number formats
/// </summary>
/// <param name="logEvent">LogEvent with culture</param>
/// <param name="layoutCulture">Culture in on Layout level</param>
/// <returns></returns>
/// <remarks>
/// <see cref="GetFormatProvider"/> is preferred
/// </remarks>
protected CultureInfo GetCulture(LogEventInfo logEvent, CultureInfo layoutCulture = null)
{
return logEvent.FormatProvider as CultureInfo ?? layoutCulture ?? LoggingConfiguration?.DefaultCultureInfo;
}
/// <summary>
/// Register a custom layout renderer.
/// </summary>
/// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks>
/// <typeparam name="T"> Type of the layout renderer.</typeparam>
/// <param name="name"> Name of the layout renderer - without ${}.</param>
public static void Register<T>(string name)
where T : LayoutRenderer
{
var layoutRendererType = typeof(T);
Register(name, layoutRendererType);
}
/// <summary>
/// Register a custom layout renderer.
/// </summary>
/// <remarks>Short-cut for registering to default <see cref="ConfigurationItemFactory"/></remarks>
/// <param name="layoutRendererType"> Type of the layout renderer.</param>
/// <param name="name"> Name of the layout renderer - without ${}.</param>
public static void Register(string name, Type layoutRendererType)
{
ConfigurationItemFactory.Default.LayoutRenderers
.RegisterDefinition(name, layoutRendererType);
}
/// <summary>
/// Register a custom layout renderer with a callback function <paramref name="func"/>. The callback receives the logEvent.
/// </summary>
/// <param name="name">Name of the layout renderer - without ${}.</param>
/// <param name="func">Callback that returns the value for the layout renderer.</param>
public static void Register(string name, Func<LogEventInfo, object> func)
{
Register(name, (info, configuration) => func(info));
}
/// <summary>
/// Register a custom layout renderer with a callback function <paramref name="func"/>. The callback receives the logEvent and the current configuration.
/// </summary>
/// <param name="name">Name of the layout renderer - without ${}.</param>
/// <param name="func">Callback that returns the value for the layout renderer.</param>
public static void Register(string name, Func<LogEventInfo, LoggingConfiguration, object> func)
{
var layoutRenderer = new FuncLayoutRenderer(name, func);
Register(layoutRenderer);
}
/// <summary>
/// Register a custom layout renderer with a callback function <paramref name="layoutRenderer"/>. The callback receives the logEvent and the current configuration.
/// </summary>
/// <param name="layoutRenderer">Renderer with callback func</param>
public static void Register(FuncLayoutRenderer layoutRenderer)
{
ConfigurationItemFactory.Default.GetLayoutRenderers().RegisterFuncLayout(layoutRenderer.LayoutRendererName, layoutRenderer);
}
/// <summary>
/// Resolves the interface service-type from the service-repository
/// </summary>
protected T ResolveService<T>() where T : class
{
return LoggingConfiguration.GetServiceProvider().ResolveService<T>(_isInitialized);
}
}
} | 38.421569 | 171 | 0.600834 | [
"BSD-3-Clause"
] | Fr33dan/NLog | src/NLog/LayoutRenderers/LayoutRenderer.cs | 11,757 | C# |
namespace BitShelter
{
partial class SettingsForm
{
/// <summary>
/// Required designer variable.
/// </summary>
private System.ComponentModel.IContainer components = null;
#region Windows Form Designer generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InitializeComponent()
{
this.components = new System.ComponentModel.Container();
System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(SettingsForm));
this.skinManager = new Syncfusion.Windows.Forms.SkinManager(this.components);
this.btnAddSchedule = new Syncfusion.Windows.Forms.ButtonAdv();
this.dgSnapshotRules = new System.Windows.Forms.DataGridView();
this.plSvcConnection = new System.Windows.Forms.Panel();
this.wb = new System.Windows.Forms.WebBrowser();
this.lblConnWait = new System.Windows.Forms.Label();
this.retryConnTimer = new System.Windows.Forms.Timer(this.components);
((System.ComponentModel.ISupportInitialize)(this.dgSnapshotRules)).BeginInit();
this.plSvcConnection.SuspendLayout();
this.SuspendLayout();
//
// skinManager
//
this.skinManager.Controls = null;
this.skinManager.VisualTheme = Syncfusion.Windows.Forms.VisualTheme.Metro;
//
// btnAddSchedule
//
this.btnAddSchedule.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
this.btnAddSchedule.Appearance = Syncfusion.Windows.Forms.ButtonAppearance.Metro;
this.btnAddSchedule.BackColor = System.Drawing.Color.FromArgb(((int)(((byte)(22)))), ((int)(((byte)(165)))), ((int)(((byte)(220)))));
this.btnAddSchedule.BeforeTouchSize = new System.Drawing.Size(144, 28);
this.btnAddSchedule.ForeColor = System.Drawing.Color.White;
this.btnAddSchedule.IsBackStageButton = false;
this.btnAddSchedule.Location = new System.Drawing.Point(507, 2);
this.btnAddSchedule.MetroColor = System.Drawing.Color.DarkOliveGreen;
this.btnAddSchedule.Name = "btnAddSchedule";
this.btnAddSchedule.Size = new System.Drawing.Size(144, 28);
this.btnAddSchedule.TabIndex = 5;
this.btnAddSchedule.Text = "Add Schedule";
this.btnAddSchedule.UseVisualStyle = true;
this.btnAddSchedule.UseVisualStyleBackColor = true;
this.btnAddSchedule.Click += new System.EventHandler(this.btnAddSchedule_Click);
//
// dgSnapshotRules
//
this.dgSnapshotRules.AllowUserToAddRows = false;
this.dgSnapshotRules.AllowUserToOrderColumns = true;
this.dgSnapshotRules.AutoSizeColumnsMode = System.Windows.Forms.DataGridViewAutoSizeColumnsMode.Fill;
this.dgSnapshotRules.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize;
this.dgSnapshotRules.Location = new System.Drawing.Point(4, 36);
this.dgSnapshotRules.MultiSelect = false;
this.dgSnapshotRules.Name = "dgSnapshotRules";
this.dgSnapshotRules.ReadOnly = true;
this.dgSnapshotRules.Size = new System.Drawing.Size(647, 410);
this.dgSnapshotRules.TabIndex = 6;
//
// plSvcConnection
//
this.plSvcConnection.Controls.Add(this.wb);
this.plSvcConnection.Controls.Add(this.lblConnWait);
this.plSvcConnection.Dock = System.Windows.Forms.DockStyle.Fill;
this.plSvcConnection.Enabled = false;
this.plSvcConnection.Location = new System.Drawing.Point(0, 0);
this.plSvcConnection.Name = "plSvcConnection";
this.plSvcConnection.Size = new System.Drawing.Size(656, 450);
this.plSvcConnection.TabIndex = 7;
this.plSvcConnection.Visible = false;
//
// wb
//
this.wb.Dock = System.Windows.Forms.DockStyle.Fill;
this.wb.Location = new System.Drawing.Point(0, 88);
this.wb.MinimumSize = new System.Drawing.Size(20, 20);
this.wb.Name = "wb";
this.wb.ScriptErrorsSuppressed = true;
this.wb.Size = new System.Drawing.Size(656, 362);
this.wb.TabIndex = 3;
//
// lblConnWait
//
this.lblConnWait.Dock = System.Windows.Forms.DockStyle.Top;
this.lblConnWait.Font = new System.Drawing.Font("Microsoft Sans Serif", 14F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(0)));
this.lblConnWait.Location = new System.Drawing.Point(0, 0);
this.lblConnWait.Name = "lblConnWait";
this.lblConnWait.Padding = new System.Windows.Forms.Padding(0, 20, 0, 0);
this.lblConnWait.Size = new System.Drawing.Size(656, 88);
this.lblConnWait.TabIndex = 2;
this.lblConnWait.Text = "Connection to the service failed.\r\nRetrying in 5...";
this.lblConnWait.TextAlign = System.Drawing.ContentAlignment.TopCenter;
//
// retryConnTimer
//
this.retryConnTimer.Interval = 1000;
this.retryConnTimer.Tag = "5000";
this.retryConnTimer.Tick += new System.EventHandler(this.retryConnTimer_Tick);
//
// SettingsForm
//
this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.BorderThickness = 2;
this.CaptionFont = new System.Drawing.Font("Microsoft Sans Serif", 10F);
this.ClientSize = new System.Drawing.Size(656, 450);
this.Controls.Add(this.dgSnapshotRules);
this.Controls.Add(this.btnAddSchedule);
this.Controls.Add(this.plSvcConnection);
this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon")));
this.Name = "SettingsForm";
this.Text = "BitShelter - Settings";
((System.ComponentModel.ISupportInitialize)(this.dgSnapshotRules)).EndInit();
this.plSvcConnection.ResumeLayout(false);
this.ResumeLayout(false);
}
#endregion
private Syncfusion.Windows.Forms.SkinManager skinManager;
private Syncfusion.Windows.Forms.ButtonAdv btnAddSchedule;
private System.Windows.Forms.DataGridView dgSnapshotRules;
private System.Windows.Forms.Panel plSvcConnection;
private System.Windows.Forms.Label lblConnWait;
private System.Windows.Forms.WebBrowser wb;
private System.Windows.Forms.Timer retryConnTimer;
}
} | 49 | 166 | 0.682993 | [
"MIT"
] | alexis-/BitShelter | BitShelter.Agent/Forms/SettingsForm.Designer.cs | 6,617 | C# |
namespace Lottery.View.Model
{
public class AwardModel
{
public string AwardName { get; set; }
public string AwardDescription { get; set; }
}
}
| 19.222222 | 52 | 0.618497 | [
"Apache-2.0"
] | dzevad91/Backend-app- | Lottery.View.Model/AwardModel.cs | 175 | 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.
namespace Microsoft.CodeAnalysis.Razor.Workspaces
{
internal abstract class LSPEditorFeatureDetector
{
public abstract bool IsLSPEditorAvailable(string documentMoniker, object hierarchy);
public abstract bool IsLSPEditorAvailable();
/// <summary>
/// A remote client is a LiveShare guest or a Codespaces instance
/// </summary>
public abstract bool IsRemoteClient();
public abstract bool IsLiveShareHost();
}
}
| 32.55 | 111 | 0.706605 | [
"Apache-2.0"
] | ladipro/aspnetcore-tooling | src/Razor/src/Microsoft.CodeAnalysis.Razor.Workspaces/LSPEditorFeatureDetector.cs | 653 | C# |
#region BSD License
/*
* Use of this source code is governed by a BSD-style
* license that can be found in the LICENSE.md file or at
* https://github.com/Wagnerp/Krypton-Toolkit-Suite-Extended-NET-5.480/blob/master/LICENSE
*
*/
#endregion
using ExtendedFileDialogs.Enumerations;
using System;
using System.Drawing;
using System.Runtime.InteropServices;
namespace ExtendedFileDialogs.Structs
{
#region WINDOWINFO
[StructLayout(LayoutKind.Sequential)]
internal struct WINDOWINFO
{
public UInt32 cbSize;
public RECT rcWindow;
public RECT rcClient;
public UInt32 dwStyle;
public UInt32 dwExStyle;
public UInt32 dwWindowStatus;
public UInt32 cxWindowBorders;
public UInt32 cyWindowBorders;
public UInt16 atomWindowType;
public UInt16 wCreatorVersion;
}
#endregion
#region POINT
[StructLayout(LayoutKind.Sequential)]
internal struct POINT
{
public int x;
public int y;
#region Constructors
public POINT(int x, int y)
{
this.x = x;
this.y = y;
}
public POINT(Point point)
{
x = point.X;
y = point.Y;
}
#endregion
}
#endregion
#region RECT
[StructLayout(LayoutKind.Sequential)]
internal struct RECT
{
public int left;
public int top;
public int right;
public int bottom;
#region Properties
public POINT Location
{
get { return new POINT((int)left, (int)top); }
set
{
right -= (left - value.x);
bottom -= (bottom - value.y);
left = value.x;
top = value.y;
}
}
internal uint Width
{
get { return (uint)Math.Abs(right - left); }
set { right = left + (int)value; }
}
internal uint Height
{
get { return (uint)Math.Abs(bottom - top); }
set { bottom = top + (int)value; }
}
#endregion
#region Overrides
public override string ToString()
{
return left + ":" + top + ":" + right + ":" + bottom;
}
#endregion
}
#endregion
#region WINDOWPOS
[StructLayout(LayoutKind.Sequential)]
internal struct WINDOWPOS
{
public IntPtr hwnd;
public IntPtr hwndAfter;
public int x;
public int y;
public int cx;
public int cy;
public uint flags;
#region Overrides
public override string ToString()
{
return x + ":" + y + ":" + cx + ":" + cy + ":" + ((SWP_Flags)flags).ToString();
}
#endregion
}
#endregion
//#region NCCALCSIZE_PARAMS
//internal struct NCCALCSIZE_PARAMS
//{
// public RECT rgrc1;
// public RECT rgrc2;
// public RECT rgrc3;
// public IntPtr lppos;
//}
//#endregion
#region NMHDR
[StructLayout(LayoutKind.Sequential)]
internal struct NMHDR
{
public IntPtr hwndFrom;
public IntPtr idFrom;
public uint code;
}
#endregion
#region NMHEADER
[StructLayout(LayoutKind.Sequential)]
internal struct NMHEADER
{
internal NMHDR hdr;
internal int iItem;
internal int iButton;
internal IntPtr pItem;
}
#endregion
#region OPENFILENAME
/// <summary>
/// Defines the shape of hook procedures that can be called by the OpenFileDialog
/// </summary>
internal delegate IntPtr OfnHookProc(IntPtr hWnd, UInt16 msg, Int32 wParam, Int32 lParam);
/// <summary>
/// See the documentation for OPENFILENAME
/// </summary>
//typedef struct tagOFN {
// DWORD lStructSize;
// HWND hwndOwner;
// HINSTANCE hInstance;
// LPCTSTR lpstrFilter;
// LPTSTR lpstrCustomFilter;
// DWORD nMaxCustFilter;
// DWORD nFilterIndex;
// LPTSTR lpstrFile;
// DWORD nMaxFile;
// LPTSTR lpstrFileTitle;
// DWORD nMaxFileTitle;
// LPCTSTR lpstrInitialDir;
// LPCTSTR lpstrTitle;
// DWORD Flags;
// WORD nFileOffset;
// WORD nFileExtension;
// LPCTSTR lpstrDefExt;
// LPARAM lCustData;
// LPOFNHOOKPROC lpfnHook;
// LPCTSTR lpTemplateName;
//#if (_WIN32_WINNT >= 0x0500)
// void * pvReserved;
// DWORD dwReserved;
// DWORD FlagsEx;
//#endif // (_WIN32_WINNT >= 0x0500)
//} OPENFILENAME, *LPOPENFILENAME;
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
internal struct OPENFILENAME
{
public UInt32 lStructSize;
public IntPtr hwndOwner;
public IntPtr hInstance;
public String lpstrFilter;
public String lpstrCustomFilter;
public UInt32 nMaxCustFilter;
public Int32 nFilterIndex;
public String lpstrFile;
public UInt32 nMaxFile;
public String lpstrFileTitle;
public UInt32 nMaxFileTitle;
public String lpstrInitialDir;
public String lpstrTitle;
public UInt32 Flags;
public UInt16 nFileOffset;
public UInt16 nFileExtension;
public String lpstrDefExt;
public IntPtr lCustData;
public OfnHookProc lpfnHook;
public String lpTemplateName;
public IntPtr pvReserved;
public UInt32 dwReserved;
public UInt32 FlagsEx;
};
#endregion
#region OFNOTIFY
[StructLayout(LayoutKind.Sequential)]
internal struct OFNOTIFY
{
public NMHDR hdr;
public IntPtr OpenFileName;
public IntPtr fileNameShareViolation;
}
#endregion
} | 25.865801 | 94 | 0.565523 | [
"BSD-3-Clause"
] | Krypton-Suite-Legacy-Archive/Krypton-Toolkit-Suite-Extended-NET-5.480 | Source/Krypton Toolkit Suite Extended/Full Toolkit/Extended File Dialogs/Structs/STRUCTS.cs | 5,977 | C# |
using System.Reflection;
using System.Runtime.CompilerServices;
using System.Runtime.InteropServices;
// General Information about an assembly is controlled through the following
// set of attributes. Change these attribute values to modify the information
// associated with an assembly.
[assembly: AssemblyTitle("HashCode2017.Qualification")]
[assembly: AssemblyDescription("")]
[assembly: AssemblyConfiguration("")]
[assembly: AssemblyCompany("")]
[assembly: AssemblyProduct("HashCode2017.Qualification")]
[assembly: AssemblyCopyright("Copyright © 2017")]
[assembly: AssemblyTrademark("")]
[assembly: AssemblyCulture("")]
// Setting ComVisible to false makes the types in this assembly not visible
// to COM components. If you need to access a type in this assembly from
// COM, set the ComVisible attribute to true on that type.
[assembly: ComVisible(false)]
// The following GUID is for the ID of the typelib if this project is exposed to COM
[assembly: Guid("0c66633e-0d9d-4a15-9106-d03d5d7d6668")]
// Version information for an assembly consists of the following four values:
//
// Major Version
// Minor Version
// Build Number
// Revision
//
// You can specify all the values or you can default the Build and Revision Numbers
// by using the '*' as shown below:
// [assembly: AssemblyVersion("1.0.*")]
[assembly: AssemblyVersion("1.0.0.0")]
[assembly: AssemblyFileVersion("1.0.0.0")]
| 38.513514 | 84 | 0.748772 | [
"MIT"
] | Fellfalla/HashCode2017 | HashCode2017/HashCode2017.Qualification/Properties/AssemblyInfo.cs | 1,428 | C# |
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using RimWorld;
using Verse;
using Verse.AI;
using Verse.AI.Group;
using UnityEngine;
namespace TorannMagic.Golems
{
public class JobGiver_GolemForceGotoDespawn : ThinkNode_JobGiver
{
protected override Job TryGiveJob(Pawn pawn)
{
CompGolem cg = pawn.TryGetComp<CompGolem>();
if(cg == null)
{
return null;
}
if(!cg.shouldDespawn)
{
return null;
}
if (!cg.dormantPosition.IsValid)
{
return null;
}
if (pawn.CanReach(cg.dormantPosition, PathEndMode.ClosestTouch, Danger.Deadly))
{
Job job = JobMaker.MakeJob(TorannMagicDefOf.JobDriver_GolemDespawn, cg.dormantPosition);
job.locomotionUrgency = LocomotionUrgency.Sprint;
return job;
}
cg.shouldDespawn = false;
return null;
}
}
}
| 26.380952 | 104 | 0.564079 | [
"BSD-3-Clause"
] | Sn1p3rr3c0n/RWoM | RimWorldOfMagic/RimWorldOfMagic/Golems/JobGiver_GolemForceGotoDespawn.cs | 1,110 | C# |
// Copyright Naked Objects Group Ltd, 45 Station Road, Henley on Thames, UK, RG9 1AT
// 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.Diagnostics;
using Microsoft.VisualStudio.TestTools.UnitTesting;
using NakedFramework.Selenium.Helpers.Tests;
using OpenQA.Selenium;
namespace NakedObjects.Selenium.Test.ObjectTests {
public abstract class FooterTestsRoot : AWTest {
protected override string BaseUrl => TestConfig.BaseObjectUrl;
public virtual void Home() {
Debug.WriteLine(nameof(Home));
GeminiUrl("object?o1=___1.Product--968");
WaitForView(Pane.Single, PaneType.Object, "Touring-1000 Blue, 54");
Click(br.FindElement(By.CssSelector(".icon.home")));
WaitForView(Pane.Single, PaneType.Home, "Home");
}
public virtual void BackAndForward() {
Debug.WriteLine(nameof(BackAndForward));
Url(BaseUrl);
GoToMenuFromHomePage("Orders");
Click(GetObjectEnabledAction("Random Order"));
WaitForView(Pane.Single, PaneType.Object);
var orderTitle = WaitForCss(".title").Text;
ClickBackButton();
WaitForView(Pane.Single, PaneType.Home);
ClickForwardButton();
WaitForView(Pane.Single, PaneType.Object, orderTitle);
EditObject();
WaitForView(Pane.Single, PaneType.Object, "Editing - " + orderTitle);
ClickBackButton();
WaitForView(Pane.Single, PaneType.Home);
ClickForwardButton();
WaitForView(Pane.Single, PaneType.Object, "Editing - " + orderTitle);
Click(GetCancelEditButton());
WaitForView(Pane.Single, PaneType.Object, orderTitle);
ClickBackButton();
WaitForView(Pane.Single, PaneType.Home);
ClickForwardButton();
WaitForView(Pane.Single, PaneType.Object, orderTitle);
var link = GetReferenceFromProperty("Customer");
var cusTitle = link.Text;
Click(link);
WaitForView(Pane.Single, PaneType.Object, cusTitle);
ClickBackButton();
WaitForView(Pane.Single, PaneType.Object, orderTitle);
ClickForwardButton();
WaitForView(Pane.Single, PaneType.Object, cusTitle);
OpenObjectActions();
OpenSubMenu("Orders");
OpenActionDialog("Create New Order");
ClickBackButton();
WaitForView(Pane.Single, PaneType.Object, cusTitle);
ClickBackButton();
WaitForView(Pane.Single, PaneType.Object, orderTitle);
}
public virtual void RecentObjects() {
Debug.WriteLine(nameof(RecentObjects));
GeminiUrl("home?m1=CustomerRepository&d1=FindCustomerByAccountNumber&f1_accountNumber=%22AW%22");
ClearFieldThenType("#accountnumber1", "AW00000042");
Click(OKButton());
WaitForView(Pane.Single, PaneType.Object, "Healthy Activity Store, AW00000042");
ClickHomeButton();
GoToMenuFromHomePage("Customers");
OpenActionDialog("Find Customer By Account Number");
ClearFieldThenType("#accountnumber1", "AW00000359");
Click(OKButton());
WaitForView(Pane.Single, PaneType.Object, "Mechanical Sports Center, AW00000359");
ClickHomeButton();
GoToMenuFromHomePage("Customers");
OpenActionDialog("Find Customer By Account Number");
ClearFieldThenType("#accountnumber1", "AW00022262");
Click(OKButton());
WaitForView(Pane.Single, PaneType.Object, "Marcus Collins, AW00022262");
ClickHomeButton();
GoToMenuFromHomePage("Products");
Click(GetObjectEnabledAction("Find Product By Number"));
ClearFieldThenType("#number1", "LJ-0192-S");
Click(OKButton());
WaitForView(Pane.Single, PaneType.Object, "Long-Sleeve Logo Jersey, S");
ClickRecentButton();
WaitForView(Pane.Single, PaneType.Recent);
var el = WaitForCssNo("tr td:nth-child(1)", 0);
Assert.AreEqual("Long-Sleeve Logo Jersey, S", el.Text);
el = WaitForCssNo("tr td:nth-child(1)", 1);
Assert.AreEqual("Marcus Collins, AW00022262", el.Text);
el = WaitForCssNo("tr td:nth-child(1)", 2);
Assert.AreEqual("Mechanical Sports Center, AW00000359", el.Text);
el = WaitForCssNo("tr td:nth-child(1)", 3);
Assert.AreEqual("Healthy Activity Store, AW00000042", el.Text);
//Test left- and right-click navigation from Recent
el = WaitForCssNo("tr td:nth-child(1)", 0);
Assert.AreEqual("Long-Sleeve Logo Jersey, S", el.Text);
RightClick(el);
WaitForView(Pane.Right, PaneType.Object, "Long-Sleeve Logo Jersey, S");
WaitForView(Pane.Left, PaneType.Recent);
el = WaitForCssNo("tr td:nth-child(1)", 1);
Assert.AreEqual("Marcus Collins, AW00022262", el.Text);
Click(el);
WaitForView(Pane.Left, PaneType.Object, "Marcus Collins, AW00022262");
//Test that clear button works
ClickRecentButton();
WaitForView(Pane.Left, PaneType.Recent);
WaitForCss("tr td:nth-child(1)", 6);
var clear = GetInputButton("Clear", Pane.Left).AssertIsEnabled();
Click(clear);
GetInputButton("Clear", Pane.Left).AssertIsDisabled();
WaitForCss("tr td", 0);
}
public virtual void ApplicationProperties() {
var lastPropertyText = "Client version:";
Debug.WriteLine(nameof(ApplicationProperties));
GeminiUrl("home");
WaitForView(Pane.Single, PaneType.Home);
ClickPropertiesButton();
WaitForView(Pane.Single, PaneType.ApplicationProperties, "Application Properties");
wait.Until(d => br.FindElements(By.CssSelector(".property")).Count >= 6);
wait.Until(dr => dr.FindElements(By.CssSelector(".property"))[5].Text.StartsWith(lastPropertyText));
var properties = br.FindElements(By.CssSelector(".property"));
Assert.IsTrue(properties[0].Text.StartsWith("Application Name:"), properties[0].Text);
Assert.IsTrue(properties[1].Text.StartsWith("User Name:"), properties[1].Text);
Assert.IsTrue(properties[2].Text.StartsWith("Server Url: http"), properties[2].Text); // maybe https
Assert.IsTrue(properties[3].Text.StartsWith("Server API version:"), properties[3].Text);
Assert.IsTrue(properties[4].Text.StartsWith("Server version:"), properties[4].Text);
Assert.IsTrue(properties[5].Text.StartsWith(lastPropertyText), properties[5].Text);
}
public virtual void LogOff() {
Debug.WriteLine(nameof(LogOff));
GeminiUrl("home");
ClickLogOffButton();
wait.Until(d => br.FindElement(By.CssSelector(".title")).Text.StartsWith("Log Off"));
var cancel = wait.Until(dr => dr.FindElement(By.CssSelector("button[value='Cancel']")));
Click(cancel);
WaitForView(Pane.Single, PaneType.Home);
}
#region WarningsAndInfo
public virtual void ExplicitWarningsAndInfo() {
Debug.WriteLine(nameof(ExplicitWarningsAndInfo));
GeminiUrl("home?m1=WorkOrderRepository");
Click(GetObjectEnabledAction("Generate Info And Warning"));
var warn = WaitForCss(".footer .warnings");
Assert.AreEqual("Warn User of something else", warn.Text);
var msg = WaitForCss(".footer .messages");
Assert.AreEqual("Inform User of something", msg.Text);
//Test that both are cleared by next action
Click(GetObjectEnabledAction("Random Work Order"));
WaitUntilElementDoesNotExist(".footer .warnings");
WaitUntilElementDoesNotExist(".footer .messages");
}
public virtual void ZeroParamActionReturningNullGeneratesGenericWarning() {
Debug.WriteLine(nameof(ZeroParamActionReturningNullGeneratesGenericWarning));
GeminiUrl("home?m1=EmployeeRepository");
Click(GetObjectEnabledAction("Me"));
WaitForTextEquals(".footer .warnings", "no result found");
Click(GetObjectEnabledAction("My Departmental Colleagues"));
WaitForTextEquals(".footer .warnings", "Current user unknown");
}
#endregion
}
public abstract class FooterTests : FooterTestsRoot {
[TestMethod]
public override void Home() {
base.Home();
}
[TestMethod]
public override void BackAndForward() {
base.BackAndForward();
}
[TestMethod]
public override void RecentObjects() {
base.RecentObjects();
}
[TestMethod]
public override void ApplicationProperties() {
base.ApplicationProperties();
}
[TestMethod]
public override void LogOff() {
base.LogOff();
}
#region Warnings and Info
[TestMethod]
public override void ExplicitWarningsAndInfo() {
base.ExplicitWarningsAndInfo();
}
[TestMethod]
public override void ZeroParamActionReturningNullGeneratesGenericWarning() {
base.ZeroParamActionReturningNullGeneratesGenericWarning();
}
#endregion
}
#region Mega tests
public abstract class MegaFooterTestsRoot : FooterTestsRoot {
[TestMethod] //Mega
[Priority(0)]
public void FooterTest() {
ExplicitWarningsAndInfo();
ZeroParamActionReturningNullGeneratesGenericWarning();
Home();
BackAndForward();
RecentObjects();
ApplicationProperties();
LogOff();
}
//[TestMethod]
[Priority(-1)]
public void ProblematicTests() { }
}
//[TestClass]
public class MegaFooterTestsFirefox : MegaFooterTestsRoot {
[ClassInitialize]
public new static void InitialiseClass(TestContext context) {
GeminiTest.InitialiseClass(context);
}
[TestInitialize]
public virtual void InitializeTest() {
InitFirefoxDriver();
Url(BaseUrl);
}
[TestCleanup]
public virtual void CleanupTest() {
CleanUpTest();
}
}
//[TestClass]
public class MegaFooterTestsIe : MegaFooterTestsRoot {
[ClassInitialize]
public new static void InitialiseClass(TestContext context) {
FilePath(@"drivers.IEDriverServer.exe");
GeminiTest.InitialiseClass(context);
}
[TestInitialize]
public virtual void InitializeTest() {
InitIeDriver();
Url(BaseUrl);
}
[TestCleanup]
public virtual void CleanupTest() {
CleanUpTest();
}
}
[TestClass] //toggle
public class MegaFooterTestsChrome : MegaFooterTestsRoot {
[ClassInitialize]
public new static void InitialiseClass(TestContext context) {
FilePath(@"drivers.chromedriver.exe");
GeminiTest.InitialiseClass(context);
}
[TestInitialize]
public virtual void InitializeTest() {
InitChromeDriver();
Url(BaseUrl);
}
[TestCleanup]
public virtual void CleanupTest() {
CleanUpTest();
}
}
#endregion
} | 40.601329 | 136 | 0.613861 | [
"Apache-2.0"
] | NakedObjectsGroup/NakedObjectsFramework | Test/NakedObjects.Selenium.Test/ObjectTests/FooterTests.cs | 12,223 | C# |
namespace HomeHunter.Models.ViewModels.Neighbourhood
{
public class NeighbourhoodViewModel
{
public string Name { get; set; }
}
}
| 18.875 | 53 | 0.682119 | [
"MIT"
] | CryptoEcliptic/HomeHunter | HomeHunter/App/HomeHunter.Models/ViewModels/Neighbourhood/NeighbourhoodViewModel.cs | 153 | C# |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.