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
// (c) Copyright HutongGames, LLC 2010-2018. All rights reserved. #if UNITY_5_6_OR_NEWER using UnityEngine; using UnityEngine.Video; namespace HutongGames.PlayMaker.Actions { [ActionCategory(ActionCategory.Video)] [Tooltip("Check Whether the player restarts from the beginning without when it reaches the end of the clip.")] public class VideoPlayerGetIsLooping : FsmStateAction { [RequiredField] [CheckForComponent(typeof(VideoPlayer))] [Tooltip("The GameObject with as VideoPlayer component.")] public FsmOwnerDefault gameObject; [Tooltip("The Value")] [UIHint(UIHint.Variable)] public FsmBool isLooping; [Tooltip("Event sent if content is looping")] public FsmEvent isLoopingEvent; [Tooltip("Event sent if content is not looping")] public FsmEvent isNotLoopingEvent; [Tooltip("Execute action everyframe. Events are however sent discretly, only when changes occurs")] public bool everyframe; GameObject go; VideoPlayer _vp; int _isLooping = -1; public override void Reset() { gameObject = null; isLooping = null; isLoopingEvent = null; isNotLoopingEvent = null; } public override void OnEnter() { GetVideoPlayer (); ExecuteAction (); } public override void OnUpdate() { ExecuteAction (); } void ExecuteAction() { if (_vp == null) { return; } if (_vp.isLooping) { isLooping.Value = true; if (_isLooping != 1) { Fsm.Event (isLoopingEvent); } _isLooping = 1; } else { isLooping.Value = false; if (_isLooping != 0) { Fsm.Event (isNotLoopingEvent); } _isLooping = 0; } } void GetVideoPlayer() { go = Fsm.GetOwnerDefaultTarget(gameObject); if (go != null) { _vp = go.GetComponent<VideoPlayer>(); } } } } #endif
18.864583
111
0.672557
[ "MIT" ]
aiden-ji/oneButtonBoB
Assets/PlayMaker/Actions/VideoPlayer/VideoPlayerGetIsLooping.cs
1,813
C#
using System; using System.Collections.Generic; using System.Drawing; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Media.Media3D; using Untangle.ViewModels; using PointF = System.Drawing.PointF; namespace Untangle.Generation { public static class GraphLayout { public static int SelectRandomLayout(Graph graph, System.Windows.Size size) { int arrangement = RandomSingleton.Next(7); int intersectionCount = 0; while (intersectionCount == 0) { if (arrangement == 0 || arrangement == 1) { intersectionCount = GraphLayout.Circle(graph); } else if (arrangement == 2) { intersectionCount = GraphLayout.RandomPoints(graph, size); } else if (arrangement == 3 || arrangement == 4) { intersectionCount = GraphLayout.Lattice(graph, size, (int)size.Height / 101, (int)size.Width / 101); } else if (arrangement == 5 || arrangement == 6) { intersectionCount = Hexagonal(graph, size); } } return intersectionCount; } /// <summary> /// Resets the positions of all vertices in the game level, arranging them in a circle in /// random order. /// </summary> public static int Circle(Graph graph) { int vertexCount = graph.VertexCount; List<ViewModels.Vertex> verticesToScramble = graph.Vertices.ToList(); int i = 0; while (verticesToScramble.Count > 0) { int vertexIndex = RandomSingleton.Next(verticesToScramble.Count); ViewModels.Vertex vertex = verticesToScramble[vertexIndex]; double angle = Math.PI * 2 * i / vertexCount; var position = new System.Windows.Point(Math.Cos(angle) * 300.0, -Math.Sin(angle) * 300.0); vertex.Position = position; verticesToScramble.RemoveAt(vertexIndex); i++; } graph.CalculateAllIntersections(); return graph.IntersectionCount; } /// <summary> /// Resets the positions of all vertices in the game level, arranging them in a circle in /// random order. /// </summary> public static int RandomPoints(Graph graph, System.Windows.Size size) { int vertexCount = graph.VertexCount; List<ViewModels.Vertex> verticesToScramble = graph.Vertices.ToList(); int i = 0; while (verticesToScramble.Count > 0) { int vertexIndex = RandomSingleton.Next(verticesToScramble.Count); ViewModels.Vertex vertex = verticesToScramble[vertexIndex]; int width = (int)(size.Width / 2); int height = (int)(size.Height / 2); int x = RandomSingleton.Next(-width, width); int y = RandomSingleton.Next(-height, height); var position = new System.Windows.Point(x, y); vertex.Position = position; verticesToScramble.RemoveAt(vertexIndex); i++; } graph.CalculateAllIntersections(); return graph.IntersectionCount; } /// <summary> /// Resets the positions of all vertices in the game level, arranging them in a circle in /// random order. /// </summary> public static int Lattice(Graph graph, System.Windows.Size size, int rows, int columns) { int width = (int)(size.Width - (size.Width / 10)); int height = (int)(size.Height - (size.Height / 10)); int vertexCount = graph.VertexCount; bool addRows = (columns >= rows); while (rows * columns <= vertexCount) { if (addRows) { rows++; addRows = false; } else { columns++; addRows = true; } } var columnBasis = (int)(width / columns); var rowBasis = (int)(height / rows); int widthStart = -(int)(width / 2); int heightStart = -(int)(height / 2); int multiplier = 0; var columnVectors = Enumerable.Repeat(widthStart, columns + 1).Select(n => n + (columnBasis * multiplier++)).ToArray(); multiplier = 0; var rowVectors = Enumerable.Repeat(heightStart, rows + 1).Select(n => n + (rowBasis * multiplier++)).ToArray(); List<(int, int)> latticePoints = new List<(int, int)>(); int colIndex = 0; int rowIndex = 0; while (colIndex < columnVectors.Length) { rowIndex = 0; while (rowIndex < rowVectors.Length) { latticePoints.Add((columnVectors[colIndex], rowVectors[rowIndex])); rowIndex++; } colIndex++; } List<ViewModels.Vertex> verticesToScramble = graph.Vertices.ToList(); int i = 0; while (verticesToScramble.Count > 0) { int vertexIndex = RandomSingleton.Next(verticesToScramble.Count); ViewModels.Vertex vertex = verticesToScramble[vertexIndex]; int latticeIndex = RandomSingleton.Next(latticePoints.Count); (int, int) point = latticePoints[latticeIndex]; latticePoints.RemoveAt(latticeIndex); int x = point.Item1; int y = point.Item2; var position = new System.Windows.Point(x, y); vertex.Position = position; verticesToScramble.RemoveAt(vertexIndex); i++; } graph.CalculateAllIntersections(); return graph.IntersectionCount; } /// <summary> /// Resets the positions of all vertices in the game level, arranging them in a Hexagonal lattice. /// </summary> public static int Hexagonal(Graph graph, System.Windows.Size size) { int hexagonsRequired = graph.VertexCount / 3; int rows = (int)Math.Floor(Math.Sqrt(hexagonsRequired)); int columns = hexagonsRequired / rows; float height = (float)(size.Height / (rows + 1)); List<PointF> hexPoints = GetHexLatticePoints(rows, columns, height); float maxWidth = hexPoints.Select(pt => pt.X).Max(); float maxHeight = hexPoints.Select(pt => pt.Y).Max(); var vertexPool = graph.Vertices.ToList(); float xAdjustment = (float)maxWidth / 2; float yAdjustment = (float)maxHeight / 2; foreach (PointF point in hexPoints) { if (!vertexPool.Any()) { break; } int nextIndex = RandomSingleton.Next(0, vertexPool.Count); ViewModels.Vertex selected = vertexPool[nextIndex]; vertexPool.Remove(selected); selected.SetPosition(new System.Windows.Point(point.X - xAdjustment, point.Y - yAdjustment)); } graph.CalculateAllIntersections(); return graph.IntersectionCount; } // Define other methods and classes here public static List<PointF> GetHexLatticePoints(int rows, int columns, float height) { List<PointF> results = new List<PointF>(); for (int row = 0; row < rows; row++) { for (int col = 0; col < columns; col++) // Draw the row. { PointF[] hexagon = GetHexagonPoints(height, row, col); // Get the points for the row's next hexagon. results.AddRange(hexagon); } } return results.Distinct(new PointFEqualityComparer()).ToList(); } // Return the points that define the indicated hexagon. public static PointF[] GetHexagonPoints(float height, float row, float col) { float width = HexWidth(height); float y = height / 2; // Start with the leftmost corner of the upper left hexagon. float x = 0; x += col * (width * 0.75f); // Move over for the column number. y += row * height; // Move down the required number of rows. if (col % 2 == 1) // If the column is odd, move down half a hex more. { y += height / 2; } return new PointF[] // Generate the points. { new PointF(x, y), new PointF(x + width * 0.25f, y - height / 2), new PointF(x + width * 0.75f, y - height / 2), new PointF(x + width, y), new PointF(x + width * 0.75f, y + height / 2), new PointF(x + width * 0.25f, y + height / 2), }; } // Return the width of a hexagon. public static float HexWidth(float height) { return (float)(4 * (height / 2 / Math.Sqrt(3))); } public class PointFEqualityComparer : IEqualityComparer<PointF> { bool IEqualityComparer<PointF>.Equals(PointF x, PointF y) { if (x == null) { return (y == null) ? true : false; } return (x.X == y.X && x.Y == y.Y) ? true : false; } int IEqualityComparer<PointF>.GetHashCode(PointF obj) { return new Tuple<float, float>(obj.X, obj.Y).GetHashCode(); } } } }
27.961404
122
0.658301
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AdamWhiteHat/Untangle-Game
Untangle/Generation/GraphLayout.cs
7,971
C#
//----------------------------------------------------------------------- // <copyright file="ProtocolMode.cs" // Copyright (c) 2021 Adam Craven. All rights reserved. // </copyright> // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. //----------------------------------------------------------------------- namespace Oprf.Net.Abstractions { /// <summary> /// Oblivious Pseudo-Random Function protocol variant modes of operation. /// </summary> /// <remarks> /// https://datatracker.ietf.org/doc/html/draft-irtf-cfrg-voprf-06.txt#section-3 /// </remarks> public enum ProtocolMode { Base = 0x00, Verifiable = 0x01 // Not supported or needed for Opaque } }
37.96875
84
0.611523
[ "Apache-2.0" ]
channeladam/OPRF.NET
src/Oprf.Net/Abstractions/ProtocolMode.cs
1,215
C#
namespace JsonToRssGenerator.Data { public class Category { public string Name { get; } public string SubCategory { get; } public Category(string name, string subCategory = null) { Name = name; SubCategory = subCategory; } } }
21.266667
64
0.532915
[ "MIT" ]
Newbilius/JsonToPodcastRssGenerator
Program/Data/Category.cs
321
C#
[assembly:System.Diagnostics.DebuggableAttribute((System.Diagnostics.DebuggableAttribute.DebuggingModes)(2))] [assembly:System.Reflection.AssemblyCompanyAttribute("Microsoft Corporation")] [assembly:System.Reflection.AssemblyCopyrightAttribute("Microsoft Corporation. All rights reserved.")] [assembly:System.Reflection.AssemblyDescriptionAttribute("NuGet v3 core library.")] [assembly:System.Reflection.AssemblyFileVersionAttribute("3.5.0.1996")] [assembly:System.Reflection.AssemblyInformationalVersionAttribute("3.5.0-rtm-1996")] [assembly:System.Reflection.AssemblyMetadataAttribute("Serviceable", "True")] [assembly:System.Reflection.AssemblyProductAttribute("NuGet")] [assembly:System.Resources.NeutralResourcesLanguageAttribute("en-US")] [assembly:System.Runtime.CompilerServices.CompilationRelaxationsAttribute(8)] [assembly:System.Runtime.CompilerServices.RuntimeCompatibilityAttribute(WrapNonExceptionThrows=true)] [assembly:System.Runtime.InteropServices.ComVisibleAttribute(false)] [assembly:System.Runtime.Versioning.TargetFrameworkAttribute(".NETStandard,Version=v1.3")] namespace NuGet.Repositories { public partial class LocalPackageInfo { public LocalPackageInfo(string packageId, NuGet.Versioning.NuGetVersion version, string path, string manifestPath, string zipPath) { } public string ExpandedPath { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } [System.Runtime.CompilerServices.CompilerGeneratedAttribute]set { } } public string Id { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public string ManifestPath { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public NuGet.Packaging.NuspecReader Nuspec { get { throw null; } } public NuGet.Versioning.NuGetVersion Version { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public string ZipPath { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public override string ToString() { throw null; } } public partial class LocalPackageSourceInfo { public LocalPackageSourceInfo(NuGet.Repositories.NuGetv3LocalRepository repository, NuGet.Repositories.LocalPackageInfo package) { } public NuGet.Repositories.LocalPackageInfo Package { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public NuGet.Repositories.NuGetv3LocalRepository Repository { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } } public partial class NuGetv3LocalRepository { public NuGetv3LocalRepository(string path) { } public NuGet.Packaging.VersionFolderPathResolver PathResolver { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public string RepositoryRoot { [System.Runtime.CompilerServices.CompilerGeneratedAttribute]get { throw null; } } public void ClearCacheForIds(System.Collections.Generic.IEnumerable<string> packageIds) { } public System.Collections.Generic.IEnumerable<NuGet.Repositories.LocalPackageInfo> FindPackagesById(string packageId) { throw null; } } public static partial class NuGetv3LocalRepositoryUtility { public static NuGet.Repositories.LocalPackageSourceInfo GetPackage(System.Collections.Generic.IReadOnlyList<NuGet.Repositories.NuGetv3LocalRepository> repositories, string id, NuGet.Versioning.NuGetVersion version) { throw null; } } }
77.282609
238
0.795499
[ "MIT" ]
NikolaMilosavljevic/source-build
src/reference-assemblies/NuGet.Repositories/netstandard1.3/3.5.0.0/NuGet.Repositories.cs
3,555
C#
using System; using System.Collections.Generic; using FluentAssertions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using OmniSharp.Extensions.LanguageServer.Protocol; using OmniSharp.Extensions.LanguageServer.Protocol.Client.Capabilities; using OmniSharp.Extensions.LanguageServer.Protocol.Serialization; using OmniSharp.Extensions.LanguageServer.Protocol.Server.Capabilities; using Xunit; namespace Lsp.Tests.Capabilities.Server { public class ServerCapabilitiesTests { [Theory, JsonFixture] public void SimpleTest(string expected) { var model = new ServerCapabilities() { CodeActionProvider = true, CodeLensProvider = new CodeLensOptions() { ResolveProvider = true, }, CompletionProvider = new CompletionOptions() { ResolveProvider = true, TriggerCharacters = new[] { "a", "b", "c" } }, DefinitionProvider = true, DocumentFormattingProvider = true, DocumentHighlightProvider = true, DocumentLinkProvider = new DocumentLinkOptions() { ResolveProvider = true }, DocumentOnTypeFormattingProvider = new DocumentOnTypeFormattingOptions() { FirstTriggerCharacter = ".", MoreTriggerCharacter = new[] { ";", " " } }, DocumentRangeFormattingProvider = true, DocumentSymbolProvider = true, ExecuteCommandProvider = new ExecuteCommandOptions() { Commands = new string[] { "command1", "command2" } }, Experimental = new Dictionary<string, JToken>() { { "abc", "123" } }, HoverProvider = true, ReferencesProvider = true, RenameProvider = true, SignatureHelpProvider = new SignatureHelpOptions() { TriggerCharacters = new[] { ";", " " } }, TextDocumentSync = new TextDocumentSync(new TextDocumentSyncOptions() { Change = TextDocumentSyncKind.Full, OpenClose = true, Save = new SaveOptions() { IncludeText = true }, WillSave = true, WillSaveWaitUntil = true }), WorkspaceSymbolProvider = true, }; var result = Fixture.SerializeObject(model); result.Should().Be(expected); var deresult = new Serializer(ClientVersion.Lsp3).DeserializeObject<ServerCapabilities>(expected); deresult.Should().BeEquivalentTo(model); } } }
39.888889
110
0.549443
[ "MIT" ]
Bia10/csharp-language-server-protocol
test/Lsp.Tests/Capabilities/Server/ServerCapabilitiesTests.cs
2,872
C#
using System; namespace Leger { public class GraphObjectTypeInfo { /// <summary> /// Identifiant unique (GUID) du type de noeud. /// </summary> public Guid Id { get; private set; } /// <summary> /// Nom lisible par un humain du type de noeud. /// </summary> public string Name { get; private set; } /// <summary> /// Description à destination d'un humain du type et de ses données internes. /// </summary> public string Description { get; set; } /// <summary> /// Indique s'il s'agit d'un type noeud ou arc. /// </summary> public GraphObjectType Type { get; private set; } /// <summary> /// Spécifique aux objets de type Edge. /// Indique si l'ordre de déclarations des liens est important ou non dans l'interprétation du type. /// </summary> public bool Oriented { get; internal set; } /// <summary> /// Spécifique aux objets de type Vertex. /// Indique si le contenu du noeud, lorsqu'il est une chaîne de caractères, peut être affichés directement à l'utilisateur. /// </summary> public bool DirectContent { get; private set; } public GraphObjectTypeInfo(Guid id, string name, GraphObjectType type, bool oriented_edge = false, bool direct_content = false) { if (type == GraphObjectType.Edge && direct_content == true) { throw new ArgumentException(); } if (type == GraphObjectType.Vertex && oriented_edge == true) { throw new ArgumentException(); } Id = id; Name = name; Type = type; Oriented = oriented_edge; DirectContent = direct_content; } public GraphObjectTypeInfo(string id, string name, GraphObjectType type, bool oriented_edge = false, bool direct_content = false) : this(Guid.Parse(id), name, type, oriented_edge, direct_content) { } public override bool Equals(object obj) { if (obj is GraphObjectTypeInfo) { GraphObjectTypeInfo nt = (GraphObjectTypeInfo)obj; return Id.Equals(nt.Id); } else { return false; } } public override int GetHashCode() { return Id.GetHashCode(); } } }
32.597403
137
0.547012
[ "BSD-3-Clause" ]
titanix/HyperGraph_Public
Libraries/HyperGraphNetStandard/Graph/TypeInfo/GraphObjectTypeInfo.cs
2,523
C#
using System.Web.Script.Serialization; using NewLife.Collections; using NewLife.Data; namespace NewLife.Cube.Charts; /// <summary>系列。一组数值以及他们映射成的图</summary> public class Series : IExtend3 { #region 属性 /// <summary>图表类型</summary> public String Type { get; set; } //public SeriesTypes Type { get; set; } /// <summary>名称</summary> public String Name { get; set; } /// <summary>数据</summary> public Object Data { get; set; } /// <summary>折线光滑</summary> public Boolean Smooth { get; set; } /// <summary>标记的图形</summary> public String Symbol { get; set; } ///// <summary>标记点。例如最大最小值</summary> //public Object MarkPoint { get; set; } ///// <summary>标记线。例如平均线</summary> //public Object MarkLine { get; set; } /// <summary>扩展字典</summary> [ScriptIgnore] public IDictionary<String, Object> Items { get; set; } = new NullableDictionary<String, Object>(StringComparer.OrdinalIgnoreCase); /// <summary>扩展数据</summary> /// <param name="key"></param> /// <returns></returns> public Object this[String key] { get => Items[key]; set => Items[key] = value; } #endregion #region 方法 /// <summary>标记最大最小值</summary> /// <param name="max"></param> /// <param name="min"></param> public void MarkPoint(Boolean max, Boolean min) { var typeNames = new Dictionary<String, String>(); if (max) typeNames["max"] = "Max"; if (min) typeNames["min"] = "Min"; MarkPoint(typeNames); } /// <summary>标记点。例如最大最小值</summary> /// <param name="typeNames"></param> public void MarkPoint(IDictionary<String, String> typeNames) { Items["markPoint"] = new { data = typeNames.Select(e => new { type = e.Key, name = e.Value }).ToArray() }; } /// <summary>标记平均线</summary> /// <param name="avg"></param> public void MarkLine(Boolean avg) { var typeNames = new Dictionary<String, String>(); if (avg) typeNames["average"] = "Avg"; MarkLine(typeNames); } /// <summary>标记线</summary> /// <param name="typeNames"></param> public void MarkLine(IDictionary<String, String> typeNames) { Items["markLine"] = new { data = typeNames.Select(e => new { type = e.Key, name = e.Value }).ToArray() }; } #endregion }
28.329268
134
0.601378
[ "MIT" ]
xueshaoyu/NewLife.Cube
NewLife.CubeNC/Charts/Series.cs
2,507
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using Microsoft.Framework.PackageManager.CommandLine; using Xunit; namespace Microsoft.Framework.PackageManager.Tests { public class CommandLineApplicationTests { [Fact] public void CommandNameCanBeMatched() { var called = false; var app = new CommandLineApplication(); app.Command("test", c => { c.OnExecute(() => { called = true; return 5; }); }); var result = app.Execute("test"); Assert.Equal(5, result); Assert.True(called); } [Fact] public void RemainingArgsArePassed() { CommandArgument first = null; CommandArgument second = null; var app = new CommandLineApplication(); app.Command("test", c => { first = c.Argument("first", "First argument"); second = c.Argument("second", "Second argument"); c.OnExecute(() => 0); }); app.Execute("test", "one", "two"); Assert.Equal("one", first.Value); Assert.Equal("two", second.Value); } [Fact] public void ExtraArgumentCausesException() { CommandArgument first = null; CommandArgument second = null; var app = new CommandLineApplication(); app.Command("test", c => { first = c.Argument("first", "First argument"); second = c.Argument("second", "Second argument"); c.OnExecute(() => 0); }); var ex = Assert.Throws<Exception>(() => app.Execute("test", "one", "two", "three")); Assert.Contains("three", ex.Message); } [Fact] public void UnknownCommandCausesException() { var app = new CommandLineApplication(); app.Command("test", c => { c.Argument("first", "First argument"); c.Argument("second", "Second argument"); c.OnExecute(() => 0); }); var ex = Assert.Throws<Exception>(() => app.Execute("test2", "one", "two", "three")); Assert.Contains("test2", ex.Message); } [Fact] public void OptionSwitchMayBeProvided() { CommandOption first = null; CommandOption second = null; var app = new CommandLineApplication(); app.Command("test", c => { first = c.Option("--first <NAME>", "First argument"); second = c.Option("--second <NAME>", "Second argument"); c.OnExecute(() => 0); }); app.Execute("test", "--first", "one", "--second", "two"); Assert.Equal("one", first.Value); Assert.Equal("two", second.Value); } [Fact] public void OptionValueMustBeProvided() { CommandOption first = null; var app = new CommandLineApplication(); app.Command("test", c => { first = c.Option("--first <NAME>", "First argument"); c.OnExecute(() => 0); }); var ex = Assert.Throws<Exception>(() => app.Execute("test", "--first")); Assert.Contains("missing value for option", ex.Message); } [Fact] public void ValuesMayBeAttachedToSwitch() { CommandOption first = null; CommandOption second = null; var app = new CommandLineApplication(); app.Command("test", c => { first = c.Option("--first <NAME>", "First argument"); second = c.Option("--second <NAME>", "Second argument"); c.OnExecute(() => 0); }); app.Execute("test", "--first=one", "--second:two"); Assert.Equal("one", first.Value); Assert.Equal("two", second.Value); } [Fact] public void ForwardSlashIsSameAsDashDash() { CommandOption first = null; CommandOption second = null; var app = new CommandLineApplication(); app.Command("test", c => { first = c.Option("--first <NAME>", "First argument"); second = c.Option("--second <NAME>", "Second argument"); c.OnExecute(() => 0); }); app.Execute("test", "/first=one", "/second", "two"); Assert.Equal("one", first.Value); Assert.Equal("two", second.Value); } [Fact] public void ShortNamesMayBeDefined() { CommandOption first = null; CommandOption second = null; var app = new CommandLineApplication(); app.Command("test", c => { first = c.Option("-1 --first <NAME>", "First argument"); second = c.Option("-2 --second <NAME>", "Second argument"); c.OnExecute(() => 0); }); app.Execute("test", "-1=one", "-2", "two"); Assert.Equal("one", first.Value); Assert.Equal("two", second.Value); } } }
29.010363
111
0.480264
[ "Apache-2.0" ]
rvfvazquez/KRuntime
test/Microsoft.Framework.PackageManager.Tests/CommandLineApplicationTests.cs
5,599
C#
using System; using System.Runtime.Serialization; using Vts.Common; namespace Vts.MonteCarlo.Tissues { /// <summary> /// Implements ITissueRegion. Defines a layer infinite in extent along /// x,y-axes and with extent along z-axis given by ZRange. /// </summary> public class LayerTissueRegion : ITissueRegion, ILayerOpticalPropertyRegion { /// <summary> /// constructor for layer region /// </summary> /// <param name="zRange">specifies extent of layer</param> /// <param name="op">optical properties of layer</param> public LayerTissueRegion(DoubleRange zRange, OpticalProperties op) { TissueRegionType = "Layer"; ZRange = zRange; RegionOP = op; } /// <summary> /// default constructor /// </summary> public LayerTissueRegion() : this( new DoubleRange(0.0, 10), new OpticalProperties(0.01, 1.0, 0.8, 1.4)) { } /// <summary> /// tissue region identifier /// </summary> public string TissueRegionType { get; set; } /// <summary> /// extent of z layer /// </summary> public DoubleRange ZRange { get; set; } /// <summary> /// optical properties of layer /// </summary> public OpticalProperties RegionOP { get; set; } /// <summary> /// center of layer /// </summary> [IgnoreDataMember] public Position Center { get { return new Position( 0D, 0D, (ZRange.Start + ZRange.Stop) / 2); } set { var oldCenter = Center; var newCenter = value; var dz = newCenter.Z - oldCenter.Z; ZRange.Start += dz; ZRange.Stop += dz; } } /// <summary> /// This checks which region photon is currently in. /// inclusion defined in half-open interval [start,stop) so that continuum of layers do not overlap. /// </summary> /// <param name="p">Position being checked</param> /// <returns>True if photon in region, false if not</returns> public bool ContainsPosition(Position p) { return p.Z >= ZRange.Start && p.Z < ZRange.Stop; } /// <summary> /// Method to determine if photon on layer boundary. Needed to determine which boundary photon is /// on when layer region contains inclusion. Errors in Position accommodated for in test. /// </summary> /// <param name="p">Position being checked</param> /// <returns>True if photon on boundary, false if not</returns> public bool OnBoundary(Position p) { var onBoundary = false; if (Math.Abs(p.Z - ZRange.Start) < 1e-10 || Math.Abs(p.Z - ZRange.Stop) < 1e-10) { onBoundary = true; } return onBoundary; } /// <summary> /// method to determine normal to surface at given position /// </summary> /// <param name="position"></param> /// <returns>Direction</returns> public Direction SurfaceNormal(Position position) { throw new NotImplementedException(); } /// <summary> /// Method to determine if photon track or ray intersects layer boundary. /// Note: LayerTissueRegion.RayIntersectBoundary does NOT use photon.S in the calculation /// so all photons (unless horizontal) intersect the top or bottom of the layer and the /// returned distance is not infinity (unless horizontal). This is because MonteCarloSimulation /// uses the distance to the boundary without intersection in its processing. /// This is different that all other TissueRegions. /// </summary> /// <param name="photon">Photon</param> /// <param name="distanceToBoundary">return: distance to boundary, actual distance if no intersection</param> /// <returns>true if intersection, false otherwise</returns> public bool RayIntersectBoundary(Photon photon, out double distanceToBoundary) { if (photon.DP.Direction.Uz == 0.0) { distanceToBoundary = double.PositiveInfinity; return false; } // going "up" in negative z-direction bool goingUp = photon.DP.Direction.Uz < 0.0; distanceToBoundary = goingUp ? (ZRange.Start - photon.DP.Position.Z) / photon.DP.Direction.Uz : (ZRange.Stop - photon.DP.Position.Z) / photon.DP.Direction.Uz; return true; } //public bool RayExitBoundary(Photon photptr, ref double distanceToBoundary) //{ // distanceToBoundary = 0.0; /* distance to boundary */ // if (photptr.DP.Direction.Uz < 0.0) // distanceToBoundary = ( Z.Start - photptr.DP.Position.Z) / // photptr.DP.Direction.Uz; // else if (photptr.DP.Direction.Uz > 0.0) // distanceToBoundary = ( Z.Stop - photptr.DP.Position.Z) / // photptr.DP.Direction.Uz; // if ((photptr.DP.Direction.Uz != 0.0) && (photptr.S > distanceToBoundary)) // { // //photptr.HitBoundary = true; // ////photptr.SLeft = (photptr.S - distanceToBoundary) * (mua + mus); // DAW // //photptr.SLeft = (photptr.S - distanceToBoundary) * photptr._tissue.Regions[photptr.CurrentRegionIndex].ScatterLength; // //photptr.S = distanceToBoundary; // return true; // } // else // return false; //} } }
39.333333
138
0.529335
[ "MIT" ]
VirtualPhotonics/VTS
src/Vts/MonteCarlo/Tissues/LayerTissueRegion.cs
6,136
C#
using System; using System.Collections.Generic; using Smooth.Algebraics; using Smooth.Slinq; namespace Smooth.Foundations.PatternMatching.Options { public sealed class OfMatcher<T> { private readonly OptionMatcher<T> _matcher; private readonly Action<Func<Option<T>, bool>, Action<T>> _addPredicateAndAction; private readonly List<T> _values = new List<T>(5); internal OfMatcher(T value, OptionMatcher<T> matcher, Action<Func<Option<T>, bool>, Action<T>> addPredicateAndAction) { _matcher = matcher; _addPredicateAndAction = addPredicateAndAction; _values.Add(value); } public OfMatcher<T> Or(T value) { _values.Add(value); return this; } public OptionMatcher<T> Do(Action<T> action) { _addPredicateAndAction(o => o.isSome && _values.Slinq() .Any((v, p) => Collections.EqualityComparer<T>.Default.Equals(v, p), o.value), action); return _matcher; } } }
32.8
125
0.571429
[ "MIT" ]
Volodej/smooth.foundations
Smooth/Smooth.Foundations.PatternMatching/Options/OfMatcher.cs
1,150
C#
using System; namespace RTextNppPlugin.Utilities.WpfControlHost { using RTextNppPlugin.Scintilla; using RTextNppPlugin.Utilities.Settings; internal class PersistentWpfControlHost<T> : WpfControlHostBase<T>, IDisposable where T : System.Windows.Forms.Form { #region [Interface] public PersistentWpfControlHost(Settings.RTextNppSettings persistenceKey, T elementHost, ISettings settings, INpp nppHelper ) : base(elementHost, nppHelper) { _key = persistenceKey; _settings = settings; } #endregion #region [Implementation Details] internal override void OnVisibilityChanged(object sender, EventArgs e) { base.OnVisibilityChanged(sender, e); _settings.Set(base.Visible, _key); } #endregion #region [Data members] readonly Settings.RTextNppSettings _key; readonly ISettings _settings; #endregion } }
36.259259
164
0.665986
[ "EPL-1.0" ]
sanastasiou/RTextNpp
RTextNpp/Utilities/WpfControlHost/PersistentWpfControlHost.cs
981
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Data; using System.Data.SqlClient; namespace Microsoft.Extensions.HealthChecks { public static class HealthCheckBuilderSqlServerExtensions { public static HealthCheckBuilder AddSqlCheck(this HealthCheckBuilder builder, string name, string connectionString) { builder.AddCheck($"SqlCheck({name})", async () => { try { //TODO: There is probably a much better way to do this. using (var connection = new SqlConnection(connectionString)) { connection.Open(); using (var command = connection.CreateCommand()) { command.CommandType = CommandType.Text; command.CommandText = "SELECT 1"; var result = (int)await command.ExecuteScalarAsync().ConfigureAwait(false); if (result == 1) { return HealthCheckResult.Healthy($"SqlCheck({name}): Healthy"); } return HealthCheckResult.Unhealthy($"SqlCheck({name}): Unhealthy"); } } } catch (Exception ex) { return HealthCheckResult.Unhealthy($"SqlCheck({name}): Exception during check: {ex.GetType().FullName}"); } }); return builder; } } }
38.565217
125
0.502818
[ "MIT" ]
cheahengsoon/eShopOnContainers
src/BuildingBlocks/HealthChecks/src/Microsoft.Extensions.HealthChecks.SqlServer/HealthCheckBuilderSqlServerExtensions.cs
1,774
C#
using System.Threading.Tasks; using Microsoft.AspNetCore.Mvc; using Abp.Application.Services.Dto; using Abp.AspNetCore.Mvc.Authorization; using Recyclops.Authorization; using Recyclops.Controllers; using Recyclops.Users; using Recyclops.Web.Models.Users; using Recyclops.Users.Dto; namespace Recyclops.Web.Controllers { [AbpMvcAuthorize(PermissionNames.Pages_Users)] public class UsersController : RecyclopsControllerBase { private readonly IUserAppService _userAppService; public UsersController(IUserAppService userAppService) { _userAppService = userAppService; } public async Task<ActionResult> Index() { var users = (await _userAppService.GetAll(new PagedUserResultRequestDto {MaxResultCount = int.MaxValue})).Items; // Paging not implemented yet var roles = (await _userAppService.GetRoles()).Items; var model = new UserListViewModel { Users = users, Roles = roles }; return View(model); } public async Task<ActionResult> EditUserModal(long userId) { var user = await _userAppService.Get(new EntityDto<long>(userId)); var roles = (await _userAppService.GetRoles()).Items; var model = new EditUserModalViewModel { User = user, Roles = roles }; return View("_EditUserModal", model); } } }
31.541667
154
0.6321
[ "MIT" ]
JoshTheGent/Recyclops
4.7.1/aspnet-core/src/Recyclops.Web.Mvc/Controllers/UsersController.cs
1,516
C#
using System.Data; using Microsoft.Extensions.Configuration; using Npgsql; using SafeRebus.Abstractions; using SafeRebus.Config; namespace SafeRebus.Outbox.Database { public class DbProvider : IDbProvider { private readonly IConfiguration Configuration; private const string ConnectionStringTemplate = "User ID={0};Password={1};Host={2};Port={3};Database={4};Pooling={5};"; private IDbConnection DbConnection; private IDbTransaction DbTransaction; private string User => Configuration.GetDbUser(); private string Password => Configuration.GetDbPassword(); private string Host => Configuration.GetDbHostname(); private string Port => Configuration.GetDbPort(); private string Database => Configuration.GetDbName(); private string Pooling => Configuration.GetDbPooling(); public DbProvider(IConfiguration configuration) { Configuration = configuration; } public string GetConnectionString() { var connectionString = string.Format(ConnectionStringTemplate, User, Password, Host, Port, Database, Pooling); return connectionString; } public IDbConnection GetDbConnection() { DbConnection = DbConnection ?? CreateAndOpenDbConnection(); return DbConnection; } public IDbTransaction GetDbTransaction() { DbTransaction = DbTransaction ?? GetDbConnection().BeginTransaction(); return DbTransaction; } private IDbConnection CreateAndOpenDbConnection() { var dbConnection = new NpgsqlConnection(GetConnectionString()); dbConnection.Open(); return dbConnection; } public void Dispose() { DbTransaction?.Dispose(); DbConnection?.Dispose(); } } }
30.681818
127
0.609877
[ "MIT" ]
hansehe/SafeRebus
src/SafeRebus/Implementations/SafeRebus.Outbox.Database/DbProvider.cs
2,027
C#
using System.Linq; using SharpGen.Config; using SharpGen.CppModel; using SharpGen.Model; using SharpGen.Transform; using Xunit; using Xunit.Abstractions; namespace SharpGen.UnitTests.Mapping { public class Interface : MappingTestBase { public Interface(ITestOutputHelper outputHelper) : base(outputHelper) { } [Fact] public void Simple() { var config = new ConfigFile { Id = nameof(Simple), Namespace = nameof(Simple), Includes = { new IncludeRule { File = "interface.h", Attach = true, Namespace = nameof(Simple) } }, Bindings = { new BindRule("int", "System.Int32") } }; var iface = new CppInterface("Interface") { TotalMethodCount = 1 }; iface.Add(new CppMethod("method") { ReturnValue = new CppReturnValue { TypeName = "int" } }); var include = new CppInclude("interface"); include.Add(iface); var module = new CppModule("SharpGenTestModule"); module.Add(include); var (solution, _) = MapModel(module, config); Assert.Single(solution.EnumerateDescendants<CsInterface>()); var csIface = solution.EnumerateDescendants<CsInterface>().First(); Assert.Single(csIface.Methods); var method = csIface.Methods.First(); Assert.Equal(0, method.Offset); Assert.IsType<CsFundamentalType>(method.ReturnValue.PublicType); Assert.Equal(TypeRegistry.Int32, method.ReturnValue.PublicType); } [Fact] public void DualCallbackFlowsNativeImplementation() { var config = new ConfigFile { Id = nameof(Simple), Namespace = nameof(Simple), Includes = { new IncludeRule { File = "interface.h", Attach = true, Namespace = nameof(Simple) } }, Bindings = { new BindRule("int", "System.Int32") }, Mappings = { new MappingRule { Interface = "Interface", IsCallbackInterface = true, IsDualCallbackInterface = true } } }; var iface = new CppInterface("Interface") { TotalMethodCount = 1 }; iface.Add(new CppMethod("method") { ReturnValue = new CppReturnValue { TypeName = "int" } }); var include = new CppInclude("interface"); include.Add(iface); var module = new CppModule("SharpGenTestModule"); module.Add(include); var (_, defines) = GetConsumerBindings(module, config); var interfaceDefine = defines.First(define => define.Interface == "Simple.Interface"); Assert.Equal("Simple.InterfaceNative", interfaceDefine.NativeImplementation); } [Fact] public void DefineWithNativeImplementationDefinesNativeImplementationType() { var config = new ConfigFile { Id = nameof(DefineWithNativeImplementationDefinesNativeImplementationType), Namespace = nameof(DefineWithNativeImplementationDefinesNativeImplementationType), Includes = { new IncludeRule { File = "interface.h", Attach = true, Namespace = nameof(DefineWithNativeImplementationDefinesNativeImplementationType) } }, Extension = { new DefineExtensionRule { Interface = "Imported.Param", NativeImplementation = "Imported.ParamNative" } }, Bindings = { new BindRule("int", "System.Int32"), new BindRule("Param", "Imported.Param") } }; var iface = new CppInterface("Interface") { TotalMethodCount = 1 }; var method = new CppMethod("method") { ReturnValue = new CppReturnValue { TypeName = "int" } }; method.Add(new CppParameter("param") { TypeName = "Param", Pointer = "*" }); iface.Add(method); var include = new CppInclude("interface"); include.Add(iface); var module = new CppModule("SharpGenTestModule"); module.Add(include); var (solution, _) = MapModel(module, config); Assert.Single(solution.EnumerateDescendants<CsParameter>()); var param = solution.EnumerateDescendants<CsParameter>().First(); Assert.IsType<CsInterface>(param.PublicType); Assert.NotNull(((CsInterface)param.PublicType).NativeImplementation); Assert.False(Logger.HasErrors); } [Fact] public void ReturnStructByPointer() { ConfigFile config = new() { Id = nameof(ReturnStructByPointer), Namespace = nameof(ReturnStructByPointer), Includes = { new IncludeRule { File = "d3d12.h", Attach = true, Namespace = nameof(ReturnStructByPointer) } }, Bindings = { new BindRule("int", "System.Int32"), new BindRule("DESC", "SharpGen.Runtime.PointerSize"), new BindRule("UINT", "System.UInt32") } }; CppStruct rootSig = new("D3D12_ROOT_SIGNATURE_DESC") { Items = new[] { new CppField("NumParameters") { TypeName = "UINT", Offset = 0 }, new CppField("pParameters") { TypeName = "DESC", Pointer = "*", Const = true, Offset = 4 }, new CppField("NumStaticSamplers") { TypeName = "UINT", Offset = 8 }, new CppField("pStaticSamplers") { TypeName = "DESC", Pointer = "*", Const = true, Offset = 12 }, new CppField("Flags") { TypeName = "UINT", Offset = 16 } } }; CppInterface iface = new("ID3D12RootSignatureDeserializer") { TotalMethodCount = 1, Items = new[] { new CppMethod("GetRootSignatureDesc") { ReturnValue = new CppReturnValue { Const = true, TypeName = rootSig.FullName, Pointer = "*" } } } }; CppModule module = new("SharpGenTestModule") { Items = new[] { new CppInclude("d3d12") { Items = new CppContainer[] { rootSig, iface } } } }; var (solution, _) = MapModel(module, config); Assert.Empty(solution.EnumerateDescendants<CsParameter>()); Assert.Single(solution.EnumerateDescendants<CsReturnValue>()); var returnValue = solution.EnumerateDescendants<CsReturnValue>().Single(); Assert.True(returnValue.HasPointer); Assert.Equal(rootSig.Name, returnValue.PublicType.CppElementName); Assert.False(Logger.HasErrors); } [Fact] public void VoidInBufferParameter() { ConfigFile config = new() { Id = nameof(VoidInBufferParameter), Namespace = nameof(VoidInBufferParameter), Includes = { new IncludeRule { File = "dxcapi.h", Attach = true, Namespace = nameof(VoidInBufferParameter) } }, Extension = { new DefineExtensionRule { Struct = "SharpGen.Runtime.Result", SizeOf = 4, IsNativePrimitive = true }, new DefineExtensionRule { Struct = "SharpGen.Runtime.PointerSize", SizeOf = 8, IsNativePrimitive = true } }, Bindings = { new BindRule("HRESULT", "SharpGen.Runtime.Result"), new BindRule("SIZE_T", "SharpGen.Runtime.PointerSize"), new BindRule("UINT32", "System.UInt32"), new BindRule("void", "System.Void") } }; CppInterface blob = new("IDxcBlob") { Guid = "8BA5FB08-5195-40e2-AC58-0D989C3A0102", Items = new[] { new CppMethod("GetBufferPointer") { ReturnValue = new CppReturnValue { TypeName = "void", Pointer = "*" } }, new CppMethod("GetBufferSize") { ReturnValue = new CppReturnValue { TypeName = "SIZE_T" } } } }; CppInterface blobEncoding = new("IDxcBlobEncoding") { Guid = "7241d424-2646-4191-97c0-98e96e42fc68", Base = blob.Name }; CppInterface iface = new("IDxcUtils") { TotalMethodCount = 1, Items = new[] { new CppMethod("CreateBlobFromPinned") { CallingConvention = CppCallingConvention.StdCall, ReturnValue = new CppReturnValue { TypeName = "HRESULT" }, Items = new[] { new CppParameter("pData") { Const = true, TypeName = "void", Pointer = "*", Attribute = ParamAttribute.In | ParamAttribute.Buffer }, new CppParameter("size") { TypeName = "UINT32", Attribute = ParamAttribute.In }, new CppParameter("codePage") { TypeName = "UINT32", Attribute = ParamAttribute.In }, new CppParameter("pBlobEncoding") { TypeName = "IDxcBlobEncoding", Pointer = "**", Attribute = ParamAttribute.Out } } } } }; CppModule module = new("SharpGenTestModule") { Items = new[] { new CppInclude("dxcapi") { Items = new CppContainer[] { blob, blobEncoding, iface } } } }; var (solution, _) = MapModel(module, config); var csBlob = solution.EnumerateDescendants<CsInterface>(false) .SingleOrDefault(x => x.Name == blob.Name); var csBlobEncoding = solution.EnumerateDescendants<CsInterface>(false) .SingleOrDefault(x => x.Name == blobEncoding.Name); var csUtils = solution.EnumerateDescendants<CsInterface>(false) .SingleOrDefault(x => x.Name == iface.Name); Assert.NotNull(csBlob); Assert.NotNull(csBlobEncoding); Assert.NotNull(csUtils); Assert.Equal(blob.Guid, csBlob.Guid); Assert.Equal(blobEncoding.Guid, csBlobEncoding.Guid); var method = csUtils.EnumerateDescendants<CsMethod>().SingleOrDefault(); Assert.NotNull(method); Assert.Equal(CppCallingConvention.StdCall, method.CppCallingConvention); var methodParams = method.EnumerateDescendants<CsParameter>().ToArray(); Assert.Equal(4, methodParams.Length); Assert.Equal("data", methodParams[0].Name); Assert.Equal("size", methodParams[1].Name); Assert.Equal("codePage", methodParams[2].Name); Assert.Equal("blobEncoding", methodParams[3].Name); Assert.False(methodParams[0].IsOut); Assert.False(methodParams[1].IsOut); Assert.False(methodParams[2].IsOut); Assert.True(methodParams[3].IsOut); Assert.True(methodParams[0].IsIn); Assert.True(methodParams[1].IsIn); Assert.True(methodParams[2].IsIn); Assert.False(methodParams[3].IsIn); Assert.Equal(TypeRegistry.IntPtr, methodParams[0].MarshalType); Assert.Equal(TypeRegistry.IntPtr, methodParams[0].PublicType); Assert.Equal(TypeRegistry.UInt32, methodParams[1].MarshalType); Assert.Equal(TypeRegistry.UInt32, methodParams[1].PublicType); Assert.Equal(TypeRegistry.UInt32, methodParams[2].MarshalType); Assert.Equal(TypeRegistry.UInt32, methodParams[2].PublicType); Assert.Equal(csBlobEncoding, methodParams[3].MarshalType); Assert.Equal(csBlobEncoding, methodParams[3].PublicType); Assert.True(methodParams[0].HasPointer); Assert.False(methodParams[0].IsArray); Assert.False(methodParams[0].IsInterface); Assert.True(methodParams[0].IsValueType); Assert.True(methodParams[0].IsPrimitive); Assert.False(methodParams[0].HasParams); Assert.False(methodParams[1].HasPointer); Assert.False(methodParams[1].IsArray); Assert.False(methodParams[1].IsInterface); Assert.True(methodParams[1].IsValueType); Assert.True(methodParams[1].IsPrimitive); Assert.False(methodParams[1].HasParams); Assert.False(methodParams[2].HasPointer); Assert.False(methodParams[2].IsArray); Assert.False(methodParams[2].IsInterface); Assert.True(methodParams[2].IsValueType); Assert.True(methodParams[2].IsPrimitive); Assert.False(methodParams[2].HasParams); Assert.True(methodParams[3].HasPointer); Assert.False(methodParams[3].IsArray); Assert.True(methodParams[3].IsInterface); Assert.False(methodParams[3].IsValueType); Assert.False(methodParams[3].IsPrimitive); Assert.False(methodParams[3].HasParams); Assert.False(Logger.HasErrors); } [Fact] public void BoundIntPtrInParameter() { ConfigFile config = new() { Id = nameof(BoundIntPtrInParameter), Namespace = nameof(BoundIntPtrInParameter), Includes = { new IncludeRule { File = "d3d9.h", Attach = true, Namespace = nameof(BoundIntPtrInParameter) } }, Extension = { new DefineExtensionRule { Struct = "SharpGen.Runtime.Result", SizeOf = 4, IsNativePrimitive = true } }, Bindings = { new BindRule("HRESULT", "SharpGen.Runtime.Result"), new BindRule("HDC", "System.IntPtr") } }; CppInterface iface = new("IDirect3DSurface9") { TotalMethodCount = 1, Items = new[] { new CppMethod("ReleaseDC") { CallingConvention = CppCallingConvention.StdCall, ReturnValue = new CppReturnValue { TypeName = "HRESULT" }, Items = new[] { new CppParameter("hdc") { TypeName = "HDC", Attribute = ParamAttribute.In }, } } } }; CppModule module = new("SharpGenTestModule") { Items = new[] { new CppInclude("d3d9") { Items = new CppContainer[] { iface } } } }; var (solution, _) = MapModel(module, config); var csUtils = solution.EnumerateDescendants<CsInterface>(false) .SingleOrDefault(x => x.Name == iface.Name); Assert.NotNull(csUtils); var method = csUtils.EnumerateDescendants<CsMethod>().SingleOrDefault(); Assert.NotNull(method); Assert.Equal(CppCallingConvention.StdCall, method.CppCallingConvention); var methodParams = method.EnumerateDescendants<CsParameter>().ToArray(); Assert.Single(methodParams); var param = methodParams[0]; Assert.Equal("hdc", param.Name); Assert.False(param.IsOut); Assert.True(param.IsIn); Assert.Equal(TypeRegistry.IntPtr, param.MarshalType); Assert.Equal(TypeRegistry.IntPtr, param.PublicType); Assert.False(param.HasPointer); Assert.False(param.IsArray); Assert.False(param.IsInterface); Assert.True(param.IsValueType); Assert.True(param.IsPrimitive); Assert.False(param.HasParams); var interopParams = method.InteropSignatures.ToArray(); Assert.Single(interopParams); Assert.Equal(PlatformDetectionType.Any, interopParams[0].Key); var interopParam = interopParams[0].Value; Assert.Equal("int", interopParam.ReturnType); Assert.Single(interopParam.ParameterTypes); Assert.Equal($"_{param.Name}", interopParam.ParameterTypes[0].Name); Assert.Equal(TypeRegistry.VoidPtr, interopParam.ParameterTypes[0].InteropType); Assert.False(Logger.HasErrors); } } }
34.4496
105
0.432075
[ "MIT" ]
SharpGenTools/SharpGenTools
SharpGen.UnitTests/Mapping/Interface.cs
21,533
C#
using System; using System.Collections.Generic; using System.Linq; using Foundation; using UIKit; namespace App_Xamarin_Pcl.iOS { public class Application { // This is the main entry point of the application. static void Main(string[] args) { // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); } } }
23.555556
82
0.731132
[ "MIT" ]
zyl910/vscsprojects
vs14_2015/Xamarin/App_Xamarin_Pcl/App_Xamarin_Pcl/App_Xamarin_Pcl.iOS/Main.cs
426
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("MathelSharp")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("MathelSharp")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("9e51eac3-92df-412a-81ae-ae987b291ade")] // 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.675676
85
0.726066
[ "MIT" ]
ajlopez/MathelSharp
Src/MathelSharp/Properties/AssemblyInfo.cs
1,434
C#
using SaveSystem; using System; using System.Collections; using System.Collections.Generic; using System.Linq; using UnityEditor; using UnityEditor.SceneManagement; using UnityEditor.UIElements; using UnityEngine; using UnityEngine.UIElements; [CanEditMultipleObjects] [CustomEditor(typeof(SceneSaveable))] public class SceneSaveableEditor : Editor { public VisualTreeAsset uxml; public StyleSheet styleSheet; private VisualElement listHolder; public override VisualElement CreateInspectorGUI() { if (targets.Length > 1) { VisualElement uxmlVE = uxml.CloneTree(); return uxmlVE; } else { SceneSaveable target = this.target as SceneSaveable; if (target.saveables == null) { target.saveables = new UnityEngine.Object[0]; } VisualElement uxmlVE = uxml.CloneTree(); uxmlVE.Add(new Label("Saveable targets") { style = { unityFontStyleAndWeight = FontStyle.Bold } }); listHolder = new VisualElement(); RedrawList(target, listHolder); VisualElement buttonHolder = new VisualElement() { style = { flexWrap = Wrap.Wrap, flexDirection = FlexDirection.RowReverse } }; Button addAll = new Button(AddAllSaveables) { style = { width = 100, marginLeft = 5 }, text = "Add all" }; Button minus = new Button(RemoveOne) { style = { width = 20, marginLeft = 5 }, text = "-" }; Button plus = new Button(AddOne) { style = { width = 20, marginLeft = 5 }, text = "+" }; buttonHolder.Add(addAll); buttonHolder.Add(minus); buttonHolder.Add(plus); uxmlVE.Add(listHolder); uxmlVE.Add(buttonHolder); return uxmlVE; } } private void RedrawList(SceneSaveable target, VisualElement listHolder) { listHolder.Clear(); for (int i = 0; i < target.saveables.Length; i++) { var objectField = new ObjectField(i.ToString()); objectField.allowSceneObjects = true; objectField.objectType = typeof(ISaveable); objectField.value = (target.saveables[i] as UnityEngine.Object); var index = i; objectField.RegisterValueChangedCallback( (obj) => { if (obj.newValue is ISaveable) { EditorSceneManager.MarkSceneDirty(target.gameObject.scene); target.saveables[index] = obj.newValue; } }); listHolder.Add(objectField); } } private void AddAllSaveables() { SceneSaveable target = this.target as SceneSaveable; EditorSceneManager.MarkSceneDirty(target.gameObject.scene); var all = target.gameObject.GetComponents<ISaveable>() .Select(x => x as UnityEngine.Object).ToArray(); target.saveables = all; RedrawList(target, listHolder); } private void AddOne() { SceneSaveable target = this.target as SceneSaveable; EditorSceneManager.MarkSceneDirty(target.gameObject.scene); UnityEngine.Object[] newArr = new UnityEngine.Object[target.saveables.Length + 1]; Array.Copy(target.saveables, newArr, target.saveables.Length); target.saveables = newArr; RedrawList(target, listHolder); } private void RemoveOne() { SceneSaveable target = this.target as SceneSaveable; if (target.saveables.Length == 0) return; EditorSceneManager.MarkSceneDirty(target.gameObject.scene); UnityEngine.Object[] newArr = new UnityEngine.Object[target.saveables.Length - 1]; Array.Copy(target.saveables, newArr, newArr.Length); target.saveables = newArr; RedrawList(target, listHolder); } }
19.587571
84
0.693106
[ "MIT" ]
helsinki-xr-center/Esteettomyys
Assets/Scripts/SaveSystem/Editor/SceneSaveableEditor.cs
3,469
C#
using System; using JetBrains.Annotations; namespace Alba.InkBunny.Api { [Flags] [PublicAPI] public enum SearchSaleType { None = 0, Digital = 1 << 0, Print = 1 << 1, All = Digital | Print, } }
14.588235
30
0.540323
[ "Unlicense" ]
Athari/InkBunny.Api
Alba.InkBunny.Api/Requests/Search/SearchSaleType.cs
250
C#
// Copyright 2018 by JCoder58. See License.txt for license // Auto-generated --- Do not modify. using System; using System.Collections.Generic; using System.Runtime.InteropServices; using UE4.Core; using UE4.CoreUObject; using UE4.CoreUObject.Native; using UE4.InputCore; using UE4.Native; #pragma warning disable CS0108 using UE4.Engine.Native; namespace UE4.Engine { ///<summary> ///USkeleton : that links between mesh and animation /// - Bone hierarchy for animations /// - Bone/track linkup between mesh and animation /// - Retargetting related ///</summary> ///<remarks>- Mirror table</remarks> public unsafe partial class Skeleton : UObject { //TODO: array not UObject TArray BoneTree ///<summary>Guid for virtual bones.</summary> ///<remarks>Separate so that we don't have to dirty the original guid when only changing virtual bones</remarks> public unsafe FGuid VirtualBoneGuid { get {return Skeleton_ptr->VirtualBoneGuid;} set {Skeleton_ptr->VirtualBoneGuid = value;} } //TODO: array not UObject TArray VirtualBones ///<summary> ///Array of named socket locations, set up in editor and used as a shortcut instead of specifying ///everything explicitly to AttachComponent in the SkeletalMeshComponent. ///</summary> public ObjectArrayField<SkeletalMeshSocket> Sockets{ get { if(Sockets_store == null) Sockets_store = new ObjectArrayField<SkeletalMeshSocket> (&Skeleton_ptr->Sockets); return Sockets_store; } } private ObjectArrayField<SkeletalMeshSocket> Sockets_store; ///<summary>Container for smart name mappings</summary> public unsafe SmartNameContainer SmartNames { get {return Skeleton_ptr->SmartNames;} set {Skeleton_ptr->SmartNames = value;} } ///<summary>List of blend profiles available in this skeleton</summary> public ObjectArrayField<BlendProfile> BlendProfiles{ get { if(BlendProfiles_store == null) BlendProfiles_store = new ObjectArrayField<BlendProfile> (&Skeleton_ptr->BlendProfiles); return BlendProfiles_store; } } private ObjectArrayField<BlendProfile> BlendProfiles_store; //TODO: array not UObject TArray SlotGroups //TODO: soft object TSoftObjectPtr<USkeletalMesh> PreviewSkeletalMesh //TODO: soft object TSoftObjectPtr<UDataAsset> AdditionalPreviewSkeletalMeshes ///<summary>Rig Config</summary> public unsafe RigConfiguration RigConfig { get {return Skeleton_ptr->RigConfig;} set {Skeleton_ptr->RigConfig = value;} } //TODO: array not UObject TArray AnimationNotifies ///<summary>Attached assets component for this skeleton</summary> public unsafe PreviewAssetAttachContainer PreviewAttachedAssetContainer { get {return Skeleton_ptr->PreviewAttachedAssetContainer;} set {Skeleton_ptr->PreviewAttachedAssetContainer = value;} } ///<summary>Array of user data stored with the asset</summary> public ObjectArrayField<AssetUserData> AssetUserData{ get { if(AssetUserData_store == null) AssetUserData_store = new ObjectArrayField<AssetUserData> (&Skeleton_ptr->AssetUserData); return AssetUserData_store; } } private ObjectArrayField<AssetUserData> AssetUserData_store; static Skeleton() { StaticClass = Main.GetClass("Skeleton"); } internal unsafe Skeleton_fields* Skeleton_ptr => (Skeleton_fields*) ObjPointer.ToPointer(); ///<summary>Convert from IntPtr to UObject</summary> public static implicit operator Skeleton(IntPtr p) => UObject.Make<Skeleton>(p); ///<summary>Get UE4 Class</summary> public static Class StaticClass {get; private set;} ///<summary>Get UE4 Default Object for this Class</summary> public static Skeleton DefaultObject => Main.GetDefaultObject(StaticClass); ///<summary>Spawn an object of this class</summary> public static Skeleton New(UObject obj = null, Name name = new Name()) => Main.NewObject(StaticClass, obj, name); } }
47.722222
133
0.681257
[ "MIT" ]
UE4DotNet/Plugin
DotNet/DotNet/UE4/Generated/Engine/Skeleton.cs
4,295
C#
using System; using SLua; using System.Collections.Generic; [UnityEngine.Scripting.Preserve] public class Lua_UnityEngine_AvatarMask : LuaObject { [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int constructor(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif UnityEngine.AvatarMask o; o=new UnityEngine.AvatarMask(); pushValue(l,true); pushValue(l,o); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int GetHumanoidBodyPartActive(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif UnityEngine.AvatarMask self=(UnityEngine.AvatarMask)checkSelf(l); UnityEngine.AvatarMaskBodyPart a1; a1 = (UnityEngine.AvatarMaskBodyPart)LuaDLL.luaL_checkinteger(l, 2); var ret=self.GetHumanoidBodyPartActive(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int SetHumanoidBodyPartActive(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif UnityEngine.AvatarMask self=(UnityEngine.AvatarMask)checkSelf(l); UnityEngine.AvatarMaskBodyPart a1; a1 = (UnityEngine.AvatarMaskBodyPart)LuaDLL.luaL_checkinteger(l, 2); System.Boolean a2; checkType(l,3,out a2); self.SetHumanoidBodyPartActive(a1,a2); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int AddTransformPath(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif int argc = LuaDLL.lua_gettop(l); if(argc==2){ UnityEngine.AvatarMask self=(UnityEngine.AvatarMask)checkSelf(l); UnityEngine.Transform a1; checkType(l,2,out a1); self.AddTransformPath(a1); pushValue(l,true); return 1; } else if(argc==3){ UnityEngine.AvatarMask self=(UnityEngine.AvatarMask)checkSelf(l); UnityEngine.Transform a1; checkType(l,2,out a1); System.Boolean a2; checkType(l,3,out a2); self.AddTransformPath(a1,a2); pushValue(l,true); return 1; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function AddTransformPath to call"); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int RemoveTransformPath(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif int argc = LuaDLL.lua_gettop(l); if(argc==2){ UnityEngine.AvatarMask self=(UnityEngine.AvatarMask)checkSelf(l); UnityEngine.Transform a1; checkType(l,2,out a1); self.RemoveTransformPath(a1); pushValue(l,true); return 1; } else if(argc==3){ UnityEngine.AvatarMask self=(UnityEngine.AvatarMask)checkSelf(l); UnityEngine.Transform a1; checkType(l,2,out a1); System.Boolean a2; checkType(l,3,out a2); self.RemoveTransformPath(a1,a2); pushValue(l,true); return 1; } pushValue(l,false); LuaDLL.lua_pushstring(l,"No matched override function RemoveTransformPath to call"); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int GetTransformPath(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif UnityEngine.AvatarMask self=(UnityEngine.AvatarMask)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); var ret=self.GetTransformPath(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int SetTransformPath(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif UnityEngine.AvatarMask self=(UnityEngine.AvatarMask)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); System.String a2; checkType(l,3,out a2); self.SetTransformPath(a1,a2); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int GetTransformActive(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif UnityEngine.AvatarMask self=(UnityEngine.AvatarMask)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); var ret=self.GetTransformActive(a1); pushValue(l,true); pushValue(l,ret); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int SetTransformActive(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif UnityEngine.AvatarMask self=(UnityEngine.AvatarMask)checkSelf(l); System.Int32 a1; checkType(l,2,out a1); System.Boolean a2; checkType(l,3,out a2); self.SetTransformActive(a1,a2); pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int get_transformCount(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif UnityEngine.AvatarMask self=(UnityEngine.AvatarMask)checkSelf(l); pushValue(l,true); pushValue(l,self.transformCount); return 2; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [SLua.MonoPInvokeCallbackAttribute(typeof(LuaCSFunction))] [UnityEngine.Scripting.Preserve] static public int set_transformCount(IntPtr l) { try { #if DEBUG var method = System.Reflection.MethodBase.GetCurrentMethod(); string methodName = GetMethodName(method); #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.BeginSample(methodName); #else Profiler.BeginSample(methodName); #endif #endif UnityEngine.AvatarMask self=(UnityEngine.AvatarMask)checkSelf(l); int v; checkType(l,2,out v); self.transformCount=v; pushValue(l,true); return 1; } catch(Exception e) { return error(l,e); } #if DEBUG finally { #if UNITY_5_5_OR_NEWER UnityEngine.Profiling.Profiler.EndSample(); #else Profiler.EndSample(); #endif } #endif } [UnityEngine.Scripting.Preserve] static public void reg(IntPtr l) { getTypeTable(l,"UnityEngine.AvatarMask"); addMember(l,GetHumanoidBodyPartActive); addMember(l,SetHumanoidBodyPartActive); addMember(l,AddTransformPath); addMember(l,RemoveTransformPath); addMember(l,GetTransformPath); addMember(l,SetTransformPath); addMember(l,GetTransformActive); addMember(l,SetTransformActive); addMember(l,"transformCount",get_transformCount,set_transformCount,true); createTypeMetatable(l,constructor, typeof(UnityEngine.AvatarMask),typeof(UnityEngine.Object)); } }
25.909953
96
0.719316
[ "BSD-3-Clause" ]
HugoFang/LuaProfiler
SLua/Assets/Slua/LuaObject/Unity/Lua_UnityEngine_AvatarMask.cs
10,936
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Runtime.InteropServices; using ApprovalUtilities.Utilities; namespace ApprovalTests.Utilities { public static class ParentProcessUtils { public static Process GetParentProcess(Process currentProcess) { return currentProcess.ParentProcess(); } public static IEnumerable<Process> CurrentProcessWithAncestors() { return GetSelfAndAncestors(Process.GetCurrentProcess()); } public static IEnumerable<Process> GetSelfAndAncestors(Process self) { var processIds = new HashSet<int>(); var process = self; while (process != null) { yield return process; if (processIds.Contains(process.Id)) { // loop detected (parent id have been re-allocated to a child process!) yield break; } processIds.Add(process.Id); process = process.ParentProcess(); } } private static Process ParentProcess(this Process process) { if (OsUtils.IsUnixOs()) { return null; } var parentPid = 0; var processPid = process.Id; const uint TH32_CS_SNAPPROCESS = 2; // Take snapshot of processes var hSnapshot = CreateToolhelp32Snapshot(TH32_CS_SNAPPROCESS, 0); if (hSnapshot == IntPtr.Zero) { return null; } var procInfo = new PROCESSENTRY32 {dwSize = (uint) Marshal.SizeOf(typeof (PROCESSENTRY32))}; // Read first if (Process32First(hSnapshot, ref procInfo) == false) { return null; } // Loop through the snapshot do { // If it's me, then ask for my parent. if (processPid == procInfo.th32ProcessID) { parentPid = (int) procInfo.th32ParentProcessID; } } while (parentPid == 0 && Process32Next(hSnapshot, ref procInfo)); // Read next if (parentPid <= 0) { return null; } try { return Process.GetProcessById(parentPid); } catch (ArgumentException) { //Process with an Id of X is not running return null; } } [DllImport("kernel32.dll", SetLastError = true)] private static extern IntPtr CreateToolhelp32Snapshot(uint dwFlags, uint th32ProcessId); [DllImport("kernel32.dll")] private static extern bool Process32First(IntPtr hSnapshot, ref PROCESSENTRY32 lppe); [DllImport("kernel32.dll")] private static extern bool Process32Next(IntPtr hSnapshot, ref PROCESSENTRY32 lppe); [StructLayout(LayoutKind.Sequential)] private struct PROCESSENTRY32 { public uint dwSize; public uint cntUsage; public uint th32ProcessID; public IntPtr th32DefaultHeapID; public uint th32ModuleID; public uint cntThreads; public uint th32ParentProcessID; public int pcPriClassBase; public uint dwFlags; [MarshalAs(UnmanagedType.ByValTStr, SizeConst = 260)] public string szExeFile; }; } }
31.483051
105
0.528668
[ "Apache-2.0" ]
RasheR666/ApprovalTests.Net
ApprovalTests/Utilities/ParentProcessUtils.cs
3,600
C#
using Foundation; using UIKit; namespace AnimationGroupSample { // The UIApplicationDelegate for the application. This class is responsible for launching the // User Interface of the application, as well as listening (and optionally responding) to application events from iOS. [Register ("AppDelegate")] public class AppDelegate : UIApplicationDelegate { // class-level declarations public override UIWindow Window { get; set; } public override bool FinishedLaunching (UIApplication application, NSDictionary launchOptions) { // Override point for customization after application launch. // If not required for your application you can safely delete this method return true; } public override void OnResignActivation (UIApplication application) { // Invoked when the application is about to move from active to inactive state. // This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) // or when the user quits the application and it begins the transition to the background state. // Games should use this method to pause the game. } public override void DidEnterBackground (UIApplication application) { // Use this method to release shared resources, save user data, invalidate timers and store the application state. // If your application supports background exection this method is called instead of WillTerminate when the user quits. } public override void WillEnterForeground (UIApplication application) { // Called as part of the transiton from background to active state. // Here you can undo many of the changes made on entering the background. } public override void OnActivated (UIApplication application) { // Restart any tasks that were paused (or not yet started) while the application was inactive. // If the application was previously in the background, optionally refresh the user interface. } public override void WillTerminate (UIApplication application) { // Called when the application is about to terminate. Save data, if needed. See also DidEnterBackground. } } }
35.833333
122
0.76186
[ "Apache-2.0" ]
Pkirugu/xamarin-recipes
ios/animation/coreanimation/create_an_animation_group/animationGroupSample/AppDelegate.cs
2,152
C#
//------------------------------------------------------------------------------ // <auto-generated> // O código foi gerado por uma ferramenta. // Versão de Tempo de Execução:4.0.30319.42000 // // As alterações ao arquivo poderão causar comportamento incorreto e serão perdidas se // o código for gerado novamente. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("DesignPatternsTutorialTest")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("DesignPatternsTutorialTest")] [assembly: System.Reflection.AssemblyTitleAttribute("DesignPatternsTutorialTest")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Gerado pela classe WriteCodeFragment do MSBuild.
44.333333
90
0.671992
[ "MIT" ]
xanwerneck/design-pattern-tutorial
DesignPatternsTutorialTest/obj/Debug/netcoreapp2.1/DesignPatternsTutorialTest.AssemblyInfo.cs
1,073
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; namespace Microsoft.EntityFrameworkCore.Query.Internal { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public sealed class SingleQueryResultCoordinator { /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public SingleQueryResultCoordinator() => ResultContext = new ResultContext(); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public ResultContext ResultContext { get; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public bool ResultReady { get; set; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public bool? HasNext { get; set; } /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public IList<SingleQueryCollectionContext?> Collections { get; } = new List<SingleQueryCollectionContext?>(); /// <summary> /// This is an internal API that supports the Entity Framework Core infrastructure and not subject to /// the same compatibility standards as public APIs. It may be changed or removed without notice in /// any release. You should only use it directly in your code with extreme caution and knowing that /// doing so can result in application failures when updating to a new Entity Framework Core release. /// </summary> public void SetSingleQueryCollectionContext( int collectionId, SingleQueryCollectionContext singleQueryCollectionContext) { while (Collections.Count <= collectionId) { Collections.Add(null); } Collections[collectionId] = singleQueryCollectionContext; } } }
59.342105
117
0.674058
[ "Apache-2.0" ]
0x0309/efcore
src/EFCore.Relational/Query/Internal/SingleQueryResultCoordinator.cs
4,510
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNextGen.Cdn.V20200331.Inputs { /// <summary> /// Defines the parameters for RequestUri match conditions /// </summary> public sealed class RequestUriMatchConditionParametersArgs : Pulumi.ResourceArgs { [Input("matchValues")] private InputList<string>? _matchValues; /// <summary> /// The match value for the condition of the delivery rule /// </summary> public InputList<string> MatchValues { get => _matchValues ?? (_matchValues = new InputList<string>()); set => _matchValues = value; } /// <summary> /// Describes if this is negate condition or not /// </summary> [Input("negateCondition")] public Input<bool>? NegateCondition { get; set; } [Input("odataType", required: true)] public Input<string> OdataType { get; set; } = null!; /// <summary> /// Describes operator to be matched /// </summary> [Input("operator", required: true)] public Input<string> Operator { get; set; } = null!; [Input("transforms")] private InputList<string>? _transforms; /// <summary> /// List of transforms /// </summary> public InputList<string> Transforms { get => _transforms ?? (_transforms = new InputList<string>()); set => _transforms = value; } public RequestUriMatchConditionParametersArgs() { } } }
29.677419
84
0.596196
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Cdn/V20200331/Inputs/RequestUriMatchConditionParametersArgs.cs
1,840
C#
using System; using System.Linq; using System.Windows; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Threading; using MouseEventArgs = System.Windows.Input.MouseEventArgs; namespace Captura { public partial class NotificationStack { static readonly TimeSpan TimeoutToHide = TimeSpan.FromSeconds(5); DateTime _lastMouseMoveTime; readonly DispatcherTimer _timer; public NotificationStack() { InitializeComponent(); _timer = new DispatcherTimer { Interval = TimeSpan.FromSeconds(1) }; _timer.Tick += TimerOnTick; _timer.Start(); } void TimerOnTick(object Sender, EventArgs Args) { var now = DateTime.Now; var elapsed = now - _lastMouseMoveTime; var unfinished = ItemsControl.Items .OfType<NotificationBalloon>() .Any(M => !M.Notification.Finished); if (unfinished) { _lastMouseMoveTime = now; } if (elapsed < TimeoutToHide) return; if (!unfinished) { OnClose(); } } public void Hide() { BeginAnimation(OpacityProperty, new DoubleAnimation(0, new Duration(TimeSpan.FromMilliseconds(100)))); if (_timer.IsEnabled) _timer.Stop(); } public void Show() { _lastMouseMoveTime = DateTime.Now; BeginAnimation(OpacityProperty, new DoubleAnimation(1, new Duration(TimeSpan.FromMilliseconds(300)))); if (!_timer.IsEnabled) _timer.Start(); } void OnClose() { Hide(); var copy = ItemsControl.Items.OfType<FrameworkElement>().ToArray(); foreach (var frameworkElement in copy) { Remove(frameworkElement); } } void CloseButton_Click(object Sender, RoutedEventArgs E) => OnClose(); /// <summary> /// Slides out element while decreasing opacity, then decreases height, then removes. /// </summary> void Remove(FrameworkElement Element) { var transform = new TranslateTransform(); Element.RenderTransform = transform; var translateAnim = new DoubleAnimation(500, new Duration(TimeSpan.FromMilliseconds(200))); var opactityAnim = new DoubleAnimation(0, new Duration(TimeSpan.FromMilliseconds(200))); var heightAnim = new DoubleAnimation(Element.ActualHeight, 0, new Duration(TimeSpan.FromMilliseconds(200))); heightAnim.Completed += (S, E) => { ItemsControl.Items.Remove(Element); if (ItemsControl.Items.Count == 0) { Hide(); } }; opactityAnim.Completed += (S, E) => Element.BeginAnimation(HeightProperty, heightAnim); transform.BeginAnimation(TranslateTransform.XProperty, translateAnim); Element.BeginAnimation(OpacityProperty, opactityAnim); } const int MaxItems = 5; public void Add(FrameworkElement Element) { if (Element is IRemoveRequester removeRequester) { removeRequester.RemoveRequested += () => Remove(Element); } if (Element is ScreenShotBalloon ssBalloon) ssBalloon.Expander.IsExpanded = true; foreach (var item in ItemsControl.Items) { if (item is ScreenShotBalloon screenShotBalloon) { screenShotBalloon.Expander.IsExpanded = false; } } ItemsControl.Items.Insert(0, Element); if (ItemsControl.Items.Count > MaxItems) { var itemsToRemove = ItemsControl.Items .OfType<FrameworkElement>() .Skip(MaxItems) .ToArray(); foreach (var frameworkElement in itemsToRemove) { if (frameworkElement is NotificationBalloon progressBalloon && !progressBalloon.Notification.Finished) continue; Remove(frameworkElement); } } } void NotificationStack_OnMouseMove(object Sender, MouseEventArgs E) { if (ItemsControl.Items.Count == 0) return; _lastMouseMoveTime = DateTime.Now; Show(); } } }
28.981707
122
0.544919
[ "MIT" ]
121986645/Captura
src/Captura/Controls/NotificationStack.xaml.cs
4,755
C#
/* * AUTHOR: Suparno Deb * DATE LAST MODIFIED: 09/12/2020 * FILE NAME: LocVisits.xaml.cs * PURPOSE: Handles events in response to the user's interaction with window 'LocVisits' * LAYER: Presentation */ using System; using System.Windows; using System.Windows.Controls; namespace OOSD { /// <summary> /// Interaction logic for LocVisits.xaml /// </summary> public partial class LocVisits : Window { public LocVisits() { InitializeComponent(); // Lists all the registered location objects the locList listbox foreach (Location location in DataAccess.listOfLocations) { locList.Items.Add(location); } } // The 'Go Back' button directs the user back to window 'Database' private void goBackBtn_Click(object sender, RoutedEventArgs e) { Database db = new Database(); db.Show(); this.Close(); } private void locList_SelectionChanged(object sender, SelectionChangedEventArgs e) { } private void visitRecord_SelectionChanged(object sender, SelectionChangedEventArgs e) { } // Following events are triggered when the user clicks the 'Submit' button private void submitBtn_Click(object sender, RoutedEventArgs e) { // Error handling/validation check: if the text box are blank, an error message is triggered if ((string.IsNullOrWhiteSpace(date1.Text)) || (string.IsNullOrWhiteSpace(date2.Text))) { MessageBox.Show("Error! Please ensure that the date fields are correctly entered"); } else { // If validation check is passed, the following lines of code are executed try { // var dateOne of type DateTime is initialised to the value in date1 textbox DateTime dateOne = Convert.ToDateTime(date1.Text); // var dateTwo of type DateTime is initialised to the value in date2 textbox DateTime dateTwo = Convert.ToDateTime(date2.Text); // Error handling/validation check: checks to see if the range of date is valid. If date/time in date1 is after date/time in date2, then an error message is triggered if (dateOne.CompareTo(dateTwo) > 0) { MessageBox.Show("Error! Incorrect date range."); } // Clears the visitRecord listbox after clicking 'Submit' button preventing from unwanted items piling up in that listbox visitRecord.Items.Clear(); // Iterates through the listOfVisits list foreach (Visit visitRec in DataAccess.listOfVisits) { // Error handling/validation check: checks to see if the location selected in locList listbox is equal to the location stored in the visit records if (locList.SelectedItem.ToString().Equals(visitRec.Location.ToString())) { // Error handling/validation check: checks to see that the date/time value in date1 textbox is equal to or less than the date stored in visit records if (dateOne.CompareTo(visitRec.Date) <= 0) { // Error handling/validation check: checks to see that the date/time value in date2 textbox is equal to or more than the date stored in visit records if (dateTwo.CompareTo(visitRec.Date) >= 0) { /* All the retrieved data is then listed in the visitRecord listbox in the format * Name: {personName} * Phone Number: {personPhoneNumber} * Date of Visit: {visitDate} */ visitRecord.Items.Add("ID: " + visitRec.Person.ID + Environment.NewLine + "Phone Number: " + visitRec.Person.PhoneNumber + Environment.NewLine + "Date of Visit: " + visitRec.Date); } } } } } catch { // Error handling/validation check: in the event an unexpected error is raised, the following message is triggered preventing the program from crashing MessageBox.Show("Error! Please ensure all fields are correctly entered/selected"); } } } } }
45.220183
186
0.540272
[ "Apache-2.0" ]
SuparnoD/Track-Trace
OOSD/LocVisits.xaml.cs
4,931
C#
using System.Collections.Generic; using Essensoft.AspNetCore.Payment.Alipay.Response; namespace Essensoft.AspNetCore.Payment.Alipay.Request { /// <summary> /// ssdata.dataservice.risk.antifraud.verify /// </summary> public class SsdataDataserviceRiskAntifraudVerifyRequest : IAlipayRequest<SsdataDataserviceRiskAntifraudVerifyResponse> { /// <summary> /// 蚁盾欺诈信息验证 /// </summary> public string BizContent { get; set; } #region IAlipayRequest Members private bool needEncrypt = false; private string apiVersion = "1.0"; private string terminalType; private string terminalInfo; private string prodCode; private string notifyUrl; private string returnUrl; private AlipayObject bizModel; public void SetNeedEncrypt(bool needEncrypt) { this.needEncrypt = needEncrypt; } public bool GetNeedEncrypt() { return needEncrypt; } public void SetNotifyUrl(string notifyUrl) { this.notifyUrl = notifyUrl; } public string GetNotifyUrl() { return notifyUrl; } public void SetReturnUrl(string returnUrl) { this.returnUrl = returnUrl; } public string GetReturnUrl() { return returnUrl; } public void SetTerminalType(string terminalType) { this.terminalType = terminalType; } public string GetTerminalType() { return terminalType; } public void SetTerminalInfo(string terminalInfo) { this.terminalInfo = terminalInfo; } public string GetTerminalInfo() { return terminalInfo; } public void SetProdCode(string prodCode) { this.prodCode = prodCode; } public string GetProdCode() { return prodCode; } public string GetApiName() { return "ssdata.dataservice.risk.antifraud.verify"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
22.951613
123
0.552706
[ "MIT" ]
gebiWangshushu/payment
src/Essensoft.AspNetCore.Payment.Alipay/Request/SsdataDataserviceRiskAntifraudVerifyRequest.cs
2,864
C#
using System.Linq; using System.Threading.Tasks; using Abp.Configuration; using Abp.Zero.Configuration; using Afonsoft.Ranking.Authorization.Users; using Shouldly; using Xunit; namespace Afonsoft.Ranking.Tests.Authorization.Users { public class UserManager_Tests : UserAppServiceTestBase { private readonly ISettingManager _settingManager; private readonly UserManager _userManager; public UserManager_Tests() { _settingManager = Resolve<ISettingManager>(); _userManager = Resolve<UserManager>(); LoginAsDefaultTenantAdmin(); } [Fact] public async Task Should_Create_User_With_Random_Password_For_Tenant() { await _settingManager.ChangeSettingForApplicationAsync(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireUppercase, "true"); await _settingManager.ChangeSettingForApplicationAsync(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequireNonAlphanumeric, "true"); await _settingManager.ChangeSettingForApplicationAsync(AbpZeroSettingNames.UserManagement.PasswordComplexity.RequiredLength, "25"); var randomPassword = await _userManager.CreateRandomPassword(); randomPassword.Length.ShouldBeGreaterThanOrEqualTo(25); randomPassword.Any(char.IsUpper).ShouldBeTrue(); randomPassword.Any(char.IsLetterOrDigit).ShouldBeTrue(); } } }
37.461538
153
0.735113
[ "MIT" ]
afonsoft/Ranking
test/Afonsoft.Ranking.Tests/Authorization/Users/UserManager_Tests.cs
1,463
C#
namespace WebAssembly.Instructions { /// <summary> /// Zero-replicating (logical) shift right. /// </summary> public class Int32ShiftRightSigned : ValueTwoToOneInstruction { /// <summary> /// Always <see cref="OpCode.Int32ShiftRightSigned"/>. /// </summary> public sealed override OpCode OpCode => OpCode.Int32ShiftRightSigned; private protected sealed override WebAssemblyValueType ValueType => WebAssemblyValueType.Int32; private protected sealed override System.Reflection.Emit.OpCode EmittedOpCode => System.Reflection.Emit.OpCodes.Shr; /// <summary> /// Creates a new <see cref="Int32ShiftRightSigned"/> instance. /// </summary> public Int32ShiftRightSigned() { } } }
32.32
103
0.641089
[ "Apache-2.0" ]
Astn/dotnet-webassembly
WebAssembly/Instructions/Int32ShiftRightSigned.cs
808
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.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Aws.Waf { /// <summary> /// Provides a WAF Regex Pattern Set Resource /// /// &gt; This content is derived from https://github.com/terraform-providers/terraform-provider-aws/blob/master/website/docs/r/waf_regex_pattern_set.html.markdown. /// </summary> public partial class RegexPatternSet : Pulumi.CustomResource { /// <summary> /// Amazon Resource Name (ARN) /// </summary> [Output("arn")] public Output<string> Arn { get; private set; } = null!; /// <summary> /// The name or description of the Regex Pattern Set. /// </summary> [Output("name")] public Output<string> Name { get; private set; } = null!; /// <summary> /// A list of regular expression (regex) patterns that you want AWS WAF to search for, such as `B[a@]dB[o0]t`. /// </summary> [Output("regexPatternStrings")] public Output<ImmutableArray<string>> RegexPatternStrings { get; private set; } = null!; /// <summary> /// Create a RegexPatternSet 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 RegexPatternSet(string name, RegexPatternSetArgs? args = null, CustomResourceOptions? options = null) : base("aws:waf/regexPatternSet:RegexPatternSet", name, args ?? ResourceArgs.Empty, MakeResourceOptions(options, "")) { } private RegexPatternSet(string name, Input<string> id, RegexPatternSetState? state = null, CustomResourceOptions? options = null) : base("aws:waf/regexPatternSet:RegexPatternSet", 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 RegexPatternSet 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 RegexPatternSet Get(string name, Input<string> id, RegexPatternSetState? state = null, CustomResourceOptions? options = null) { return new RegexPatternSet(name, id, state, options); } } public sealed class RegexPatternSetArgs : Pulumi.ResourceArgs { /// <summary> /// The name or description of the Regex Pattern Set. /// </summary> [Input("name")] public Input<string>? Name { get; set; } [Input("regexPatternStrings")] private InputList<string>? _regexPatternStrings; /// <summary> /// A list of regular expression (regex) patterns that you want AWS WAF to search for, such as `B[a@]dB[o0]t`. /// </summary> public InputList<string> RegexPatternStrings { get => _regexPatternStrings ?? (_regexPatternStrings = new InputList<string>()); set => _regexPatternStrings = value; } public RegexPatternSetArgs() { } } public sealed class RegexPatternSetState : Pulumi.ResourceArgs { /// <summary> /// Amazon Resource Name (ARN) /// </summary> [Input("arn")] public Input<string>? Arn { get; set; } /// <summary> /// The name or description of the Regex Pattern Set. /// </summary> [Input("name")] public Input<string>? Name { get; set; } [Input("regexPatternStrings")] private InputList<string>? _regexPatternStrings; /// <summary> /// A list of regular expression (regex) patterns that you want AWS WAF to search for, such as `B[a@]dB[o0]t`. /// </summary> public InputList<string> RegexPatternStrings { get => _regexPatternStrings ?? (_regexPatternStrings = new InputList<string>()); set => _regexPatternStrings = value; } public RegexPatternSetState() { } } }
39.382353
167
0.612024
[ "ECL-2.0", "Apache-2.0" ]
dixler/pulumi-aws
sdk/dotnet/Waf/RegexPatternSet.cs
5,356
C#
using FullInspector.Internal; namespace FullInspector { public partial class tk<T, TContext> { /// <summary> /// The control will be drawn with a read-only UI if the predicate returns true. /// </summary> public class ReadOnlyIf : ConditionalStyle { public ReadOnlyIf(Value<bool> isReadOnly) : base(isReadOnly.GetCurrentValue, (obj, context) => { fiLateBindings.EditorGUI.BeginDisabledGroup(true); return null; }, (obj, context, state) => { fiLateBindings.EditorGUI.EndDisabledGroup(); }) { } public ReadOnlyIf(Value<bool>.Generator isReadOnly) : this(Val(isReadOnly)) { } public ReadOnlyIf(Value<bool>.GeneratorNoContext isReadOnly) : this(Val(isReadOnly)) { } } } }
34.172414
88
0.507568
[ "MIT" ]
bakiya-sefer/bakiya-sefer
Assets/FullInspector2/Modules/tkControl/Controls/tkReadOnlyIf.cs
993
C#
namespace p07.LegoBlocks { using System; using System.Linq; public class StartUp { public static void Main() { int rows = int.Parse(Console.ReadLine()); int[][] array1 = GetArray(rows); int[][] array2 = GetArray(rows); array2 = GetReversedArray(array2); bool arraysFit = true; int cellsCount = array1[0].Length + array2[0].Length; for (int row = 1; row < rows; row++) { int rowLength = array1[row].Length + array2[row].Length; if (rowLength != array1[0].Length + array2[0].Length) { arraysFit = false; } cellsCount += rowLength; } if (arraysFit) { for (int row = 0; row < rows; row++) { Console.WriteLine("[{0}]", string.Join(", ", string.Join(", ", array1[row]), string.Join(", ", array2[row]))); } } else { Console.WriteLine("The total number of cells is: {0}", cellsCount); } } public static int[][] GetReversedArray(int[][] array) { for (int row = 0; row < array.Length; row++) { array[row] = array[row].Reverse().ToArray(); } return array; } public static int[][] GetArray(int rows) { int[][] array = new int[rows][]; for (int row = 0; row < rows; row++) { array[row] = Console.ReadLine() .Split(new char[] { ' ' }, StringSplitOptions.RemoveEmptyEntries) .Select(int.Parse) .ToArray(); } return array; } public static void PrintJaggedArray(int[][] array) { for (int row = 0; row < array.Length; row++) { Console.WriteLine(string.Join(" ", array[row])); } } } }
27.329114
85
0.418249
[ "MIT" ]
GitHarr/SoftUni
Homework/C#Fundamentals/C#Advanced/2.MultidimensionalArrays/Exercises/p07.LegoBlocks/StartUp.cs
2,161
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.Threading.Tasks; using Microsoft.CodeAnalysis.CodeRefactorings; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.CodeRefactorings.InlineTemporary; using Microsoft.CodeAnalysis.CSharp.Shared.Extensions; using Microsoft.CodeAnalysis.CSharp.Test.Utilities; using Microsoft.CodeAnalysis.Test.Utilities; using Roslyn.Test.Utilities; using Xunit; namespace Microsoft.CodeAnalysis.Editor.CSharp.UnitTests.CodeRefactorings.InlineTemporary { public class InlineTemporaryTests : AbstractCSharpCodeActionTest { protected override CodeRefactoringProvider CreateCodeRefactoringProvider(Workspace workspace, TestParameters parameters) => new InlineTemporaryCodeRefactoringProvider(); private async Task TestFixOneAsync(string initial, string expected) => await TestInRegularAndScript1Async(GetTreeText(initial), GetTreeText(expected)); private string GetTreeText(string initial) { return @"class C { void F() " + initial + @" }"; } private SyntaxNode GetNodeToFix(dynamic initialRoot, int declaratorIndex) => initialRoot.Members[0].Members[0].Body.Statements[0].Declaration.Variables[declaratorIndex]; private SyntaxNode GetFixedNode(dynamic fixedRoot) => fixedRoot.Members[0].Members[0].BodyOpt; [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NotWithNoInitializer1() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int [||]x; System.Console.WriteLine(x); }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NotWithNoInitializer2() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int [||]x = ; System.Console.WriteLine(x); }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NotOnSecondWithNoInitializer() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int x = 42, [||]y; System.Console.WriteLine(y); }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NotOnField() { await TestMissingInRegularAndScriptAsync( @"class C { int [||]x = 42; void M() { System.Console.WriteLine(x); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WithRefInitializer1() { await TestMissingInRegularAndScriptAsync( @"class C { ref int M() { int[] arr = new[] { 1, 2, 3 }; ref int [||]x = ref arr[2]; return ref x; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task SingleStatement() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int [||]x = 27; }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task MultipleDeclarators_First() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int [||]x = 0, y = 1, z = 2; }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task MultipleDeclarators_Second() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int x = 0, [||]y = 1, z = 2; }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task MultipleDeclarators_Last() => await TestMissingInRegularAndScriptAsync(GetTreeText(@"{ int x = 0, y = 1, [||]z = 2; }")); [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping1() { await TestFixOneAsync( @"{ int [||]x = 0; Console.WriteLine(x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping2() { await TestFixOneAsync( @"{ int [||]@x = 0; Console.WriteLine(x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping3() { await TestFixOneAsync( @"{ int [||]@x = 0; Console.WriteLine(@x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping4() { await TestFixOneAsync( @"{ int [||]x = 0; Console.WriteLine(@x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Escaping5() { var code = @" using System.Linq; class C { static void Main() { var @where[||] = 0; var q = from e in """" let a = new { @where } select a; } }"; var expected = @" using System.Linq; class C { static void Main() { var q = from e in """" let a = new { @where = 0 } select a; } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Call() { var code = @" using System; class C { public void M() { int [||]x = 1 + 1; x.ToString(); } }"; var expected = @" using System; class C { public void M() { (1 + 1).ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_NoChange() { var code = @" using System; class C { public void M() { double [||]x = 3; x.ToString(); } }"; var expected = @" using System; class C { public void M() { ((double)3).ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_NoConversion() { await TestFixOneAsync( @"{ int [||]x = 3; x.ToString(); }", @"{ 3.ToString(); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_DifferentOverload() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { double [||]x = 3; Console.WriteLine(x); } }", @" using System; class C { void M() { Console.WriteLine((double)3); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_DifferentMethod() { await TestInRegularAndScriptAsync( @" class Base { public void M(object o) { } } class Derived : Base { public void M(string s) { } } class C { void F() { Base [||]b = new Derived(); b.M(""hi""); } } ", @" class Base { public void M(object o) { } } class Derived : Base { public void M(string s) { } } class C { void F() { ((Base)new Derived()).M(""hi""); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Conversion_SameMethod() { await TestInRegularAndScriptAsync( @" class Base { public void M(int i) { } } class Derived : Base { public void M(string s) { } } class C { void F() { Base [||]b = new Derived(); b.M(3); } } ", @" class Base { public void M(int i) { } } class Derived : Base { public void M(string s) { } } class C { void F() { new Derived().M(3); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task NoCastOnVar() { await TestFixOneAsync( @"{ var [||]x = 0; Console.WriteLine(x); }", @"{ Console.WriteLine(0); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DoubleAssignment() { var code = @" class C { void M() { int [||]x = x = 1; int y = x; } }"; var expected = @" class C { void M() { int y = 1; } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestAnonymousType1() { await TestFixOneAsync( @"{ int [||]x = 42; var a = new { x }; }", @"{ var a = new { x = 42 }; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestParenthesizedAtReference_Case3() { await TestFixOneAsync( @"{ int [||]x = 1 + 1; int y = x * 2; }", @"{ int y = (1 + 1) * 2; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontBreakOverloadResolution_Case5() { var code = @" class C { void Goo(object o) { } void Goo(int i) { } void M() { object [||]x = 1 + 1; Goo(x); } }"; var expected = @" class C { void Goo(object o) { } void Goo(int i) { } void M() { Goo((object)(1 + 1)); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontTouchUnrelatedBlocks() { var code = @" class C { void M() { int [||]x = 1; { Unrelated(); } Goo(x); } }"; var expected = @" class C { void M() { { Unrelated(); } Goo(1); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestLambdaParenthesizeAndCast_Case7() { var code = @" class C { void M() { System.Func<int> [||]x = () => 1; int y = x(); } }"; var expected = @" class C { void M() { int y = ((System.Func<int>)(() => 1))(); } }"; await TestInRegularAndScriptAsync(code, expected); } [WorkItem(538094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538094")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity1() { await TestInRegularAndScriptAsync( @" class C { void F(object a, object b) { int x = 2; bool [||]y = x > (f); F(x < x, y); } int f = 0; }", @" class C { void F(object a, object b) { int x = 2; F(x < x, (x > (f))); } int f = 0; }"); } [WorkItem(538094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538094"), WorkItem(541462, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541462")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity2() { await TestInRegularAndScriptAsync( @" class C { void F(object a, object b) { int x = 2; object [||]y = x > (f); F(x < x, y); } int f = 0; }", @" class C { void F(object a, object b) { int x = 2; F(x < x, (x > (f))); } int f = 0; }"); } [WorkItem(538094, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538094")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity3() { await TestInRegularAndScriptAsync( @" class C { void F(object a, object b) { int x = 2; bool [||]y = x > (int)1; F(x < x, y); } int f = 0; }", @" class C { void F(object a, object b) { int x = 2; F(x < x, (x > (int)1)); } int f = 0; }"); } [WorkItem(544924, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544924")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity4() { await TestInRegularAndScriptAsync( @" class Program { static void Main() { int x = 2; int y[||] = (1+2); Bar(x < x, x > y); } static void Bar(object a, object b) { } }", @" class Program { static void Main() { int x = 2; Bar(x < x, (x > (1 + 2))); } static void Bar(object a, object b) { } }"); } [WorkItem(544613, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544613")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParseAmbiguity5() { await TestInRegularAndScriptAsync( @" class Program { static void Main() { int x = 2; int y[||] = (1 + 2); var z = new[] { x < x, x > y }; } }", @" class Program { static void Main() { int x = 2; var z = new[] { x < x, (x > (1 + 2)) }; } }"); } [WorkItem(538131, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538131")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestArrayInitializer() { await TestFixOneAsync( @"{ int[] [||]x = { 3, 4, 5 }; int a = Array.IndexOf(x, 3); }", @"{ int a = Array.IndexOf(new int[] { 3, 4, 5 }, 3); }"); } [WorkItem(545657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545657")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestArrayInitializer2() { var initial = @" class Program { static void Main() { int[] [||]x = { 3, 4, 5 }; System.Array a = x; } }"; var expected = @" class Program { static void Main() { System.Array a = new int[] { 3, 4, 5 }; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(545657, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545657")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestArrayInitializer3() { var initial = @" class Program { static void Main() { int[] [||]x = { 3, 4, 5 }; System.Array a = x; } }"; var expected = @" class Program { static void Main() { System.Array a = new int[] { 3, 4, 5 }; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_RefParameter1() { var initial = @"using System; class Program { void Main() { int [||]x = 0; Goo(ref x); Goo(x); } void Goo(int x) { } void Goo(ref int x) { } }"; var expected = @"using System; class Program { void Main() { int x = 0; Goo(ref {|Conflict:x|}); Goo(0); } void Goo(int x) { } void Goo(ref int x) { } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_RefParameter2() { var initial = @"using System; class Program { void Main() { int [||]x = 0; Goo(x, ref x); } void Goo(int x, ref int y) { } }"; var expected = @"using System; class Program { void Main() { int x = 0; Goo(0, ref {|Conflict:x|}); } void Goo(int x, ref int y) { } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i = 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} = 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AddAssignExpression1() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i += 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} += 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AddAssignExpression2() { var initial = @"using System; class C { static int x; static void M() { int [||]x = (x = 0) + (x += 1); int y = x; } }"; var expected = @"using System; class C { static int x; static void M() { int x = ({|Conflict:x|} = 0) + ({|Conflict:x|} += 1); int y = 0 + ({|Conflict:x|} += 1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_SubtractAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i -= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} -= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_MultiplyAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i *= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} *= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_DivideAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i /= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} /= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_ModuloAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i %= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} %= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AndAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i &= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} &= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_OrAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i |= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} |= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_ExclusiveOrAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i ^= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} ^= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_LeftShiftAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i <<= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} <<= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_RightShiftAssignExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i >>= 2; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|} >>= 2; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_PostIncrementExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i++; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|}++; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_PreIncrementExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; ++i; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; ++{|Conflict:i|}; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_PostDecrementExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; i--; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; {|Conflict:i|}--; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_PreDecrementExpression() { var initial = @"using System; class Program { void Main() { int [||]i = 1; --i; Console.WriteLine(i); } }"; var expected = @"using System; class Program { void Main() { int i = 1; --{|Conflict:i|}; Console.WriteLine(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_AddressOfExpression() { var initial = @" class C { unsafe void M() { int x = 0; var y[||] = &x; var z = &y; } }"; var expected = @" class C { unsafe void M() { int x = 0; var y = &x; var z = &{|Conflict:y|}; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(545342, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545342")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConflict_UsedBeforeDeclaration() { var initial = @"class Program { static void Main(string[] args) { var x = y; var y[||] = 45; } }"; var expected = @"class Program { static void Main(string[] args) { var x = {|Conflict:y|}; var y = 45; } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Preprocessor1() { await TestFixOneAsync(@" { int [||]x = 1, #if true y, #endif z; int a = x; }", @" { int #if true y, #endif z; int a = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Preprocessor2() { await TestFixOneAsync(@" { int y, #if true [||]x = 1, #endif z; int a = x; }", @" { int y, #if true #endif z; int a = 1; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Preprocessor3() { await TestFixOneAsync(@" { int y, #if true z, #endif [||]x = 1; int a = x; }", @" { int y, #if true z #endif ; int a = 1; }"); } [WorkItem(540164, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540164")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TriviaOnArrayInitializer() { var initial = @"class C { void M() { int[] [||]a = /**/{ 1 }; Goo(a); } }"; var expected = @"class C { void M() { Goo(new int[]/**/{ 1 }); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540156")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ProperlyFormatWhenRemovingDeclarator1() { var initial = @"class C { void M() { int [||]i = 1, j = 2, k = 3; System.Console.Write(i); } }"; var expected = @"class C { void M() { int j = 2, k = 3; System.Console.Write(1); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540156")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ProperlyFormatWhenRemovingDeclarator2() { var initial = @"class C { void M() { int i = 1, [||]j = 2, k = 3; System.Console.Write(j); } }"; var expected = @"class C { void M() { int i = 1, k = 3; System.Console.Write(2); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540156, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540156")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ProperlyFormatWhenRemovingDeclarator3() { var initial = @"class C { void M() { int i = 1, j = 2, [||]k = 3; System.Console.Write(k); } }"; var expected = @"class C { void M() { int i = 1, j = 2; System.Console.Write(3); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540186, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540186")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ProperlyFormatAnonymousTypeMember() { var initial = @"class C { void M() { var [||]x = 123; var y = new { x }; } }"; var expected = @"class C { void M() { var y = new { x = 123 }; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(6356, "DevDiv_Projects/Roslyn")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineToAnonymousTypeProperty() { var initial = @"class C { void M() { var [||]x = 123; var y = new { x = x }; } }"; var expected = @"class C { void M() { var y = new { x = 123 }; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(528075, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/528075")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineIntoDelegateInvocation() { var initial = @"using System; class Program { static void Main(string[] args) { Action<string[]> [||]del = Main; del(null); } }"; var expected = @"using System; class Program { static void Main(string[] args) { ((Action<string[]>)Main)(null); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(541341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541341")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineAnonymousMethodIntoNullCoalescingExpression() { var initial = @"using System; class Program { static void Main() { Action [||]x = delegate { }; Action y = x ?? null; } }"; var expected = @"using System; class Program { static void Main() { Action y = (Action)delegate { } ?? null; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(541341, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541341")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineLambdaIntoNullCoalescingExpression() { var initial = @"using System; class Program { static void Main() { Action [||]x = () => { }; Action y = x ?? null; } }"; var expected = @"using System; class Program { static void Main() { Action y = (Action)(() => { }) ?? null; } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation1() { var initial = @"using System; class A { static void Main() { long x[||] = 1; object z = x; Console.WriteLine((long)z); } }"; var expected = @"using System; class A { static void Main() { object z = (long)1; Console.WriteLine((long)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation2() { var initial = @"using System; class A { static void Main() { int y = 1; long x[||] = y; object z = x; Console.WriteLine((long)z); } }"; var expected = @"using System; class A { static void Main() { int y = 1; object z = (long)y; Console.WriteLine((long)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation3() { var initial = @"using System; class A { static void Main() { byte x[||] = 1; object z = x; Console.WriteLine((byte)z); } }"; var expected = @"using System; class A { static void Main() { object z = (byte)1; Console.WriteLine((byte)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation4() { var initial = @"using System; class A { static void Main() { sbyte x[||] = 1; object z = x; Console.WriteLine((sbyte)z); } }"; var expected = @"using System; class A { static void Main() { object z = (sbyte)1; Console.WriteLine((sbyte)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(538079, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/538079")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForBoxingOperation5() { var initial = @"using System; class A { static void Main() { short x[||] = 1; object z = x; Console.WriteLine((short)z); } }"; var expected = @"using System; class A { static void Main() { object z = (short)1; Console.WriteLine((short)z); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(540278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestLeadingTrivia() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { // Leading int [||]i = 10; //print Console.Write(i); } }", @"class Program { static void Main(string[] args) { // Leading //print Console.Write(10); } }"); } [WorkItem(540278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestLeadingAndTrailingTrivia() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { // Leading int [||]i = 10; // Trailing //print Console.Write(i); } }", @"class Program { static void Main(string[] args) { // Leading // Trailing //print Console.Write(10); } }"); } [WorkItem(540278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestTrailingTrivia() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { int [||]i = 10; // Trailing //print Console.Write(i); } }", @"class Program { static void Main(string[] args) { // Trailing //print Console.Write(10); } }"); } [WorkItem(540278, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540278")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestPreprocessor() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { #if true int [||]i = 10; //print Console.Write(i); #endif } }", @"class Program { static void Main(string[] args) { #if true //print Console.Write(10); #endif } }"); } [WorkItem(540277, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/540277")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestFormatting() { await TestInRegularAndScriptAsync( @"class Program { static void Main(string[] args) { int [||]i = 5; int j = 110; Console.Write(i + j); } }", @"class Program { static void Main(string[] args) { int j = 110; Console.Write(5 + j); } }"); } [WorkItem(541694, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/541694")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestSwitchSection() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { switch (10) { default: int i[||] = 10; Console.WriteLine(i); break; } } }", @"using System; class C { void M() { switch (10) { default: Console.WriteLine(10); break; } } }"); } [WorkItem(542647, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542647")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task UnparenthesizeExpressionIfNeeded1() { await TestInRegularAndScriptAsync( @" using System; class C { static Action X; static void M() { var [||]y = (X); y(); } } ", @" using System; class C { static Action X; static void M() { X(); } } "); } [WorkItem(545619, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545619")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task UnparenthesizeExpressionIfNeeded2() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { Action x = Console.WriteLine; Action y[||] = x; y(); } } ", @" using System; class Program { static void Main() { Action x = Console.WriteLine; x(); } } "); } [WorkItem(542656, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542656")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeIfNecessary1() { await TestInRegularAndScriptAsync( @"using System; using System.Collections; using System.Linq; class A { static void Main() { var [||]q = from x in """" select x; if (q is IEnumerable) { } } }", @"using System; using System.Collections; using System.Linq; class A { static void Main() { if ((from x in """" select x) is IEnumerable) { } } }"); } [WorkItem(544626, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544626")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeIfNecessary2() { await TestInRegularAndScriptAsync( @" using System; class C { static void Main() { Action<string> f[||] = Goo<string>; Action<string> g = null; var h = f + g; } static void Goo<T>(T y) { } }", @" using System; class C { static void Main() { Action<string> g = null; var h = Goo + g; } static void Goo<T>(T y) { } }"); } [WorkItem(544415, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544415")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeAddressOf1() { await TestInRegularAndScriptAsync( @" using System; unsafe class C { static void M() { int x; int* p[||] = &x; var i = (Int32)p; } }", @" using System; unsafe class C { static void M() { int x; var i = (Int32)(&x); } }"); } [WorkItem(544922, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544922")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeAddressOf2() { await TestInRegularAndScriptAsync( @" using System; unsafe class C { static void M() { int x; int* p[||] = &x; var i = p->ToString(); } }", @" using System; unsafe class C { static void M() { int x; var i = (&x)->ToString(); } }"); } [WorkItem(544921, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544921")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizePointerIndirection1() { await TestInRegularAndScriptAsync( @" using System; unsafe class C { static void M() { int* x = null; int p[||] = *x; var i = (Int64)p; } }", @" using System; unsafe class C { static void M() { int* x = null; var i = (Int64)(*x); } }"); } [WorkItem(544614, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544614")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizePointerIndirection2() { await TestInRegularAndScriptAsync( @" using System; unsafe class C { static void M() { int** x = null; int* p[||] = *x; var i = p[1].ToString(); } }", @" using System; unsafe class C { static void M() { int** x = null; var i = (*x)[1].ToString(); } }"); } [WorkItem(544563, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544563")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontInlineStackAlloc() { await TestMissingInRegularAndScriptAsync( @"using System; unsafe class C { static void M() { int* values[||] = stackalloc int[20]; int* copy = values; int* p = &values[1]; int* q = &values[15]; } }"); } [WorkItem(543744, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/543744")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTempLambdaExpressionCastingError() { await TestInRegularAndScriptAsync( @"using System; class Program { static void Main(string[] args) { Func<int?,int?> [||]lam = (int? s) => { return s; }; Console.WriteLine(lam); } }", @"using System; class Program { static void Main(string[] args) { Console.WriteLine((Func<int?, int?>)((int? s) => { return s; })); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForNull() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { string [||]x = null; Console.WriteLine(x); } }", @" using System; class C { void M() { Console.WriteLine((string)null); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastIfNeeded1() { await TestInRegularAndScriptAsync( @" class C { void M() { long x[||] = 1; System.IComparable<long> y = x; } }", @" class C { void M() { System.IComparable<long> y = (long)1; } }"); } [WorkItem(545161, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545161")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastIfNeeded2() { await TestInRegularAndScriptAsync( @" using System; class C { static void Main() { Goo(x => { int [||]y = x[0]; x[1] = y; }); } static void Goo(Action<int[]> x) { } static void Goo(Action<string[]> x) { } }", @" using System; class C { static void Main() { Goo((Action<int[]>)(x => { x[1] = x[0]; })); } static void Goo(Action<int[]> x) { } static void Goo(Action<string[]> x) { } }"); } [WorkItem(544612, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544612")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineIntoBracketedList() { await TestInRegularAndScriptAsync( @" class C { void M() { var c = new C(); int x[||] = 1; c[x] = 2; } int this[object x] { set { } } }", @" class C { void M() { var c = new C(); c[1] = 2; } int this[object x] { set { } } }"); } [WorkItem(542648, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/542648")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ParenthesizeAfterCastIfNeeded() { await TestAsync( @" using System; enum E { } class Program { static void Main() { E x[||] = (global::E) -1; object y = x; } }", @" using System; enum E { } class Program { static void Main() { object y = (global::E)-1; } }", parseOptions: null); } [WorkItem(544635, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544635")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForEnumZeroIfBoxed() { await TestAsync( @" using System; class Program { static void M() { DayOfWeek x[||] = 0; object y = x; Console.WriteLine(y); } }", @" using System; class Program { static void M() { object y = (DayOfWeek)0; Console.WriteLine(y); } }", parseOptions: null); } [WorkItem(544636, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544636")] [WorkItem(554010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForMethodGroupIfNeeded1() { await TestAsync( @" using System; class Program { static void M() { Action a[||] = Console.WriteLine; Action b = a + Console.WriteLine; } }", @" using System; class Program { static void M() { Action b = (Action)Console.WriteLine + Console.WriteLine; } }", parseOptions: null); } [WorkItem(544978, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/544978")] [WorkItem(554010, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/554010")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForMethodGroupIfNeeded2() { await TestAsync( @" using System; class Program { static void Main() { Action a[||] = Console.WriteLine; object b = a; } }", @" using System; class Program { static void Main() { object b = (Action)Console.WriteLine; } }", parseOptions: null); } [WorkItem(545103, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545103")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontInsertCastForTypeThatNoLongerBindsToTheSameType() { await TestAsync( @" class A<T> { static T x; class B<U> { static void Goo() { var y[||] = x; var z = y; } } }", @" class A<T> { static T x; class B<U> { static void Goo() { var z = x; } } }", parseOptions: null); } [WorkItem(545170, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545170")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCorrectCastForDelegateCreationExpression() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { Predicate<object> x[||] = y => true; var z = new Func<string, bool>(x); } } ", @" using System; class Program { static void Main() { var z = new Func<string, bool>(y => true); } } "); } [WorkItem(545523, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545523")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontInsertCastForObjectCreationIfUnneeded() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { Exception e[||] = new ArgumentException(); Type b = e.GetType(); } } ", @" using System; class Program { static void Main() { Type b = new ArgumentException().GetType(); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontInsertCastInForeachIfUnneeded01() { await TestInRegularAndScriptAsync( @" using System; using System.Collections.Generic; class Program { static void Main() { IEnumerable<char> s[||] = ""abc""; foreach (var x in s) Console.WriteLine(x); } } ", @" using System; using System.Collections.Generic; class Program { static void Main() { foreach (var x in ""abc"") Console.WriteLine(x); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastInForeachIfNeeded01() { await TestInRegularAndScriptAsync( @" using System; using System.Collections; class Program { static void Main() { IEnumerable s[||] = ""abc""; foreach (object x in s) Console.WriteLine(x); } } ", @" using System; using System.Collections; class Program { static void Main() { foreach (object x in (IEnumerable)""abc"") Console.WriteLine(x); } } "); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastInForeachIfNeeded02() { await TestInRegularAndScriptAsync( @" using System; using System.Collections; class Program { static void Main() { IEnumerable s[||] = ""abc""; foreach (char x in s) Console.WriteLine(x); } } ", @" using System; using System.Collections; class Program { static void Main() { foreach (char x in (IEnumerable)""abc"") Console.WriteLine(x); } } "); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastToKeepGenericMethodInference() { await TestInRegularAndScriptAsync( @" using System; class C { static T Goo<T>(T x, T y) { return default(T); } static void M() { long [||]x = 1; IComparable<long> c = Goo(x, x); } } ", @" using System; class C { static T Goo<T>(T x, T y) { return default(T); } static void M() { IComparable<long> c = Goo(1, (long)1); } } "); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastForKeepImplicitArrayInference() { await TestInRegularAndScriptAsync( @" class C { static void M() { object x[||] = null; var a = new[] { x, x }; Goo(a); } static void Goo(object[] o) { } } ", @" class C { static void M() { var a = new[] { null, (object)null }; Goo(a); } static void Goo(object[] o) { } } "); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertASingleCastToNotBreakOverloadResolution() { await TestInRegularAndScriptAsync( @" class C { static void M() { long x[||] = 42; Goo(x, x); } static void Goo(int x, int y) { } static void Goo(long x, long y) { } }", @" class C { static void M() { Goo(42, (long)42); } static void Goo(int x, int y) { } static void Goo(long x, long y) { } }"); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertASingleCastToNotBreakOverloadResolutionInLambdas() { await TestInRegularAndScriptAsync( @" using System; class C { static void M() { long x[||] = 42; Goo(() => { return x; }, () => { return x; }); } static void Goo(Func<int> x, Func<int> y) { } static void Goo(Func<long> x, Func<long> y) { } }", @" using System; class C { static void M() { Goo(() => { return 42; }, (Func<long>)(() => { return 42; })); } static void Goo(Func<int> x, Func<int> y) { } static void Goo(Func<long> x, Func<long> y) { } }"); } [WorkItem(545601, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545601")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertASingleCastToNotBreakResolutionOfOperatorOverloads() { await TestInRegularAndScriptAsync( @" using System; class C { private int value; void M() { C x[||] = 42; Console.WriteLine(x + x); } public static int operator +(C x, C y) { return x.value + y.value; } public static implicit operator C(int l) { var c = new C(); c.value = l; return c; } static void Main() { new C().M(); } }", @" using System; class C { private int value; void M() { Console.WriteLine(42 + (C)42); } public static int operator +(C x, C y) { return x.value + y.value; } public static implicit operator C(int l) { var c = new C(); c.value = l; return c; } static void Main() { new C().M(); } }"); } [WorkItem(545561, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545561")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastToNotBreakOverloadResolutionInUncheckedContext() { await TestInRegularAndScriptAsync( @" using System; class X { static int Goo(Func<int?, byte> x, object y) { return 1; } static int Goo(Func<X, byte> x, string y) { return 2; } const int Value = 1000; static void Main() { var a[||] = Goo(X => (byte)X.Value, null); unchecked { Console.WriteLine(a); } } }", @" using System; class X { static int Goo(Func<int?, byte> x, object y) { return 1; } static int Goo(Func<X, byte> x, string y) { return 2; } const int Value = 1000; static void Main() { unchecked { Console.WriteLine(Goo(X => (byte)X.Value, (object)null)); } } }"); } [WorkItem(545564, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545564")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastToNotBreakOverloadResolutionInUnsafeContext() { await TestInRegularAndScriptAsync( @" using System; static class C { static int Outer(Action<int> x, object y) { return 1; } static int Outer(Action<string> x, string y) { return 2; } static void Inner(int x, int[] y) { } unsafe static void Inner(string x, int*[] y) { } static void Main() { var a[||] = Outer(x => Inner(x, null), null); unsafe { Console.WriteLine(a); } } }", @" using System; static class C { static int Outer(Action<int> x, object y) { return 1; } static int Outer(Action<string> x, string y) { return 2; } static void Inner(int x, int[] y) { } unsafe static void Inner(string x, int*[] y) { } static void Main() { unsafe { Console.WriteLine(Outer(x => Inner(x, null), (object)null)); } } }"); } [WorkItem(545783, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/545783")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InsertCastToNotBreakOverloadResolutionInNestedLambdas() { await TestInRegularAndScriptAsync( @" using System; class C { static void Goo(Action<object> a) { } static void Goo(Action<string> a) { } static void Main() { Goo(x => { string s[||] = x; var y = s; }); } }", @" using System; class C { static void Goo(Action<object> a) { } static void Goo(Action<string> a) { } static void Main() { Goo((Action<string>)(x => { var y = x; })); } }"); } [WorkItem(546069, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/546069")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestBrokenVariableDeclarator() { await TestMissingInRegularAndScriptAsync( @"class C { static void M() { int [||]a[10] = { 0, 0 }; System.Console.WriteLine(a); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion1() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { int [|x|] = 0; #line hidden Goo(x); #line default } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion2() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { int [|x|] = 0; Goo(x); #line hidden Goo(x); #line default } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion3() { await TestInRegularAndScriptAsync( @"#line default class Program { void Main() { int [|x|] = 0; Goo(x); #line hidden Goo(); #line default } }", @"#line default class Program { void Main() { Goo(0); #line hidden Goo(); #line default } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion4() { await TestInRegularAndScriptAsync( @"#line default class Program { void Main() { int [||]x = 0; Goo(x); #line hidden Goo(); #line default Goo(x); } }", @"#line default class Program { void Main() { Goo(0); #line hidden Goo(); #line default Goo(0); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestHiddenRegion5() { await TestMissingInRegularAndScriptAsync( @"class Program { void Main() { int [||]x = 0; Goo(x); #line hidden Goo(x); #line default Goo(x); } }"); } [WorkItem(530743, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/530743")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineFromLabeledStatement() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { label: int [||]x = 1; Console.WriteLine(); int y = x; } }", @" using System; class Program { static void Main() { label: Console.WriteLine(); int y = 1; } }"); } [WorkItem(529698, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529698")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineCompoundAssignmentIntoInitializer() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class Program { static void Main() { int x = 0; int y[||] = x += 1; var z = new List<int> { y }; } }", @" using System.Collections.Generic; class Program { static void Main() { int x = 0; var z = new List<int> { (x += 1) }; } }"); } [WorkItem(609497, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609497")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_609497() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class Program { static void Main() { IList<dynamic> x[||] = new List<object>(); IList<object> y = x; } }", @" using System.Collections.Generic; class Program { static void Main() { IList<object> y = new List<object>(); } }"); } [WorkItem(636319, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/636319")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_636319() { await TestInRegularAndScriptAsync( @" using System.Collections.Generic; class Program { static void Main() { IList<object> x[||] = new List<dynamic>(); IList<dynamic> y = x; } } ", @" using System.Collections.Generic; class Program { static void Main() { IList<dynamic> y = new List<dynamic>(); } } "); } [WorkItem(609492, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/609492")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_609492() { await TestInRegularAndScriptAsync( @" using System; class Program { static void Main() { ValueType x[||] = 1; object y = x; } } ", @" using System; class Program { static void Main() { object y = 1; } } "); } [WorkItem(529950, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529950")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTempDoesNotInsertUnnecessaryExplicitTypeInLambdaParameter() { await TestInRegularAndScriptAsync( @" using System; static class C { static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, string y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => { var z[||] = x; Action a = () => z.GetType(); }, y), null); } } ", @" using System; static class C { static void Inner(Action<string> x, string y) { } static void Inner(Action<string> x, int y) { } static void Inner(Action<int> x, int y) { } static void Outer(Action<string> x, object y) { Console.WriteLine(1); } static void Outer(Action<int> x, string y) { Console.WriteLine(2); } static void Main() { Outer(y => Inner(x => { Action a = () => x.GetType(); }, y), null); } } "); } [WorkItem(619425, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/619425")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_619425_RestrictedSimpleNameExpansion() { await TestInRegularAndScriptAsync( @" class A<B> { class C : A<C> { class B : C { void M() { var x[||] = new C[0]; C[] y = x; } } } } ", @" class A<B> { class C : A<C> { class B : C { void M() { C[] y = new C[0]; } } } } "); } [WorkItem(529840, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/529840")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Bugfix_529840_DetectSemanticChangesAtInlineSite() { await TestInRegularAndScriptAsync( @" using System; class A { static void Main() { var a[||] = new A(); // Inline a Goo(a); } static void Goo(long x) { Console.WriteLine(x); } public static implicit operator int (A x) { return 1; } public static explicit operator long (A x) { return 2; } } ", @" using System; class A { static void Main() { // Inline a Goo(new A()); } static void Goo(long x) { Console.WriteLine(x); } public static implicit operator int (A x) { return 1; } public static explicit operator long (A x) { return 2; } } "); } [WorkItem(1091946, "http://vstfdevdiv:8080/DevDiv2/DevDiv/_workitems/edit/1091946")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConditionalAccessWithConversion() { await TestInRegularAndScriptAsync( @"class A { bool M(string[] args) { var [|x|] = args[0]; return x?.Length == 0; } }", @"class A { bool M(string[] args) { return args[0]?.Length == 0; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestSimpleConditionalAccess() { await TestInRegularAndScriptAsync( @"class A { void M(string[] args) { var [|x|] = args.Length.ToString(); var y = x?.ToString(); } }", @"class A { void M(string[] args) { var y = args.Length.ToString()?.ToString(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConditionalAccessWithConditionalExpression() { await TestInRegularAndScriptAsync( @"class A { void M(string[] args) { var [|x|] = args[0]?.Length ?? 10; var y = x == 10 ? 10 : 4; } }", @"class A { void M(string[] args) { var y = (args[0]?.Length ?? 10) == 10 ? 10 : 4; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(2593, "https://github.com/dotnet/roslyn/issues/2593")] public async Task TestConditionalAccessWithExtensionMethodInvocation() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; static class M { public static IEnumerable<string> Something(this C cust) { throw new NotImplementedException(); } } class C { private object GetAssemblyIdentity(IEnumerable<C> types) { foreach (var t in types) { var [|assembly|] = t?.Something().First(); var identity = assembly?.ToArray(); } return null; } }", @"using System; using System.Collections.Generic; using System.Linq; static class M { public static IEnumerable<string> Something(this C cust) { throw new NotImplementedException(); } } class C { private object GetAssemblyIdentity(IEnumerable<C> types) { foreach (var t in types) { var identity = (t?.Something().First())?.ToArray(); } return null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(2593, "https://github.com/dotnet/roslyn/issues/2593")] public async Task TestConditionalAccessWithExtensionMethodInvocation_2() { await TestInRegularAndScriptAsync( @"using System; using System.Collections.Generic; using System.Linq; static class M { public static IEnumerable<string> Something(this C cust) { throw new NotImplementedException(); } public static Func<C> Something2(this C cust) { throw new NotImplementedException(); } } class C { private object GetAssemblyIdentity(IEnumerable<C> types) { foreach (var t in types) { var [|assembly|] = (t?.Something2())()?.Something().First(); var identity = assembly?.ToArray(); } return null; } }", @"using System; using System.Collections.Generic; using System.Linq; static class M { public static IEnumerable<string> Something(this C cust) { throw new NotImplementedException(); } public static Func<C> Something2(this C cust) { throw new NotImplementedException(); } } class C { private object GetAssemblyIdentity(IEnumerable<C> types) { foreach (var t in types) { var identity = ((t?.Something2())()?.Something().First())?.ToArray(); } return null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestAliasQualifiedNameIntoInterpolation() { await TestInRegularAndScriptAsync( @"class A { void M() { var [|g|] = global::System.Guid.Empty; var s = $""{g}""; } }", @"class A { void M() { var s = $""{(global::System.Guid.Empty)}""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConditionalExpressionIntoInterpolation() { await TestInRegularAndScriptAsync( @"class A { bool M(bool b) { var [|x|] = b ? 19 : 23; var s = $""{x}""; } }", @"class A { bool M(bool b) { var s = $""{(b ? 19 : 23)}""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestConditionalExpressionIntoInterpolationWithFormatClause() { await TestInRegularAndScriptAsync( @"class A { bool M(bool b) { var [|x|] = b ? 19 : 23; var s = $""{x:x}""; } }", @"class A { bool M(bool b) { var s = $""{(b ? 19 : 23):x}""; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TestInvocationExpressionIntoInterpolation() { await TestInRegularAndScriptAsync( @"class A { public static void M(string s) { var [|x|] = s.ToUpper(); var y = $""{x}""; } }", @"class A { public static void M(string s) { var y = $""{s.ToUpper()}""; } }"); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontParenthesizeInterpolatedStringWithNoInterpolation_CSharp7() { await TestInRegularAndScriptAsync( @"class C { public void M() { var [|s1|] = $""hello""; var s2 = string.Replace(s1, ""world""); } }", @"class C { public void M() { var s2 = string.Replace($""hello"", ""world""); } }", parseOptions: TestOptions.Regular7); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [WorkItem(33108, "https://github.com/dotnet/roslyn/issues/33108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task CastInterpolatedStringWhenInliningIntoInvalidCall() { // Note: This is an error case. This test just demonstrates our current behavior. It // is ok if this behavior changes in the future in response to an implementation change. await TestInRegularAndScriptAsync( @"class C { public void M() { var [|s1|] = $""hello""; var s2 = string.Replace(s1, ""world""); } }", @"class C { public void M() { var s2 = string.Replace((string)$""hello"", ""world""); } }"); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [WorkItem(33108, "https://github.com/dotnet/roslyn/issues/33108")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DoNotCastInterpolatedStringWhenInliningIntoValidCall() { await TestInRegularAndScriptAsync( @"class C { public void M() { var [|s1|] = $""hello""; var s2 = Replace(s1, ""world""); } void Replace(string s1, string s2) { } }", @"class C { public void M() { var s2 = Replace($""hello"", ""world""); } void Replace(string s1, string s2) { } }"); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontParenthesizeInterpolatedStringWithInterpolation_CSharp7() { await TestInRegularAndScriptAsync( @"class C { public void M(int x) { var [|s1|] = $""hello {x}""; var s2 = string.Replace(s1, ""world""); } }", @"class C { public void M(int x) { var s2 = string.Replace($""hello {x}"", ""world""); } }", parseOptions: TestOptions.Regular7); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [Fact(Skip = "https://github.com/dotnet/roslyn/issues/33108"), Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DontParenthesizeInterpolatedStringWithInterpolation() { await TestInRegularAndScriptAsync( @"class C { public void M(int x) { var [|s1|] = $""hello {x}""; var s2 = string.Replace(s1, ""world""); } }", @"class C { public void M(int x) { var s2 = string.Replace($""hello {x}"", ""world""); } }"); } [WorkItem(15530, "https://github.com/dotnet/roslyn/issues/15530")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task PArenthesizeAwaitInlinedIntoReducedExtensionMethod() { await TestInRegularAndScriptAsync( @"using System.Linq; using System.Threading.Tasks; internal class C { async Task M() { var [|t|] = await Task.FromResult(""""); t.Any(); } }", @"using System.Linq; using System.Threading.Tasks; internal class C { async Task M() { (await Task.FromResult("""")).Any(); } }"); } [WorkItem(4583, "https://github.com/dotnet/roslyn/issues/4583")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineFormattableStringIntoCallSiteRequiringFormattableString() { const string initial = @" using System; " + CodeSnippets.FormattableStringType + @" class C { static void M(FormattableString s) { } static void N(int x, int y) { FormattableString [||]s = $""{x}, {y}""; M(s); } }"; const string expected = @" using System; " + CodeSnippets.FormattableStringType + @" class C { static void M(FormattableString s) { } static void N(int x, int y) { M($""{x}, {y}""); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(4624, "https://github.com/dotnet/roslyn/issues/4624")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineFormattableStringIntoCallSiteWithFormattableStringOverload() { const string initial = @" using System; " + CodeSnippets.FormattableStringType + @" class C { static void M(string s) { } static void M(FormattableString s) { } static void N(int x, int y) { FormattableString [||]s = $""{x}, {y}""; M(s); } }"; const string expected = @" using System; " + CodeSnippets.FormattableStringType + @" class C { static void M(string s) { } static void M(FormattableString s) { } static void N(int x, int y) { M((FormattableString)$""{x}, {y}""); } }"; await TestInRegularAndScriptAsync(initial, expected); } [WorkItem(9576, "https://github.com/dotnet/roslyn/issues/9576")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineIntoLambdaWithReturnStatementWithNoExpression() { const string initial = @" using System; class C { static void M(Action a) { } static void N() { var [||]x = 42; M(() => { Console.WriteLine(x); return; }); } }"; const string expected = @" using System; class C { static void M(Action a) { } static void N() { M(() => { Console.WriteLine(42); return; }); } }"; await TestInRegularAndScriptAsync(initial, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Tuples_Disabled() { var code = @" using System; class C { public void M() { (int, string) [||]x = (1, ""hello""); x.ToString(); } }"; await TestMissingAsync(code, new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp6))); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Tuples() { var code = @" using System; class C { public void M() { (int, string) [||]x = (1, ""hello""); x.ToString(); } }"; var expected = @" using System; class C { public void M() { (1, ""hello"").ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TuplesWithNames() { var code = @" using System; class C { public void M() { (int a, string b) [||]x = (a: 1, b: ""hello""); x.ToString(); } }"; var expected = @" using System; class C { public void M() { (a: 1, b: ""hello"").ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(11028, "https://github.com/dotnet/roslyn/issues/11028")] public async Task TuplesWithDifferentNames() { var code = @" class C { public void M() { (int a, string b) [||]x = (c: 1, d: ""hello""); x.a.ToString(); } }"; var expected = @" class C { public void M() { (((int a, string b))(c: 1, d: ""hello"")).a.ToString(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Deconstruction() { var code = @" using System; class C { public void M() { var [||]temp = new C(); var (x1, x2) = temp; var x3 = temp; } }"; var expected = @" using System; class C { public void M() { {|Warning:var (x1, x2) = new C()|}; var x3 = new C(); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(12802, "https://github.com/dotnet/roslyn/issues/12802")] public async Task Deconstruction2() { var code = @" class Program { static void Main() { var [||]kvp = KVP.Create(42, ""hello""); var(x1, x2) = kvp; } } public static class KVP { public static KVP<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return null; } } public class KVP<T1, T2> { public void Deconstruct(out T1 item1, out T2 item2) { item1 = default(T1); item2 = default(T2); } }"; var expected = @" class Program { static void Main() { var (x1, x2) = KVP.Create(42, ""hello""); } } public static class KVP { public static KVP<T1, T2> Create<T1, T2>(T1 item1, T2 item2) { return null; } } public class KVP<T1, T2> { public void Deconstruct(out T1 item1, out T2 item2) { item1 = default(T1); item2 = default(T2); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(11958, "https://github.com/dotnet/roslyn/issues/11958")] public async Task EnsureParenthesesInStringConcatenation() { var code = @" class C { void M() { int [||]i = 1 + 2; string s = ""a"" + i; } }"; var expected = @" class C { void M() { string s = ""a"" + (1 + 2); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = (i, 3); } }"; var expected = @" class C { void M() { var t = (i: 1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_Trivia() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = ( /*comment*/ i, 3); } }"; var expected = @" class C { void M() { var t = ( /*comment*/ i: 1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_Trivia2() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = ( /*comment*/ i, /*comment*/ 3 ); } }"; var expected = @" class C { void M() { var t = ( /*comment*/ i: 1 + 2, /*comment*/ 3 ); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_NoDuplicateNames() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = (i, i); } }"; var expected = @" class C { void M() { var t = (1 + 2, 1 + 2); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(19047, "https://github.com/dotnet/roslyn/issues/19047")] public async Task ExplicitTupleNameAdded_DeconstructionDeclaration() { var code = @" class C { static int y = 1; void M() { int [||]i = C.y; var t = ((i, (i, _)) = (1, (i, 3))); } }"; var expected = @" class C { static int y = 1; void M() { int i = C.y; var t = (({|Conflict:(int)C.y|}, ({|Conflict:(int)C.y|}, _)) = (1, (C.y, 3))); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(19047, "https://github.com/dotnet/roslyn/issues/19047")] public async Task ExplicitTupleNameAdded_DeconstructionDeclaration2() { var code = @" class C { static int y = 1; void M() { int [||]i = C.y; var t = ((i, _) = (1, 2)); } }"; var expected = @" class C { static int y = 1; void M() { int i = C.y; var t = (({|Conflict:(int)C.y|}, _) = (1, 2)); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_NoReservedNames() { var code = @" class C { void M() { int [||]Rest = 1 + 2; var t = (Rest, 3); } }"; var expected = @" class C { void M() { var t = (1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_NoReservedNames2() { var code = @" class C { void M() { int [||]Item1 = 1 + 2; var t = (Item1, 3); } }"; var expected = @" class C { void M() { var t = (1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_EscapeKeywords() { var code = @" class C { void M() { int [||]@int = 1 + 2; var t = (@int, 3); } }"; var expected = @" class C { void M() { var t = (@int: 1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitTupleNameAdded_DoNotEscapeContextualKeywords() { var code = @" class C { void M() { int [||]@where = 1 + 2; var t = (@where, 3); } }"; var expected = @" class C { void M() { var t = (where: 1 + 2, 3); } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitAnonymousTypeMemberNameAdded_DuplicateNames() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = new { i, i }; // error already } }"; var expected = @" class C { void M() { var t = new { i = 1 + 2, i = 1 + 2 }; // error already } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitAnonymousTypeMemberNameAdded_AssignmentEpression() { var code = @" class C { void M() { int j = 0; int [||]i = j = 1; var t = new { i, k = 3 }; } }"; var expected = @" class C { void M() { int j = 0; var t = new { i = j = 1, k = 3 }; } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitAnonymousTypeMemberNameAdded_Comment() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = new { /*comment*/ i, j = 3 }; } }"; var expected = @" class C { void M() { var t = new { /*comment*/ i = 1 + 2, j = 3 }; } }"; await TestInRegularAndScriptAsync(code, expected); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task ExplicitAnonymousTypeMemberNameAdded_Comment2() { var code = @" class C { void M() { int [||]i = 1 + 2; var t = new { /*comment*/ i, /*comment*/ j = 3 }; } }"; var expected = @" class C { void M() { var t = new { /*comment*/ i = 1 + 2, /*comment*/ j = 3 }; } }"; await TestInRegularAndScriptAsync(code, expected); } [WorkItem(19247, "https://github.com/dotnet/roslyn/issues/19247")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTemporary_LocalFunction() { await TestInRegularAndScriptAsync( @" using System; class C { void M() { var [|testStr|] = ""test""; expand(testStr); void expand(string str) { } } }", @" using System; class C { void M() { expand(""test""); void expand(string str) { } } }"); } [WorkItem(11712, "https://github.com/dotnet/roslyn/issues/11712")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTemporary_RefParams() { await TestInRegularAndScriptAsync( @" class C { bool M<T>(ref T x) { var [||]b = M(ref x); return b || b; } }", @" class C { bool M<T>(ref T x) { return {|Warning:M(ref x) || M(ref x)|}; } }"); } [WorkItem(11712, "https://github.com/dotnet/roslyn/issues/11712")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineTemporary_OutParams() { await TestInRegularAndScriptAsync( @" class C { bool M<T>(out T x) { var [||]b = M(out x); return b || b; } }", @" class C { bool M<T>(out T x) { return {|Warning:M(out x) || M(out x)|}; } }"); } [WorkItem(24791, "https://github.com/dotnet/roslyn/issues/24791")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineVariableDoesNotAddUnnecessaryCast() { await TestInRegularAndScriptAsync( @"class C { bool M() { var [||]o = M(); if (!o) throw null; throw null; } }", @"class C { bool M() { if (!M()) throw null; throw null; } }"); } [WorkItem(16819, "https://github.com/dotnet/roslyn/issues/16819")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineVariableDoesNotAddsDuplicateCast() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [||]o = (Exception)null; Console.Write(o == new Exception()); } }", @"using System; class C { void M() { Console.Write((Exception)null == new Exception()); } }"); } [WorkItem(30903, "https://github.com/dotnet/roslyn/issues/30903")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineVariableContainsAliasOfValueTupleType() { await TestInRegularAndScriptAsync( @"using X = System.ValueTuple<int, int>; class C { void M() { var [|x|] = (X)(0, 0); var x2 = x; } }", @"using X = System.ValueTuple<int, int>; class C { void M() { var x2 = (X)(0, 0); } }"); } [WorkItem(30903, "https://github.com/dotnet/roslyn/issues/30903")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineVariableContainsAliasOfMixedValueTupleType() { await TestInRegularAndScriptAsync( @"using X = System.ValueTuple<int, (int, int)>; class C { void M() { var [|x|] = (X)(0, (0, 0)); var x2 = x; } }", @"using X = System.ValueTuple<int, (int, int)>; class C { void M() { var x2 = (X)(0, (0, 0)); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(35645, "https://github.com/dotnet/roslyn/issues/35645")] public async Task UsingDeclaration() { var code = @" using System; class C : IDisposable { public void M() { using var [||]c = new C(); c.ToString(); } public void Dispose() { } }"; await TestMissingInRegularAndScriptAsync(code, new TestParameters(parseOptions: TestOptions.Regular.WithLanguageVersion(LanguageVersion.CSharp8))); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Selections1() { await TestFixOneAsync( @"{ [|int x = 0;|] Console.WriteLine(x); }", @"{ Console.WriteLine(0); }"); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Selections2() { await TestFixOneAsync( @"{ int [|x = 0|], y = 1; Console.WriteLine(x); }", @"{ int y = 1; Console.WriteLine(0); }"); } [WorkItem(35180, "https://github.com/dotnet/roslyn/issues/35180")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task Selections3() { await TestFixOneAsync( @"{ int x = 0, [|y = 1|], z = 2; Console.WriteLine(y); }", @"{ int x = 0, z = 2; Console.WriteLine(1); }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnOnInlineIntoConditional1() { await TestFixOneAsync( @"{ var [|x = true|]; System.Diagnostics.Debug.Assert(x); }", @"{ {|Warning:System.Diagnostics.Debug.Assert(true)|}; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnOnInlineIntoConditional2() { await TestFixOneAsync( @"{ var [|x = true|]; System.Diagnostics.Debug.Assert(x == true); }", @"{ {|Warning:System.Diagnostics.Debug.Assert(true == true)|}; }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnOnInlineIntoMultipleConditionalLocations() { await TestInRegularAndScriptAsync( @"class C { void M() { var [|x = true|]; System.Diagnostics.Debug.Assert(x); System.Diagnostics.Debug.Assert(x); } }", @"class C { void M() { {|Warning:System.Diagnostics.Debug.Assert(true)|}; {|Warning:System.Diagnostics.Debug.Assert(true)|}; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task OnlyWarnOnConditionalLocations() { await TestInRegularAndScriptAsync( @"using System; class C { void M() { var [|x = true|]; System.Diagnostics.Debug.Assert(x); Console.Writeline(x); } }", @"using System; class C { void M() { {|Warning:System.Diagnostics.Debug.Assert(true)|}; Console.Writeline(true); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(40201, "https://github.com/dotnet/roslyn/issues/40201")] public async Task TestUnaryNegationOfDeclarationPattern() { await TestInRegularAndScriptAsync( @"using System.Threading; class C { void Test() { var [|ct|] = CancellationToken.None; if (!(Helper(ct) is string notDiscard)) { } } object Helper(CancellationToken ct) { return null; } }", @"using System.Threading; class C { void Test() { if (!(Helper(CancellationToken.None) is string notDiscard)) { } } object Helper(CancellationToken ct) { return null; } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(18322, "https://github.com/dotnet/roslyn/issues/18322")] public async Task TestInlineIntoExtensionMethodInvokedOnThis() { await TestInRegularAndScriptAsync( @"public class Class1 { void M() { var [|c|] = 8; this.DoStuff(c); } } public static class Class1Extensions { public static void DoStuff(this Class1 c, int x) { } }", @"public class Class1 { void M() { this.DoStuff(8); } } public static class Class1Extensions { public static void DoStuff(this Class1 c, int x) { } }"); } [WorkItem(8716, "https://github.com/dotnet/roslyn/issues/8716")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DoNotQualifyInlinedLocalFunction() { await TestInRegularAndScriptAsync(@" using System; class C { void Main() { void LocalFunc() { Console.Write(2); } var [||]local = new Action(LocalFunc); local(); } }", @" using System; class C { void Main() { void LocalFunc() { Console.Write(2); } new Action(LocalFunc)(); } }"); } [WorkItem(22540, "https://github.com/dotnet/roslyn/issues/22540")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task DoNotQualifyWhenInliningIntoPattern() { await TestInRegularAndScriptAsync(@" using Syntax; namespace Syntax { class AwaitExpressionSyntax : ExpressionSyntax { public ExpressionSyntax Expression; } class ExpressionSyntax { } class ParenthesizedExpressionSyntax : ExpressionSyntax { } } static class Goo { static void Bar(AwaitExpressionSyntax awaitExpression) { ExpressionSyntax [||]expression = awaitExpression.Expression; if (!(expression is ParenthesizedExpressionSyntax parenthesizedExpression)) return; } }", @" using Syntax; namespace Syntax { class AwaitExpressionSyntax : ExpressionSyntax { public ExpressionSyntax Expression; } class ExpressionSyntax { } class ParenthesizedExpressionSyntax : ExpressionSyntax { } } static class Goo { static void Bar(AwaitExpressionSyntax awaitExpression) { if (!(awaitExpression.Expression is ParenthesizedExpressionSyntax parenthesizedExpression)) return; } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = new C(); c.P = 1; var c2 = c; } }", @" class C { int P { get; set; } void M() { {|Warning:new C().P = 1|}; var c2 = new C(); } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_IgnoreParentheses() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = (new C()); c.P = 1; var c2 = c; } }", @" class C { int P { get; set; } void M() { {|Warning:(new C()).P = 1|}; var c2 = (new C()); } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_MethodInvocation() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = M2(); c.P = 1; var c2 = c; } C M2() { return new C(); } }", @" class C { int P { get; set; } void M() { {|Warning:M2().P = 1|}; var c2 = M2(); } C M2() { return new C(); } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_MethodInvocation2() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = new C(); c.M2(); var c2 = c; } void M2() { P = 1; } }", @" class C { int P { get; set; } void M() { {|Warning:new C().M2()|}; var c2 = new C(); } void M2() { P = 1; } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_NestedObjectInitialization() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = new C[1] { new C() }; c[0].P = 1; var c2 = c; } }", @" class C { int P { get; set; } void M() { {|Warning:(new C[1] { new C() })[0].P = 1|}; var c2 = new C[1] { new C() }; } }"); } [WorkItem(42835, "https://github.com/dotnet/roslyn/issues/42835")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task WarnWhenPossibleChangeInSemanticMeaning_NestedMethodCall() { await TestInRegularAndScriptAsync(@" class C { int P { get; set; } void M() { var [||]c = new C[1] { M2() }; c[0].P = 1; var c2 = c; } C M2() { P += 1; return new C(); } }", @" class C { int P { get; set; } void M() { {|Warning:(new C[1] { M2() })[0].P = 1|}; var c2 = new C[1] { M2() }; } C M2() { P += 1; return new C(); } }"); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task InlineIntoWithExpression() { await TestInRegularAndScriptAsync(@" record Person(string Name) { void M(Person p) { string [||]x = """"; _ = p with { Name = x }; } } namespace System.Runtime.CompilerServices { public sealed class IsExternalInit { } }", @" record Person(string Name) { void M(Person p) { _ = p with { Name = """" }; } } namespace System.Runtime.CompilerServices { public sealed class IsExternalInit { } }", parseOptions: CSharpParseOptions.Default.WithLanguageVersion(LanguageVersion.Preview)); } [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] [WorkItem(44263, "https://github.com/dotnet/roslyn/issues/44263")] public async Task Call_TopLevelStatement() { var code = @" using System; int [||]x = 1 + 1; x.ToString(); "; var expected = @" using System; (1 + 1).ToString(); "; // Global statements in regular code are local variables, so Inline Temporary works. Script code is not // tested because global statements in script code are field declarations, which are not considered // temporary. await TestAsync(code, expected, TestOptions.Regular.WithLanguageVersion(LanguageVersionExtensions.CSharp9)); } [WorkItem(44263, "https://github.com/dotnet/roslyn/issues/44263")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TopLevelStatement() { // Note: we should simplify 'global' as well // https://github.com/dotnet/roslyn/issues/44420 var code = @" int val = 0; int [||]val2 = val + 1; System.Console.WriteLine(val2); "; var expected = @" int val = 0; global::System.Console.WriteLine(val + 1); "; // Global statements in regular code are local variables, so Inline Temporary works. Script code is not // tested because global statements in script code are field declarations, which are not considered // temporary. await TestAsync(code, expected, TestOptions.Regular.WithLanguageVersion(LanguageVersionExtensions.CSharp9)); } [WorkItem(44263, "https://github.com/dotnet/roslyn/issues/44263")] [Fact, Trait(Traits.Feature, Traits.Features.CodeActionsInlineTemporary)] public async Task TopLevelStatement_InScope() { // Note: we should simplify 'global' as well // https://github.com/dotnet/roslyn/issues/44420 await TestAsync(@" { int val = 0; int [||]val2 = val + 1; System.Console.WriteLine(val2); } ", @" { int val = 0; global::System.Console.WriteLine(val + 1); } ", TestOptions.Regular.WithLanguageVersion(LanguageVersionExtensions.CSharp9)); } } }
21.091856
172
0.548126
[ "MIT" ]
JavierMatosD/roslyn
src/EditorFeatures/CSharpTest/CodeActions/InlineTemporary/InlineTemporaryTests.cs
111,367
C#
using System; using System.Text; using System.Collections.Generic; namespace Altazion.Api.Data { ///<summary> ///Objet de données VitrineContentData ///</summary> public class VitrineContentData { ///<summary> ///Obtient ou définit la valeur Articles ///</summary> public ArticleDetailDansVitrineData[] Articles{ get; set; } ///<summary> ///Obtient ou définit la valeur Guid ///</summary> public Guid Guid{ get; set; } ///<summary> ///Obtient ou définit la valeur Libelle ///</summary> public string Libelle{ get; set; } ///<summary> ///Obtient ou définit la valeur Code ///</summary> public string Code{ get; set; } ///<summary> ///Obtient ou définit la valeur Groupe ///</summary> public string Groupe{ get; set; } ///<summary> ///Obtient ou définit la valeur EstAutomatique ///</summary> public bool EstAutomatique{ get; set; } ///<summary> ///Obtient ou définit la valeur CampagneAssocieeGuid ///</summary> public Guid? CampagneAssocieeGuid{ get; set; } } }
21.081633
61
0.666021
[ "MIT" ]
altazion/altazion-sdk-csharp
SdkCSharpSources/Altazion.Api/Data/CatalogueSelectionsControllerVitrineContentData.cs
1,043
C#
using System.Collections; namespace Core.Extensions { public interface IStringDictionary : IEnumerable { void Add(string pKey, string pValue); bool ContainsKey(string pKey); void Clear(); int Count { get; } IEnumerable Keys { get; } IEnumerable Values { get; } } }
23.214286
52
0.615385
[ "Apache-2.0" ]
ClassicDIY/SkyeTracker
code/Archive/Netduino/Core/Extensions/IStringDictionary.cs
325
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using osu.Framework.Graphics; using osu.Game.Graphics.UserInterface; namespace osu.Game.Overlays.Comments.Buttons { public class LoadRepliesButton : LoadingButton { private ButtonContent content; public LoadRepliesButton() { AutoSizeAxes = Axes.Both; } protected override Drawable CreateContent() => content = new ButtonContent(); protected override void OnLoadStarted() => content.ToggleTextVisibility(false); protected override void OnLoadFinished() => content.ToggleTextVisibility(true); private class ButtonContent : CommentRepliesButton { public ButtonContent() { Text = "load replies"; } } } }
28.636364
88
0.625397
[ "MIT" ]
02Naitsirk/osu
osu.Game/Overlays/Comments/Buttons/LoadRepliesButton.cs
915
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Ganss.Excel { /// <summary> /// Attribute which specifies that the formula result instead of the formula should be mapped. /// This applies only to string properties, as for all other types the result will be mapped. /// </summary> /// <seealso cref="System.Attribute" /> [AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)] public sealed class FormulaResultAttribute : Attribute { } }
30.666667
98
0.713768
[ "MIT" ]
Selmirrrrr/ExcelMapper
ExcelMapper/FormulaResultAttribute.cs
554
C#
namespace QRCode { partial class frMgtRules { /// <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(); System.Windows.Forms.DataGridViewCellStyle dataGridViewCellStyle1 = new System.Windows.Forms.DataGridViewCellStyle(); System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(frMgtRules)); this.dataGridView1 = new System.Windows.Forms.DataGridView(); this.gzmc = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.gznr = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.sl = new System.Windows.Forms.DataGridViewTextBoxColumn(); this.contextMenuStrip1 = new System.Windows.Forms.ContextMenuStrip(this.components); this.创建新的规则ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.删除选中规则ToolStripMenuItem = new System.Windows.Forms.ToolStripMenuItem(); this.label1 = new System.Windows.Forms.Label(); ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).BeginInit(); this.contextMenuStrip1.SuspendLayout(); this.SuspendLayout(); // // dataGridView1 // this.dataGridView1.BackgroundColor = System.Drawing.SystemColors.Control; this.dataGridView1.BorderStyle = System.Windows.Forms.BorderStyle.None; this.dataGridView1.ClipboardCopyMode = System.Windows.Forms.DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText; this.dataGridView1.ColumnHeadersHeightSizeMode = System.Windows.Forms.DataGridViewColumnHeadersHeightSizeMode.AutoSize; this.dataGridView1.Columns.AddRange(new System.Windows.Forms.DataGridViewColumn[] { this.gzmc, this.gznr, this.sl}); this.dataGridView1.ContextMenuStrip = this.contextMenuStrip1; this.dataGridView1.GridColor = System.Drawing.Color.Silver; this.dataGridView1.Location = new System.Drawing.Point(0, 0); this.dataGridView1.MultiSelect = false; this.dataGridView1.Name = "dataGridView1"; dataGridViewCellStyle1.Alignment = System.Windows.Forms.DataGridViewContentAlignment.MiddleLeft; dataGridViewCellStyle1.BackColor = System.Drawing.SystemColors.Control; dataGridViewCellStyle1.Font = new System.Drawing.Font("宋体", 9F, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, ((byte)(134))); dataGridViewCellStyle1.ForeColor = System.Drawing.SystemColors.WindowText; dataGridViewCellStyle1.SelectionBackColor = System.Drawing.SystemColors.ControlLight; dataGridViewCellStyle1.SelectionForeColor = System.Drawing.SystemColors.ControlDark; dataGridViewCellStyle1.WrapMode = System.Windows.Forms.DataGridViewTriState.True; this.dataGridView1.RowHeadersDefaultCellStyle = dataGridViewCellStyle1; this.dataGridView1.RowHeadersVisible = false; this.dataGridView1.RowTemplate.DefaultCellStyle.SelectionBackColor = System.Drawing.Color.Linen; this.dataGridView1.RowTemplate.DefaultCellStyle.SelectionForeColor = System.Drawing.Color.DodgerBlue; this.dataGridView1.RowTemplate.Height = 27; this.dataGridView1.SelectionMode = System.Windows.Forms.DataGridViewSelectionMode.FullRowSelect; this.dataGridView1.Size = new System.Drawing.Size(974, 321); this.dataGridView1.TabIndex = 0; this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick); // // gzmc // this.gzmc.DataPropertyName = "Name"; this.gzmc.Frozen = true; this.gzmc.HeaderText = "规则名称"; this.gzmc.Name = "gzmc"; this.gzmc.ReadOnly = true; // // gznr // this.gznr.DataPropertyName = "Data"; this.gznr.Frozen = true; this.gznr.HeaderText = "规则内容"; this.gznr.Name = "gznr"; this.gznr.ReadOnly = true; this.gznr.Width = 400; // // sl // this.sl.Frozen = true; this.sl.HeaderText = "二维码数量"; this.sl.Name = "sl"; this.sl.ReadOnly = true; this.sl.Width = 120; // // contextMenuStrip1 // this.contextMenuStrip1.ImageScalingSize = new System.Drawing.Size(20, 20); this.contextMenuStrip1.Items.AddRange(new System.Windows.Forms.ToolStripItem[] { this.创建新的规则ToolStripMenuItem, this.删除选中规则ToolStripMenuItem}); this.contextMenuStrip1.Name = "contextMenuStrip1"; this.contextMenuStrip1.Size = new System.Drawing.Size(176, 80); this.contextMenuStrip1.Opening += new System.ComponentModel.CancelEventHandler(this.contextMenuStrip1_Opening); // // 创建新的规则ToolStripMenuItem // this.创建新的规则ToolStripMenuItem.Name = "创建新的规则ToolStripMenuItem"; this.创建新的规则ToolStripMenuItem.Size = new System.Drawing.Size(175, 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(175, 24); this.删除选中规则ToolStripMenuItem.Text = "删除选中规则"; this.删除选中规则ToolStripMenuItem.Click += new System.EventHandler(this.删除选中规则ToolStripMenuItem_Click); // // label1 // this.label1.BackColor = System.Drawing.SystemColors.ControlLight; this.label1.Location = new System.Drawing.Point(5, 267); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(963, 1); this.label1.TabIndex = 4; // // frMgtRules // this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 15F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(975, 323); this.Controls.Add(this.label1); this.Controls.Add(this.dataGridView1); this.Icon = ((System.Drawing.Icon)(resources.GetObject("$this.Icon"))); this.MaximizeBox = false; this.Name = "frMgtRules"; this.StartPosition = System.Windows.Forms.FormStartPosition.CenterParent; this.Text = "规则管理"; ((System.ComponentModel.ISupportInitialize)(this.dataGridView1)).EndInit(); this.contextMenuStrip1.ResumeLayout(false); this.ResumeLayout(false); } #endregion private System.Windows.Forms.DataGridView dataGridView1; private System.Windows.Forms.ContextMenuStrip contextMenuStrip1; private System.Windows.Forms.ToolStripMenuItem 删除选中规则ToolStripMenuItem; private System.Windows.Forms.ToolStripMenuItem 创建新的规则ToolStripMenuItem; private System.Windows.Forms.DataGridViewTextBoxColumn gzmc; private System.Windows.Forms.DataGridViewTextBoxColumn gznr; private System.Windows.Forms.DataGridViewTextBoxColumn sl; private System.Windows.Forms.Label label1; } }
52.841463
161
0.63201
[ "MIT" ]
cookcoder/qrcode
qrcode/frMgtRules.Designer.cs
8,970
C#
using System; using System.Collections.Generic; namespace CogniPyCLI { class Program { static void Main(string[] args) { InteractiveMode.EntryPoint(args); } } }
15.071429
45
0.587678
[ "Apache-2.0" ]
GrzegorzKanka/cognipy
cognipy/CogniPyCLI/Program.cs
213
C#
using System.Reflection; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("AddImageToPDFAsAPage")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("ImageGear for .NET")] [assembly: AssemblyCopyright("")] [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("a092b2e6-81a0-47f6-8c39-ee485e67f8f8")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
37.5
84
0.744444
[ "MIT" ]
Accusoft/imagegear-net-samples
Samples/PDF and JPEG/AddImageToPDFAsAPage/AssemblyInfo.cs
1,352
C#
namespace IDisposableAnalyzers { using Microsoft.CodeAnalysis; internal static class IDISP002DisposeMember { public const string DiagnosticId = "IDISP002"; internal static readonly DiagnosticDescriptor Descriptor = new DiagnosticDescriptor( id: DiagnosticId, title: "Dispose member.", messageFormat: "Dispose member.", category: AnalyzerCategory.Correctness, defaultSeverity: DiagnosticSeverity.Warning, isEnabledByDefault: true, description: "Dispose the member as it is assigned with a created IDisposable.", helpLinkUri: HelpLink.ForId(DiagnosticId)); } }
34.45
92
0.670537
[ "MIT" ]
AArnott/IDisposableAnalyzers
IDisposableAnalyzers/IDISP002DisposeMember.cs
689
C#
using System.Collections.ObjectModel; namespace WebAPIApp.Areas.HelpPage.ModelDescriptions { public class ComplexTypeModelDescription : ModelDescription { public ComplexTypeModelDescription() { Properties = new Collection<ParameterDescription>(); } public Collection<ParameterDescription> Properties { get; private set; } } }
27.357143
80
0.704961
[ "Apache-2.0" ]
iliantrifonov/TelerikAcademy
ASP.NETWebForms/01.IntroductionToASP.NET/WebAPIApp/Areas/HelpPage/ModelDescriptions/ComplexTypeModelDescription.cs
383
C#
using System; using System.Collections.Generic; using System.Linq; using hw.DebugFormatter; namespace hw.Helper { /// <summary> /// Dicionary that does not allow null values /// </summary> /// <typeparam name="TKey"> </typeparam> /// <typeparam name="TValue"> </typeparam> [AdditionalNodeInfo("NodeDump")] public sealed class FunctionCache<TKey, TValue> : Dictionary<TKey, TValue> { readonly Func<TKey, TValue> _createValue; public FunctionCache(Func<TKey, TValue> createValue) { _createValue = createValue; } public FunctionCache(TValue defaultValue, Func<TKey, TValue> createValue) { DefaultValue = defaultValue; _createValue = createValue; } public FunctionCache(IEqualityComparer<TKey> comparer, Func<TKey, TValue> createValue) : base(comparer) { _createValue = createValue; } public FunctionCache(FunctionCache<TKey, TValue> target, IEqualityComparer<TKey> comparer) : base(target, comparer) { _createValue = target._createValue; } public FunctionCache(IDictionary<TKey, TValue> target, Func<TKey, TValue> createValue) : base(target) { _createValue = createValue; } public FunctionCache(FunctionCache<TKey, TValue> target) : base(target) { _createValue = target._createValue; } public FunctionCache() { _createValue = ThrowKeyNotFoundException; } static TValue ThrowKeyNotFoundException(TKey key) { throw new KeyNotFoundException(key.ToString()); } public FunctionCache<TKey, TValue> Clone { get { return new FunctionCache<TKey, TValue>(this); } } [DisableDump] public string NodeDump { get { return GetType().PrettyName(); } } void Ensure(TKey key) { if(ContainsKey(key)) return; base[key] = DefaultValue; base[key] = _createValue(key); } public readonly TValue DefaultValue; public bool IsValid(TKey key) { return ContainsKey(key); } public void IsValid(TKey key, bool value) { if(value) Ensure(key); else if(ContainsKey(key)) Remove(key); } /// <summary> /// Gets the value with the specified key /// </summary> /// <value> </value> /// created 13.01.2007 15:43 public new TValue this[TKey key] { get { Ensure(key); return base[key]; } set { Add(key, value); } } public new TKey[] Keys { get { var keys = base.Keys; var result = new TKey[keys.Count]; var i = 0; foreach(var key in keys) result[i++] = key; return result; } } sealed class NoCaseComparer : IEqualityComparer<string> { static IEqualityComparer<string> _default; /// <summary> /// Determines whether the specified objects are equal. /// </summary> /// <returns> true if the specified objects are equal; otherwise, false. </returns> /// <param name="y"> The second object of type T to compare. </param> /// <param name="target"> The first object of type T to compare. </param> public bool Equals(string target, string y) { return target.ToUpperInvariant() == y.ToUpperInvariant(); } /// <summary> /// When overridden in a derived class, serves as a hash function for the specified object for hashing algorithms and /// data structures, such as a hash table. /// </summary> /// <returns> A hash code for the specified object. </returns> /// <param name="obj"> The object for which to get a hash code. </param> /// <exception cref="T:System.ArgumentNullException">The type of obj is a reference type and obj is null.</exception> public int GetHashCode(string obj) { return EqualityComparer<string>.Default.GetHashCode(obj.ToUpperInvariant()); } public static IEqualityComparer<string> Default { get { return _default ?? (_default = new NoCaseComparer()); } } } } }
32.089041
133
0.542796
[ "MIT" ]
hahoyer/HWClassLibrary.cs
src/hw.T4/hw/Helper/FunctionCache.cs
4,685
C#
using System; using System.Collections.Generic; using System.Configuration; using System.Data; using System.Linq; using System.Threading.Tasks; using System.Windows; namespace My_OCR { /// <summary> /// Interaction logic for App.xaml /// </summary> public partial class App : Application { } }
18.722222
43
0.664688
[ "Apache-2.0" ]
GuptaArpit14/My-OCR
App.xaml.cs
339
C#
/* * * (c) Copyright Ascensio System Limited 2010-2020 * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * http://www.apache.org/licenses/LICENSE-2.0 * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.Web; using System.Web.UI; using AjaxPro; using ASC.Core; using ASC.Web.Studio.Core; using ASC.Web.Studio.Utility; namespace ASC.Web.Studio.UserControls.Management.SingleSignOnSettings { //TODO: Remove this or re-write like in Control Panel? [ManagementControl(ManagementType.PortalSecurity, ManagementType.SingleSignOnSettings, Location, SortOrder = 100)] [AjaxNamespace("SsoSettingsController")] public partial class SingleSignOnSettings : UserControl { protected SsoSettingsV2 Settings { get; private set; } protected const string Location = "~/UserControls/Management/SingleSignOnSettings/SingleSignOnSettings.ascx"; protected string HelpLink { get; set; } protected void Page_Load(object sender, EventArgs e) { if (CoreContext.Configuration.Standalone || !SetupInfo.IsVisibleSettings(ManagementType.SingleSignOnSettings.ToString())) { Response.Redirect(CommonLinkUtility.GetDefault(), true); return; } AjaxPro.Utility.RegisterTypeForAjax(typeof(SingleSignOnSettings), Page); Page.RegisterBodyScripts("~/UserControls/Management/SingleSignOnSettings/js/singlesignonsettings.js"); Settings = SsoSettingsV2.Load(); HelpLink = CommonLinkUtility.GetHelpLink(); } } }
35.892857
133
0.71194
[ "Apache-2.0" ]
Ektai-Solution-Pty-Ltd/CommunityServer
web/studio/ASC.Web.Studio/UserControls/Management/SingleSignOnSettings/SingleSignOnSettings.ascx.cs
2,010
C#
using System.Collections.Generic; using System.Linq; using System.Net.Http; using System.Threading.Tasks; using Coinbase_Portfolio_Tracker.Models.Coinbase; using Coinbase_Portfolio_Tracker.Models.Coinbase.Dto; using Coinbase_Portfolio_Tracker.Models.Coinbase.Responses; namespace Coinbase_Portfolio_Tracker.Services.Coinbase { public interface ICoinbaseAccountService { Task<List<CoinbaseAccount>> GetAccountsAsync(); } public class CoinbaseAccountService : RequestService, ICoinbaseAccountService { public CoinbaseAccountService(ICoinbaseConnectService coinbaseConnectService) : base(coinbaseConnectService) { } public async Task<List<CoinbaseAccount>> GetAccountsAsync() { var cbAccountsResponse = await SendApiRequest<CoinbaseAccountResponse>(HttpMethod.Get, "accounts"); return cbAccountsResponse.Accounts .Select(account => new CoinbaseAccount() { Id = account.Id, Name = account.Name, AccountCurrency = account.Currency.Code, BalanceAmount = account.Balance.Amount, BalanceAmountCurrency = account.Balance.Currency }).ToList(); } } }
34.871795
111
0.639706
[ "MIT" ]
chitrangShah/Coinbase_Portfolio_Tracker
Services/Coinbase/CoinbaseAccountService.cs
1,360
C#
using System; using System.Reflection; using HarmonyLib; namespace Pacemaker { internal static class Reflect { public class Method { protected readonly Type Type; protected readonly string Name; protected readonly Type[]? Parameters; protected readonly Type[]? Generics; protected readonly MethodInfo MethodInfo; public Method(Type? type, string name, Type[]? parameters = null, Type[]? generics = null) { Name = name; Parameters = parameters; Generics = generics; Type = type ?? throw new ArgumentNullException($"Null type given when reflecting {PrettyName}!", nameof(type)); MethodInfo = ResolveMethodInfo() ?? throw new MissingMethodException($"Failed to find {PrettyName} in type {Type.FullName}!"); } public TDelegate GetDelegate<TDelegate>(object instance) where TDelegate : Delegate { return instance is null ? throw new ArgumentNullException(nameof(instance), $"{Type.Name} instance cannot be null when binding closed instance delegate to {PrettyName}!") : Delegate.CreateDelegate(typeof(TDelegate), instance, MethodInfo.Name) is not TDelegate @delegate ? throw new InvalidOperationException($"Failed to bind closed delegate to instance {PrettyName} of type {instance.GetType().FullName}!") : @delegate; } public TDelegate GetOpenDelegate<TDelegate>() where TDelegate : Delegate { return Delegate.CreateDelegate(typeof(TDelegate), null, MethodInfo) is not TDelegate @delegate ? throw new InvalidOperationException($"Failed to bind open delegate to {PrettyName} of type {MethodInfo.DeclaringType.FullName}!") : @delegate; } public TDelegate GetDelegate<TDelegate>() where TDelegate : Delegate { return Delegate.CreateDelegate(typeof(TDelegate), MethodInfo) is not TDelegate @delegate ? throw new InvalidOperationException($"Failed to bind closed delegate to {PrettyName} of type {MethodInfo.DeclaringType.FullName}!") : @delegate; } protected string ParametersString => Parameters is null || Parameters.Length == 0 ? string.Empty : $"({string.Join<Type>(", ", Parameters)})"; protected string GenericsString => Generics is null || Generics.Length == 0 ? string.Empty : $"<{string.Join<Type>(",", Generics)}>"; protected virtual string MethodType => "method"; protected virtual string PrettyName => $"{MethodType} {(MethodInfo is null ? Name : MethodInfo.Name)}{GenericsString}{ParametersString}"; protected virtual MethodInfo? ResolveMethodInfo() => AccessTools.Method(Type, Name, Parameters, Generics); } public class DeclaredMethod : Method { public DeclaredMethod(Type? type, string name, Type[]? parameters = null, Type[]? generics = null) : base(type, name, parameters, generics) { } protected override MethodInfo? ResolveMethodInfo() => AccessTools.DeclaredMethod(Type, Name, Parameters, Generics); } public class Getter : Method { public Getter(Type? type, string name) : base(type, name) { } protected override MethodInfo? ResolveMethodInfo() => AccessTools.PropertyGetter(Type, Name); protected override string MethodType => "property getter"; } public class DeclaredGetter : Getter { public DeclaredGetter(Type? type, string name) : base(type, name) { } protected override MethodInfo? ResolveMethodInfo() => AccessTools.DeclaredPropertyGetter(Type, Name); } public class Setter : Method { public Setter(Type? type, string name) : base(type, name) { } protected override MethodInfo? ResolveMethodInfo() => AccessTools.PropertySetter(Type, Name); protected override string MethodType => "property setter"; } public class DeclaredSetter : Setter { public DeclaredSetter(Type? type, string name) : base(type, name) { } protected override MethodInfo? ResolveMethodInfo() => AccessTools.DeclaredPropertySetter(Type, Name); } public sealed class Method<T> : Method { public Method(string name, Type[]? parameters = null, Type[]? generics = null) : base(typeof(T), name, parameters, generics) { } } public sealed class DeclaredMethod<T> : DeclaredMethod { public DeclaredMethod(string name, Type[]? parameters = null, Type[]? generics = null) : base(typeof(T), name, parameters, generics) { } } public sealed class Getter<T> : Getter { public Getter(string name) : base(typeof(T), name) { } } public sealed class DeclaredGetter<T> : DeclaredGetter { public DeclaredGetter(string name) : base(typeof(T), name) { } } public sealed class Setter<T> : Setter { public Setter(string name) : base(typeof(T), name) { } } public sealed class DeclaredSetter<T> : DeclaredSetter { public DeclaredSetter(string name) : base(typeof(T), name) { } } } }
45.66129
167
0.598375
[ "MIT" ]
Jirow13/Pacemaker
src/Reflect.cs
5,664
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. // ---------------------------------------------------------------------------------- namespace Microsoft.WindowsAzure.Commands.Test.Utilities.HDInsight.Simulators { using Management.HDInsight.Cmdlet.Logging; using Management.HDInsight.Logging; internal class BufferingLogWriterFactory : IBufferingLogWriterFactory { public static IBufferingLogWriter Instance { get; set; } public static void Reset() { Instance = null; } public IBufferingLogWriter Create() { return Instance; } } }
36.885714
87
0.596437
[ "MIT" ]
Milstein/azure-sdk-tools
WindowsAzurePowershell/src/Commands.Test.Utilities/HDInsight/Simulators/BufferingLogWriterFactory.cs
1,259
C#
// -------------------------------------------------------------------------------------------------------------------- // <copyright file="CatmullRomSplineHelper.cs" company="OxyPlot"> // Copyright (c) 2014 OxyPlot contributors // </copyright> // <summary> // Provides functionality to interpolate a list of points by a canonical spline. // </summary> // -------------------------------------------------------------------------------------------------------------------- namespace OxyPlot { using System; using System.Collections.Generic; using System.Linq; /// <summary> /// Provides functionality to interpolate a list of points by a Centripetal Catmull–Rom spline. /// </summary> /// <remarks>Based on CanonicalSplineHelper.cs (c) 2009 by Charles Petzold (WPF and Silverlight) /// See also <a href="http://www.charlespetzold.com/blog/2009/01/Canonical-Splines-in-WPF-and-Silverlight.html">blog post</a>.</remarks> public class CatmullRomSpline : IInterpolationAlgorithm { /// <summary> /// The alpha. /// </summary> public double Alpha { get; } public int MaxSegments { get; set; } /// <summary> /// Initializes a new instance of the <see cref = "CatmullRomSpline" /> class. /// </summary> /// <param name="alpha">The alpha.</param> public CatmullRomSpline(double alpha) { this.Alpha = alpha; this.MaxSegments = 100; } /// <summary> /// Creates a spline of data points. /// </summary> /// <param name="points">The points.</param> /// <param name="isClosed">True if the spline is closed.</param> /// <param name="tolerance">The tolerance.</param> /// <returns>A list of data points.</returns> public List<DataPoint> CreateSpline(List<DataPoint> points, bool isClosed, double tolerance) { return CreateSpline(points, this.Alpha, isClosed, tolerance, MaxSegments); } /// <summary> /// Creates a spline of screen points. /// </summary> /// <param name="points">The points.</param> /// <param name="isClosed">True if the spline is closed.</param> /// <param name="tolerance">The tolerance.</param> /// <returns>A list of screen points.</returns> public List<ScreenPoint> CreateSpline(IList<ScreenPoint> points, bool isClosed, double tolerance) { return CreateSpline(points, this.Alpha, isClosed, tolerance, MaxSegments); } /// <summary> /// Creates a spline of data points. /// </summary> /// <param name="points">The points.</param> /// <param name="alpha">The alpha.</param> /// <param name="isClosed">True if the spline is closed.</param> /// <param name="tolerance">The tolerance.</param> /// <returns>A list of data points.</returns> internal static List<DataPoint> CreateSpline(List<DataPoint> points, double alpha, bool isClosed, double tolerance, int maxSegments) { var screenPoints = points.Select(p => new ScreenPoint(p.X, p.Y)).ToList(); var interpolatedScreenPoints = CreateSpline(screenPoints, alpha, isClosed, tolerance, maxSegments); var interpolatedDataPoints = new List<DataPoint>(interpolatedScreenPoints.Count); foreach (var s in interpolatedScreenPoints) { interpolatedDataPoints.Add(new DataPoint(s.X, s.Y)); } return interpolatedDataPoints; } /// <summary> /// Creates a spline of screen points. /// </summary> /// <param name="points">The points.</param> /// <param name="alpha">The alpha.</param> /// <param name="isClosed">True if the spline is closed.</param> /// <param name="tolerance">The tolerance.</param> /// <returns>A list of screen points.</returns> internal static List<ScreenPoint> CreateSpline( IList<ScreenPoint> points, double alpha, bool isClosed, double tolerance, int maxSegments) { var result = new List<ScreenPoint>(); if (points == null) { return result; } int n = points.Count; if (n < 1) { return result; } if (n < 2) { result.AddRange(points); return result; } if (n == 2) { if (!isClosed) { Segment(result, points[0], points[0], points[1], points[1], alpha, tolerance, maxSegments); } else { Segment(result, points[1], points[0], points[1], points[0], alpha, tolerance, maxSegments); Segment(result, points[0], points[1], points[0], points[1], alpha, tolerance, maxSegments); } } else { for (int i = 0; i < n; i++) { if (i == 0) { Segment( result, isClosed ? points[n - 1] : points[0], points[0], points[1], points[2], alpha, tolerance, maxSegments); } else if (i == n - 2) { Segment( result, points[i - 1], points[i], points[i + 1], isClosed ? points[0] : points[i + 1], alpha, tolerance, maxSegments); } else if (i == n - 1) { if (isClosed) { Segment(result, points[i - 1], points[i], points[0], points[1], alpha, tolerance, maxSegments); } } else { Segment(result, points[i - 1], points[i], points[i + 1], points[i + 2], alpha, tolerance, maxSegments); } } } return result; } /// <summary> /// The segment. /// </summary> /// <param name="points">The points.</param> /// <param name="pt0">The pt 0.</param> /// <param name="pt1">The pt 1.</param> /// <param name="pt2">The pt 2.</param> /// <param name="pt3">The pt 3.</param> /// <param name="alpha">The alpha.</param> /// <param name="tolerance">The tolerance.</param> /// <param name="maxSegments">The maximum number of segments.</param> private static void Segment( IList<ScreenPoint> points, ScreenPoint pt0, ScreenPoint pt1, ScreenPoint pt2, ScreenPoint pt3, double alpha, double tolerance, int maxSegments) { if (Equals(pt1, pt2)) { points.Add(pt1); return; } if (Equals(pt0, pt1)) { pt0 = Prev(pt1, pt2); } if (Equals(pt2, pt3)) { pt3 = Prev(pt2, pt1); } double t0 = 0d; double t1 = GetT(t0, pt0, pt1, alpha); double t2 = GetT(t1, pt1, pt2, alpha); double t3 = GetT(t2, pt2, pt3, alpha); int iterations = (int)((Math.Abs(pt1.X - pt2.X) + Math.Abs(pt1.Y - pt2.Y)) / tolerance); //Make sure it is positive (negative means an integer overflow) iterations = Math.Max(0, iterations); //Never more iterations than maxSegments iterations = Math.Min(maxSegments, iterations); for (double t = t1; t < t2; t += (t2 - t1) / iterations) { ScreenPoint a1 = Sum(Mult((t1 - t) / (t1 - t0), pt0), Mult((t - t0) / (t1 - t0), pt1)); ScreenPoint a2 = Sum(Mult((t2 - t) / (t2 - t1), pt1), Mult((t - t1) / (t2 - t1), pt2)); ScreenPoint a3 = Sum(Mult((t3 - t) / (t3 - t2), pt2), Mult((t - t2) / (t3 - t2), pt3)); ScreenPoint b1 = Sum(Mult((t2 - t) / (t2 - t0), a1), Mult((t - t0) / (t2 - t0), a2)); ScreenPoint b2 = Sum(Mult((t3 - t) / (t3 - t1), a2), Mult((t - t1) / (t3 - t1), a3)); ScreenPoint c1 = Sum(Mult((t2 - t) / (t2 - t1), b1), Mult((t - t1) / (t2 - t1), b2)); points.Add(c1); } } private static double GetT(double t, ScreenPoint p0, ScreenPoint p1, double alpha) { double a = Math.Pow(p1.X - p0.X, 2d) + Math.Pow(p1.Y - p0.Y, 2d); double b = Math.Pow(a, 0.5); double c = Math.Pow(b, alpha); return c + t; } private static ScreenPoint Mult(double d, ScreenPoint s) { return new ScreenPoint(s.X * d, s.Y * d); } private static bool Equals(ScreenPoint a, ScreenPoint b) { return Equals(a.X, b.X) && Equals(a.Y, b.Y); } private static ScreenPoint Prev(ScreenPoint s0, ScreenPoint s1) { return new ScreenPoint(s0.X - 0.0001 * (s1.X - s0.X), s0.Y - 0.0001 * (s1.Y - s0.Y)); } private static ScreenPoint Sum(ScreenPoint a, ScreenPoint b) { return new ScreenPoint(a.X + b.X, a.Y + b.Y); } } }
37.969466
140
0.466425
[ "MIT" ]
jmagnette/oxyplot
Source/OxyPlot/Rendering/Utilities/CatmullRomSpline.cs
9,952
C#
using Countdown.Core.Models; using System; using System.Collections.Generic; using System.Linq.Expressions; using System.Text; namespace Countdown.Core.Infrastructure { public abstract class Specification<T> where T: EntityModel { public abstract Expression<Func<T, bool>> ToExpression(); public bool IsSatisfiedBy(T entity) { Func<T, bool> predicate = ToExpression().Compile(); return predicate(entity); } } }
23
65
0.670807
[ "MIT" ]
geegee4iee/countdown
Countdown.Core/Infrastructure/Specification.cs
485
C#
namespace TryAtSoftware.Randomizer.Core { using System; using System.Reflection; using JetBrains.Annotations; using TryAtSoftware.Randomizer.Core.Interfaces; public class RandomValueSetter<TEntity, TValue> : IRandomValueSetter<TEntity> where TEntity : class { private readonly string _propertyName; private readonly IRandomizer<TValue> _randomizer; private readonly IMembersBinder<TEntity> _binder; public RandomValueSetter([NotNull] string propertyName, [NotNull] IRandomizer<TValue> randomizer, [NotNull] IMembersBinder<TEntity> membersBinder) { this._propertyName = propertyName ?? throw new ArgumentNullException(nameof(propertyName)); this._randomizer = randomizer ?? throw new ArgumentNullException(nameof(randomizer)); this._binder = membersBinder ?? throw new ArgumentNullException(nameof(membersBinder)); } public void SetValue(TEntity instance) { if (instance is null || !this._binder.MemberInfos.TryGetValue(this._propertyName, out var memberInfo)) return; var value = this._randomizer.PrepareRandomValue(); try { if (memberInfo is PropertyInfo propertyInfo) propertyInfo.SetValue(instance, value); } catch { // If any exception occurs, we want to swallow it. } } } }
37.3
154
0.641421
[ "MIT" ]
TryAtSoftware/Randomizer
src/TryAtSoftware.Randomizer.Core/RandomValueSetter.cs
1,494
C#
using System; using System.Collections.Generic; using System.Text; namespace HZY.Admin.Dto.Core { using AutoMapper; public static class DtoExtensions { public static T2 MapTo<T1, T2>(this T1 Source) where T1 : class where T2 : class { if (Source == null) return default; var config = new MapperConfiguration(cfg => cfg.CreateMap<T1, T2>()); var mapper = config.CreateMapper(); return mapper.Map<T2>(Source); } } }
19.107143
81
0.575701
[ "MIT" ]
jamee1696/HZY.AdminRazor
HZY.Admin/Dto/Core/DtoExtensions.cs
537
C#
using System; using System.Collections.Generic; using System.Linq; using System.IO; namespace Ragnarok { /// <summary> /// Linq関係の拡張メソッドを定義します。 /// </summary> public static class Extension { /// <summary> /// foreachのlinq版。 /// </summary> public static void ForEach<T>(this IEnumerable<T> source, params Action<T>[] actions) { if (source == null) { return; } foreach (var item in source) { foreach (var action in actions) { action(item); } } } /// <summary> /// each_with_index@ruby のlinq版。 /// </summary> public static void ForEachWithIndex<T>(this IEnumerable<T> source, params Action<T, int>[] actions) { if (source == null) { return; } var index = 0; foreach (var item in source) { foreach (var action in actions) { action(item, index); } index += 1; } } /// <summary> /// Whereにインデックスがついたバージョン。 /// </summary> public static IEnumerable<T> WhereWithIndex<T>(this IEnumerable<T> source, Func<T, int, bool> predicate) { if (source != null) { var index = 0; foreach (var elem in source) { if (predicate(elem, index)) { yield return elem; } index += 1; } } } /// <summary> /// Selectにインデックスがついたバージョン。 /// </summary> public static IEnumerable<TResult> SelectWithIndex<TSource, TResult>( this IEnumerable<TSource> source, Func<TSource, int, TResult> func) { if (source != null) { var index = 0; foreach (var item in source) { yield return func(item, index++); } } } /// <summary> /// 指定の条件を最初に満たす要素番号を取得します。 /// </summary> /// <remarks> /// 条件を満たす要素がない場合は-1を返します。 /// </remarks> public static int FindIndex<T>(this IEnumerable<T> source, Predicate<T> pred) { if (source == null) { return -1; } var index = 0; foreach (var item in source) { if (pred(item)) { return index; } index += 1; } return -1; } /// <summary> /// 最初に指定の条件を満たす要素を削除します。 /// </summary> public static bool RemoveIf<T>(this IList<T> source, Predicate<T> pred) { if (source == null) { return false; } var index = source.FindIndex(pred); if (index >= 0) { source.RemoveAt(index); return true; } else { return false; } } /// <summary> /// <paramref name="source"/>に<paramref name="actions"/>を適用し、その要素列を返します。 /// </summary> public static IEnumerable<T> Apply<T>(this IEnumerable<T> source, params Action<T>[] actions) where T : class { if (source == null) { yield break; } foreach (var item in source) { foreach (var action in actions) { action(item); } yield return item; } } /// <summary> /// selfに指定の操作を適用します。 /// </summary> public static T Apply<T>(this T self, params Action<T>[] actions) where T : class { ForEach(actions, _ => _(self)); return self; } /// <summary> /// <paramref name="source"/>中の要素を<paramref name="count"/> /// 個ごとにまとめ直します。 /// 最後の要素数が足りない場合は足りないまま返します。 /// </summary> public static IEnumerable<IEnumerable<TSource>> TakeBy<TSource>(this IEnumerable<TSource> source, int count) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (count < 1) { throw new ArgumentOutOfRangeException(nameof(count)); } while (source.Any()) { yield return source.Take(count); source = source.Skip(count); } } /// <summary> /// <paramref name="source"/>中の要素を<paramref name="count"/> /// 個ごとにまとめ直します。 /// 最後の要素数が足りない場合はdefault値で補います。 /// </summary> public static IEnumerable<IEnumerable<TSource>> TakeOrDefaultBy<TSource>( this IEnumerable<TSource> source, int count) { if (source == null) { throw new ArgumentNullException(nameof(source)); } if (count < 1) { throw new ArgumentOutOfRangeException(nameof(count)); } using (var enumerator = source.GetEnumerator()) { var values = new TSource[count]; while (enumerator.MoveNext()) { values[0] = enumerator.Current; var index = 1; for (; index < count; ++index) { if (!enumerator.MoveNext()) break; values[index] = enumerator.Current; } for (; index < count; ++index) { values[index] = default; } yield return values; } } } /// <summary> /// Listクラスをリサイズします。 /// </summary> public static void Resize<T>(this List<T> list, int size, T value = default) { if (list == null) { throw new ArgumentNullException(nameof(list)); } int curSize = list.Count; if (size < curSize) { list.RemoveRange(size, curSize - size); } else if (size > curSize) { if (size > list.Capacity) { // 最適化 list.Capacity = size; } list.AddRange(Enumerable.Repeat(value, size - curSize)); } } /// <summary> /// Listクラスをリサイズします。 /// </summary> public static void Resize<T>(this List<T> list, int size) where T : new() { Resize(list, size, new T()); } /// <summary> /// リストの要素をすべて削除し、新しいコレクションを代入します。 /// </summary> public static void Assign<T>(this IList<T> list, IEnumerable<T> collection) { if (list == null) { throw new ArgumentNullException(nameof(list)); } list.Clear(); collection.ForEach(_ => list.Add(_)); } /// <summary> /// イベントハンドラを呼び出します。 /// </summary> public static void RaiseEvent(this EventHandler handler, object sender, EventArgs e) { if (handler == null) { return; } handler(sender, e); } /// <summary> /// 例外が起こらないようにイベントハンドラを呼び出します。 /// </summary> public static void SafeRaiseEvent(this EventHandler handler, object sender, EventArgs e) { if (handler == null) { return; } Util.SafeCall(() => handler(sender, e)); } /// <summary> /// イベントハンドラを呼び出します。 /// </summary> public static void RaiseEvent<TEventArgs>(this EventHandler<TEventArgs> handler, object sender, TEventArgs e) where TEventArgs : EventArgs { if (handler == null) { return; } handler(sender, e); } /// <summary> /// 例外が起こらないようにイベントハンドラを呼び出します。 /// </summary> public static void SafeRaiseEvent<TEventArgs>(this EventHandler<TEventArgs> handler, object sender, TEventArgs e) where TEventArgs : EventArgs { if (handler == null) { return; } Util.SafeCall(() => handler(sender, e)); } } }
27.604457
94
0.388295
[ "MIT" ]
ebifrier/Ragnarok
Ragnarok/Extension.cs
10,658
C#
using ScriptableObjects; using UnityEngine; namespace Pathfinding { public static class Pathfinding { private static PathPriorityQueue _searchFrontier; private static int _searchFrontierPhase; public static float FindPathTime(Cell start, Cell end, float[] speedMultipliers) { var timeToTravel = 0f; FindPath(start, end, speedMultipliers); for (var cell = end; cell != start; cell = cell.GetNeighbor(cell.PathFrom)) { timeToTravel += cell.moveCostTo[(int) cell.PathFrom.Opposite()]; } return timeToTravel; } public static void FindPath(Cell start, Cell end, float[] speedMultipliers) { _searchFrontierPhase += 2; if (_searchFrontier == null) { _searchFrontier = new PathPriorityQueue(); } else { _searchFrontier.Clear(); } start.SearchPhase = _searchFrontierPhase; start.Distance = 0; _searchFrontier.Enqueue(start); var aquaticMul = speedMultipliers[(int) WareData.Vehicle.VehicleType.Water]; var landMul = speedMultipliers[(int) WareData.Vehicle.VehicleType.Land]; if (speedMultipliers[(int) WareData.Vehicle.VehicleType.Air] > aquaticMul) aquaticMul = speedMultipliers[(int) WareData.Vehicle.VehicleType.Air]; if (speedMultipliers[(int) WareData.Vehicle.VehicleType.Air] > landMul) landMul = speedMultipliers[(int) WareData.Vehicle.VehicleType.Air]; while (_searchFrontier.Count > 0) { var current = _searchFrontier.Dequeue(); current.SearchPhase += 1; if (current == end) return; for (var dir = HexDirection.NE; dir <= HexDirection.NW; dir++) { var neighbor = current.GetNeighbor(dir); if ( neighbor == null || neighbor.SearchPhase > _searchFrontierPhase ) continue; var moveCost = Mathf.RoundToInt(current.moveCostTo[(int) dir] / (current.isAquaticMovementTo[(int) dir] ? aquaticMul : landMul)); var distance = current.Distance + moveCost; if (neighbor.SearchPhase < _searchFrontierPhase) { neighbor.SearchPhase = _searchFrontierPhase; neighbor.Distance = distance; neighbor.PathFrom = dir.Opposite();//current; neighbor.SearchHeuristic = neighbor.GetDistance(end); _searchFrontier.Enqueue(neighbor); } else if (distance < neighbor.Distance) { var oldPriority = neighbor.SearchPriority; neighbor.Distance = distance; neighbor.PathFrom = dir.Opposite();//current; _searchFrontier.Change(neighbor, oldPriority); } } } } } }
38.402299
117
0.518707
[ "MIT" ]
Fahrrader/TradeEconomicsSimulation
Assets/Scripts/Pathfinding/Pathfinding.cs
3,341
C#
using System; namespace Chapter03Examples { class FuncExample { public static void Main1() { Func<int, string> mathCalc = Func1; mathCalc += Func2; var resultA = mathCalc(2); Console.WriteLine($"ResultA={resultA}"); var resultB = mathCalc(4); Console.WriteLine($"ResultB={resultB}"); } private static string Func1(int num) { Console.WriteLine($"Called Func1({num})"); return $"Func1: num = {num}"; } private static string Func2(int num) { Console.WriteLine($"Called Func2({num})"); return $"Func2: num = {num}"; } } }
22.121212
54
0.5
[ "MIT" ]
raihantaher/The-C-Sharp-Workshop
Examples/Chapter03/FuncExample.cs
732
C#
using CryptoExchange.Net.Converters; using Newtonsoft.Json; using System; namespace CoinEx.Net.Objects { /// <summary> /// Mining difficulty info /// </summary> public class CoinExMiningDifficulty { /// <summary> /// The difficulty in CET/Hour /// </summary> public string Difficulty { get; set; } = string.Empty; /// <summary> /// Estimated hourly mining yield to distribute /// </summary> public string Prediction { get; set; } = string.Empty; /// <summary> /// The update time of the Prediction field /// </summary> [JsonConverter(typeof(TimestampSecondsConverter))] [JsonProperty("update_time")] public DateTime UpdateTime { get; set; } } }
27.964286
62
0.592593
[ "MIT" ]
EricGarnier/CoinEx.Net
CoinEx.Net/Objects/CoinExMiningDifficulty.cs
785
C#
using UnityEngine; using System.Collections; /// <summary> /// NPC wisp in the ethereal void. Is not really an NPC but an animated decoration /// </summary> public class NPC_Wisp : NPC { /// <summary> /// NPC Does not need a start like NPcs /// </summary> protected override void Start () { npc_whoami=48;//Wisp conversation. } /// <summary> /// NPC Door update is not required. /// </summary> public override void Update() { //base.Update (); } public override bool ApplyAttack (short damage, GameObject source) { return true; } public override bool ApplyAttack (short damage) { return true; } }
18
82
0.671429
[ "MIT" ]
FaizanMughal/UnderworldExporter
UnityScripts/scripts/NPC/NPC_Wisp.cs
632
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.VisualStudio.TestPlatform.CommandLine.Processors { using System; using System.Diagnostics.CodeAnalysis; using System.Diagnostics.Contracts; using System.Globalization; using System.Xml; using System.Xml.XPath; using Microsoft.VisualStudio.TestPlatform.Common; using Microsoft.VisualStudio.TestPlatform.Common.Interfaces; using Microsoft.VisualStudio.TestPlatform.ObjectModel; using Microsoft.VisualStudio.TestPlatform.ObjectModel.Utilities; using Microsoft.VisualStudio.TestPlatform.Utilities; using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers; using Microsoft.VisualStudio.TestPlatform.Utilities.Helpers.Interfaces; using Microsoft.VisualStudio.TestPlatform.CommandLine.Processors.Utilities; using CommandLineResources = Microsoft.VisualStudio.TestPlatform.CommandLine.Resources.Resources; internal class RunSettingsArgumentProcessor : IArgumentProcessor { #region Constants /// <summary> /// The name of the command line argument that the PortArgumentExecutor handles. /// </summary> public const string CommandName = "/Settings"; #endregion private Lazy<IArgumentProcessorCapabilities> metadata; private Lazy<IArgumentExecutor> executor; /// <summary> /// Gets the metadata. /// </summary> public Lazy<IArgumentProcessorCapabilities> Metadata { get { if (this.metadata == null) { this.metadata = new Lazy<IArgumentProcessorCapabilities>(() => new RunSettingsArgumentProcessorCapabilities()); } return this.metadata; } } /// <summary> /// Gets or sets the executor. /// </summary> public Lazy<IArgumentExecutor> Executor { get { if (this.executor == null) { this.executor = new Lazy<IArgumentExecutor>(() => new RunSettingsArgumentExecutor(CommandLineOptions.Instance, RunSettingsManager.Instance)); } return this.executor; } set { this.executor = value; } } } internal class RunSettingsArgumentProcessorCapabilities : BaseArgumentProcessorCapabilities { public override string CommandName => RunSettingsArgumentProcessor.CommandName; public override bool AllowMultiple => false; public override bool IsAction => false; public override ArgumentProcessorPriority Priority => ArgumentProcessorPriority.RunSettings; public override string HelpContentResourceName => CommandLineResources.RunSettingsArgumentHelp; public override HelpContentPriority HelpPriority => HelpContentPriority.RunSettingsArgumentProcessorHelpPriority; } internal class RunSettingsArgumentExecutor : IArgumentExecutor { private CommandLineOptions commandLineOptions; private IRunSettingsProvider runSettingsManager; internal IFileHelper FileHelper { get; set; } internal RunSettingsArgumentExecutor(CommandLineOptions commandLineOptions, IRunSettingsProvider runSettingsManager) { this.commandLineOptions = commandLineOptions; this.runSettingsManager = runSettingsManager; this.FileHelper = new FileHelper(); } public void Initialize(string argument) { if (string.IsNullOrWhiteSpace(argument)) { throw new CommandLineException(CommandLineResources.RunSettingsRequired); } if (!this.FileHelper.Exists(argument)) { throw new CommandLineException( string.Format( CultureInfo.CurrentCulture, CommandLineResources.RunSettingsFileNotFound, argument)); } Contract.EndContractBlock(); // Load up the run settings and set it as the active run settings. try { IXPathNavigable document = this.GetRunSettingsDocument(argument); this.runSettingsManager.UpdateRunSettings(document.CreateNavigator().OuterXml); //Add default runsettings values if not exists in given runsettings file. this.runSettingsManager.AddDefaultRunSettings(); this.commandLineOptions.SettingsFile = argument; } catch (XmlException exception) { throw new CommandLineException(CommandLineResources.MalformedRunSettingsFile, exception); } catch (SettingsException exception) { throw new CommandLineException(exception.Message, exception); } } [SuppressMessage("Microsoft.Security.Xml", "CA3053:UseXmlSecureResolver", Justification = "XmlReaderSettings.XmlResolver is not available in core. Suppress until fxcop issue is fixed.")] protected virtual XmlReader GetReaderForFile(string runSettingsFile) { return XmlReader.Create(runSettingsFile, XmlRunSettingsUtilities.ReaderSettings); } [SuppressMessage("Microsoft.Security.Xml", "CA3053:UseXmlSecureResolver", Justification = "XmlDocument.XmlResolver is not available in core. Suppress until fxcop issue is fixed.")] private IXPathNavigable GetRunSettingsDocument(string runSettingsFile) { IXPathNavigable runSettingsDocument; if (!MSTestSettingsUtilities.IsLegacyTestSettingsFile(runSettingsFile)) { using (XmlReader reader = this.GetReaderForFile(runSettingsFile)) { var settingsDocument = new XmlDocument(); settingsDocument.Load(reader); ClientUtilities.FixRelativePathsInRunSettings(settingsDocument, runSettingsFile); #if NET46 runSettingsDocument = settingsDocument; #else runSettingsDocument = settingsDocument.ToXPathNavigable(); #endif } } else { runSettingsDocument = XmlRunSettingsUtilities.CreateDefaultRunSettings(); runSettingsDocument = MSTestSettingsUtilities.Import(runSettingsFile, runSettingsDocument, Architecture.X86, FrameworkVersion.Framework45); } if (this.commandLineOptions.EnableCodeCoverage == true) { try { CodeCoverageDataAdapterUtilities.UpdateWithCodeCoverageSettingsIfNotConfigured(runSettingsDocument); } catch (XPathException e) { throw new SettingsException(CommandLineResources.MalformedRunSettingsFile, e); } } return runSettingsDocument; } public ArgumentProcessorResult Execute() { // Nothing to do here, the work was done in initialization. return ArgumentProcessorResult.Success; } } }
37.365
161
0.636692
[ "MIT" ]
eerhardt/vstest
src/vstest.console/Processors/RunSettingsArgumentProcessor.cs
7,473
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 EnsureThat; using Microsoft.ApplicationInsights; namespace Microsoft.Health.Logging.Telemetry { public class IomtTelemetryLogger : ITelemetryLogger { private readonly TelemetryClient _telemetryClient; public IomtTelemetryLogger(TelemetryClient telemetryClient) { _telemetryClient = telemetryClient; EnsureArg.IsNotNull(_telemetryClient); } public virtual void LogMetric(Common.Telemetry.Metric metric, double metricValue) { EnsureArg.IsNotNull(metric); LogMetricWithDimensions(metric, metricValue); } public virtual void LogError(Exception ex) { if (ex is AggregateException e) { // Address bug https://github.com/microsoft/iomt-fhir/pull/120 LogAggregateException(e); } else { LogExceptionWithProperties(ex); LogInnerException(ex); } } public virtual void LogTrace(string message) { _telemetryClient.TrackTrace(message); } public void LogMetricWithDimensions(Common.Telemetry.Metric metric, double metricValue) { EnsureArg.IsNotNull(metric); _telemetryClient.LogMetric(metric, metricValue); } private void LogExceptionWithProperties(Exception ex) { EnsureArg.IsNotNull(ex, nameof(ex)); _telemetryClient.LogException(ex); } private void LogAggregateException(AggregateException e) { LogInnerException(e); foreach (var exception in e.InnerExceptions) { LogExceptionWithProperties(exception); } } private void LogInnerException(Exception ex) { EnsureArg.IsNotNull(ex, nameof(ex)); var innerException = ex.InnerException; if (innerException != null) { LogExceptionWithProperties(innerException); } } } }
30.716049
101
0.549839
[ "MIT" ]
msebragge/iomt-fhir
src/lib/Microsoft.Health.Logger/Telemetry/IomtTelemetryLogger.cs
2,490
C#
using PhotoShop.Core.Interfaces; using PhotoShop.Core.Models; using FluentValidation; using MediatR; using System; using System.Threading.Tasks; using System.Threading; using System.Linq; namespace PhotoShop.API.Features.Mentees { public class RemoveMenteeCommand { public class Validator : AbstractValidator<Request> { public Validator() { RuleFor(request => request.MenteeId).NotEqual(default(Guid)); } } public class Request : IRequest { public Guid MenteeId { get; set; } } public class Handler : IRequestHandler<Request> { private readonly IEventStore _eventStore; public Handler(IEventStore eventStore) => _eventStore = eventStore; public Task Handle(Request request, CancellationToken cancellationToken) { var mentee = _eventStore.Load<Mentee>(request.MenteeId); mentee.Remove(); _eventStore.Save(mentee); return Task.CompletedTask; } } } }
25.130435
84
0.584775
[ "MIT" ]
QuinntyneBrown/PhotoShop
src/PhotoShop.API/Features/Mentees/RemoveMenteeCommand.cs
1,156
C#
using System; using Exceptions; namespace StackCalculator { /// <summary> /// Класс, реализующий стек на остнове связного списка /// </summary> public class LinkedStack : IStack { /// <summary> /// Голова стека (ссылка на верхний элемент) /// </summary> private StackElement _head; public void Push(int value) { _head = new StackElement(value, _head); Count++; } public int Pop() { if (this.IsEmpty()) { throw new EmptyStackException( "Попытка доступа к элементам пустого стека" ); } var tempValue = _head.Value; _head = _head.Next; Count--; return tempValue; } public int Peek() { if (this.IsEmpty()) { throw new EmptyStackException( "Попытка доступа к элементам пустого стека" ); } return _head.Value; } public void Clear() { Count = 0; _head = null; } public int Count { get; private set; } /// <summary> /// Класс, реализующий элемент стека, хранит целочисленные значения /// </summary> private class StackElement { public int Value { get; } public StackElement Next { get; } public StackElement(int value, StackElement next) { Value = value; Next = next; } } } }
23.291667
75
0.455575
[ "Apache-2.0" ]
anticNVM/144.math.spbu-II
homeWork 3/T1-StackCalculator/StackCalculator/LinkedStack.cs
1,880
C#
using System; namespace Deepgram.Transcription { public class TranscriptReceivedEventArgs: EventArgs { public TranscriptReceivedEventArgs(LiveTranscriptionResult transcript) { Transcript = transcript; } public LiveTranscriptionResult Transcript { get; set; } } }
21.533333
78
0.678019
[ "MIT" ]
deepgram-devs/deepgram-dotnet-sdk
Deepgram/Transcription/TranscriptReceivedEventArgs.cs
325
C#
using System; using System.Collections.Generic; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Animation { /// <summary> /// Interaction logic for ExpandElement.xaml /// </summary> public partial class ExpandElement : System.Windows.Window { public ExpandElement() { InitializeComponent(); } } }
20.5
62
0.703833
[ "MIT" ]
DiogoBarbosaSilvaSousa/apress
pro-wpf-4.5-in-csharp/Pro WPF 4.5 in C#/Chapter16/Animation/ExpandElement.xaml.cs
574
C#
using System; using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; using UnityEngine.SceneManagement; public class FinishLogic : MonoBehaviour { int countDownStartValue=5; public Text timerUI; public GameObject Time5; public GameObject Time4; public GameObject Time3; public GameObject Time2; public GameObject Time1; public GameObject Time0; // Start is called before the first frame update void Start() { countDownTimer(); } void countDownTimer(){ if( countDownStartValue>0){ TimeSpan spanTime = TimeSpan.FromSeconds(countDownStartValue); timerUI.text= ""+spanTime.Seconds; countDownStartValue--; Invoke("countDownTimer", 1.0f); if(countDownStartValue==5){Time5.SetActive(true);} if(countDownStartValue==4){Time5.SetActive(false);Time4.SetActive(true);} if(countDownStartValue==3){Time4.SetActive(false);Time3.SetActive(true);} if(countDownStartValue==2){Time3.SetActive(false);Time2.SetActive(true);} if(countDownStartValue==1){Time2.SetActive(false);Time1.SetActive(true);} } else { if(countDownStartValue==0){Time1.SetActive(false);Time0.SetActive(true);} SceneManager.LoadScene("MainMenu", LoadSceneMode.Single); } } // Update is called once per frame void Update() { } }
26.12069
85
0.642904
[ "MIT" ]
JoseRamonMartinez/ForkLift-Simulator-MiniGame
Assets/Scenes/Scripts/FinishLogic.cs
1,517
C#
/* * Copyright 2010-2014 Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the appstream-2016-12-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.AppStream.Model { /// <summary> /// Container for the parameters to the CreateStreamingURL operation. /// Creates a temporary URL to start an AppStream 2.0 streaming session for the specified /// user. A streaming URL enables application streaming to be tested without user setup. /// </summary> public partial class CreateStreamingURLRequest : AmazonAppStreamRequest { private string _applicationId; private string _fleetName; private string _sessionContext; private string _stackName; private string _userId; private long? _validity; /// <summary> /// Gets and sets the property ApplicationId. /// <para> /// The name of the application to launch after the session starts. This is the name that /// you specified as <b>Name</b> in the Image Assistant. /// </para> /// </summary> [AWSProperty(Min=1)] public string ApplicationId { get { return this._applicationId; } set { this._applicationId = value; } } // Check to see if ApplicationId property is set internal bool IsSetApplicationId() { return this._applicationId != null; } /// <summary> /// Gets and sets the property FleetName. /// <para> /// The name of the fleet. /// </para> /// </summary> [AWSProperty(Required=true, Min=1)] public string FleetName { get { return this._fleetName; } set { this._fleetName = value; } } // Check to see if FleetName property is set internal bool IsSetFleetName() { return this._fleetName != null; } /// <summary> /// Gets and sets the property SessionContext. /// <para> /// The session context. For more information, see <a href="https://docs.aws.amazon.com/appstream2/latest/developerguide/managing-stacks-fleets.html#managing-stacks-fleets-parameters">Session /// Context</a> in the <i>Amazon AppStream 2.0 Developer Guide</i>. /// </para> /// </summary> [AWSProperty(Min=1)] public string SessionContext { get { return this._sessionContext; } set { this._sessionContext = value; } } // Check to see if SessionContext property is set internal bool IsSetSessionContext() { return this._sessionContext != null; } /// <summary> /// Gets and sets the property StackName. /// <para> /// The name of the stack. /// </para> /// </summary> [AWSProperty(Required=true, Min=1)] public string StackName { get { return this._stackName; } set { this._stackName = value; } } // Check to see if StackName property is set internal bool IsSetStackName() { return this._stackName != null; } /// <summary> /// Gets and sets the property UserId. /// <para> /// The identifier of the user. /// </para> /// </summary> [AWSProperty(Required=true, Min=2, Max=32)] public string UserId { get { return this._userId; } set { this._userId = value; } } // Check to see if UserId property is set internal bool IsSetUserId() { return this._userId != null; } /// <summary> /// Gets and sets the property Validity. /// <para> /// The time that the streaming URL will be valid, in seconds. Specify a value between /// 1 and 604800 seconds. The default is 60 seconds. /// </para> /// </summary> public long Validity { get { return this._validity.GetValueOrDefault(); } set { this._validity = value; } } // Check to see if Validity property is set internal bool IsSetValidity() { return this._validity.HasValue; } } }
31.515528
199
0.582578
[ "Apache-2.0" ]
FoxBearBear/aws-sdk-net
sdk/src/Services/AppStream/Generated/Model/CreateStreamingURLRequest.cs
5,074
C#
using System.Linq; using System.Threading.Tasks; using System.Web; using System.Web.Mvc; using Microsoft.AspNet.Identity; using Microsoft.AspNet.Identity.Owin; using Microsoft.Owin.Security; using IceCloud.BeebApp.UI.SiteSolucao.Models; namespace IceCloud.BeebApp.UI.SiteSolucao.Controllers { [Authorize] public class AccountController : Controller { private ApplicationSignInManager _signInManager; private ApplicationUserManager _userManager; public AccountController() { } public AccountController(ApplicationUserManager userManager, ApplicationSignInManager signInManager) { UserManager = userManager; SignInManager = signInManager; } public ApplicationSignInManager SignInManager { get { return _signInManager ?? HttpContext.GetOwinContext().Get<ApplicationSignInManager>(); } private set { _signInManager = value; } } public ApplicationUserManager UserManager { get { return _userManager ?? HttpContext.GetOwinContext().GetUserManager<ApplicationUserManager>(); } private set { _userManager = value; } } // // GET: /Account/Login [AllowAnonymous] public ActionResult Login(string returnUrl) { ViewBag.ReturnUrl = returnUrl; return View(); } // // POST: /Account/Login [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Login(LoginViewModel model, string returnUrl) { if (!ModelState.IsValid) { return View(model); } // Isso não conta falhas de login em relação ao bloqueio de conta // Para permitir que falhas de senha acionem o bloqueio da conta, altere para shouldLockout: true var result = await SignInManager.PasswordSignInAsync(model.Email, model.Password, model.RememberMe, shouldLockout: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = model.RememberMe }); case SignInStatus.Failure: default: ModelState.AddModelError("", "Tentativa de login inválida."); return View(model); } } // // GET: /Account/VerifyCode [AllowAnonymous] public async Task<ActionResult> VerifyCode(string provider, string returnUrl, bool rememberMe) { // Exija que o usuário efetue login via nome de usuário/senha ou login externo if (!await SignInManager.HasBeenVerifiedAsync()) { return View("Error"); } return View(new VerifyCodeViewModel { Provider = provider, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/VerifyCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> VerifyCode(VerifyCodeViewModel model) { if (!ModelState.IsValid) { return View(model); } // O código a seguir protege de ataques de força bruta em relação aos códigos de dois fatores. // Se um usuário inserir códigos incorretos para uma quantidade especificada de tempo, então a conta de usuário // será bloqueado por um período especificado de tempo. // Você pode configurar os ajustes de bloqueio da conta em IdentityConfig var result = await SignInManager.TwoFactorSignInAsync(model.Provider, model.Code, isPersistent: model.RememberMe, rememberBrowser: model.RememberBrowser); switch (result) { case SignInStatus.Success: return RedirectToLocal(model.ReturnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.Failure: default: ModelState.AddModelError("", "Código inválido."); return View(model); } } // // GET: /Account/Register [AllowAnonymous] public ActionResult Register() { return View(); } // // POST: /Account/Register [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> Register(RegisterViewModel model) { if (ModelState.IsValid) { var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user, model.Password); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); // Para obter mais informações sobre como habilitar a confirmação da conta e redefinição de senha, visite https://go.microsoft.com/fwlink/?LinkID=320771 // Enviar um email com este link // string code = await UserManager.GenerateEmailConfirmationTokenAsync(user.Id); // var callbackUrl = Url.Action("ConfirmEmail", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Confirmar sua conta", "Confirme sua conta clicando <a href=\"" + callbackUrl + "\">aqui</a>"); return RedirectToAction("Index", "Home"); } AddErrors(result); } // Se chegamos até aqui e houver alguma falha, exiba novamente o formulário return View(model); } // // GET: /Account/ConfirmEmail [AllowAnonymous] public async Task<ActionResult> ConfirmEmail(string userId, string code) { if (userId == null || code == null) { return View("Error"); } var result = await UserManager.ConfirmEmailAsync(userId, code); return View(result.Succeeded ? "ConfirmEmail" : "Error"); } // // GET: /Account/ForgotPassword [AllowAnonymous] public ActionResult ForgotPassword() { return View(); } // // POST: /Account/ForgotPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ForgotPassword(ForgotPasswordViewModel model) { if (ModelState.IsValid) { var user = await UserManager.FindByNameAsync(model.Email); if (user == null || !(await UserManager.IsEmailConfirmedAsync(user.Id))) { // Não revelar que o usuário não existe ou não está confirmado return View("ForgotPasswordConfirmation"); } // Para obter mais informações sobre como habilitar a confirmação da conta e redefinição de senha, visite https://go.microsoft.com/fwlink/?LinkID=320771 // Enviar um email com este link // string code = await UserManager.GeneratePasswordResetTokenAsync(user.Id); // var callbackUrl = Url.Action("ResetPassword", "Account", new { userId = user.Id, code = code }, protocol: Request.Url.Scheme); // await UserManager.SendEmailAsync(user.Id, "Redefinir senha", "Redefina sua senha, clicando <a href=\"" + callbackUrl + "\">aqui</a>"); // return RedirectToAction("ForgotPasswordConfirmation", "Account"); } // Se chegamos até aqui e houver alguma falha, exiba novamente o formulário return View(model); } // // GET: /Account/ForgotPasswordConfirmation [AllowAnonymous] public ActionResult ForgotPasswordConfirmation() { return View(); } // // GET: /Account/ResetPassword [AllowAnonymous] public ActionResult ResetPassword(string code) { return code == null ? View("Error") : View(); } // // POST: /Account/ResetPassword [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ResetPassword(ResetPasswordViewModel model) { if (!ModelState.IsValid) { return View(model); } var user = await UserManager.FindByNameAsync(model.Email); if (user == null) { // Não revelar que o usuário não existe return RedirectToAction("ResetPasswordConfirmation", "Account"); } var result = await UserManager.ResetPasswordAsync(user.Id, model.Code, model.Password); if (result.Succeeded) { return RedirectToAction("ResetPasswordConfirmation", "Account"); } AddErrors(result); return View(); } // // GET: /Account/ResetPasswordConfirmation [AllowAnonymous] public ActionResult ResetPasswordConfirmation() { return View(); } // // POST: /Account/ExternalLogin [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public ActionResult ExternalLogin(string provider, string returnUrl) { // Solicitar um redirecionamento para o provedor de logon externo return new ChallengeResult(provider, Url.Action("ExternalLoginCallback", "Account", new { ReturnUrl = returnUrl })); } // // GET: /Account/SendCode [AllowAnonymous] public async Task<ActionResult> SendCode(string returnUrl, bool rememberMe) { var userId = await SignInManager.GetVerifiedUserIdAsync(); if (userId == null) { return View("Error"); } var userFactors = await UserManager.GetValidTwoFactorProvidersAsync(userId); var factorOptions = userFactors.Select(purpose => new SelectListItem { Text = purpose, Value = purpose }).ToList(); return View(new SendCodeViewModel { Providers = factorOptions, ReturnUrl = returnUrl, RememberMe = rememberMe }); } // // POST: /Account/SendCode [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> SendCode(SendCodeViewModel model) { if (!ModelState.IsValid) { return View(); } // Gerar o token e enviá-lo if (!await SignInManager.SendTwoFactorCodeAsync(model.SelectedProvider)) { return View("Error"); } return RedirectToAction("VerifyCode", new { Provider = model.SelectedProvider, ReturnUrl = model.ReturnUrl, RememberMe = model.RememberMe }); } // // GET: /Account/ExternalLoginCallback [AllowAnonymous] public async Task<ActionResult> ExternalLoginCallback(string returnUrl) { var loginInfo = await AuthenticationManager.GetExternalLoginInfoAsync(); if (loginInfo == null) { return RedirectToAction("Login"); } // Faça logon do usuário com este provedor de logon externo se o usuário já tiver um logon var result = await SignInManager.ExternalSignInAsync(loginInfo, isPersistent: false); switch (result) { case SignInStatus.Success: return RedirectToLocal(returnUrl); case SignInStatus.LockedOut: return View("Lockout"); case SignInStatus.RequiresVerification: return RedirectToAction("SendCode", new { ReturnUrl = returnUrl, RememberMe = false }); case SignInStatus.Failure: default: // Se o usuário não tiver uma conta, solicite que o usuário crie uma conta ViewBag.ReturnUrl = returnUrl; ViewBag.LoginProvider = loginInfo.Login.LoginProvider; return View("ExternalLoginConfirmation", new ExternalLoginConfirmationViewModel { Email = loginInfo.Email }); } } // // POST: /Account/ExternalLoginConfirmation [HttpPost] [AllowAnonymous] [ValidateAntiForgeryToken] public async Task<ActionResult> ExternalLoginConfirmation(ExternalLoginConfirmationViewModel model, string returnUrl) { if (User.Identity.IsAuthenticated) { return RedirectToAction("Index", "Manage"); } if (ModelState.IsValid) { // Obter as informações sobre o usuário do provedor de logon externo var info = await AuthenticationManager.GetExternalLoginInfoAsync(); if (info == null) { return View("ExternalLoginFailure"); } var user = new ApplicationUser { UserName = model.Email, Email = model.Email }; var result = await UserManager.CreateAsync(user); if (result.Succeeded) { result = await UserManager.AddLoginAsync(user.Id, info.Login); if (result.Succeeded) { await SignInManager.SignInAsync(user, isPersistent: false, rememberBrowser: false); return RedirectToLocal(returnUrl); } } AddErrors(result); } ViewBag.ReturnUrl = returnUrl; return View(model); } // // POST: /Account/LogOff [HttpPost] [ValidateAntiForgeryToken] public ActionResult LogOff() { AuthenticationManager.SignOut(DefaultAuthenticationTypes.ApplicationCookie); return RedirectToAction("Index", "Home"); } // // GET: /Account/ExternalLoginFailure [AllowAnonymous] public ActionResult ExternalLoginFailure() { return View(); } protected override void Dispose(bool disposing) { if (disposing) { if (_userManager != null) { _userManager.Dispose(); _userManager = null; } if (_signInManager != null) { _signInManager.Dispose(); _signInManager = null; } } base.Dispose(disposing); } #region Auxiliares // Usado para proteção XSRF ao adicionar logons externos private const string XsrfKey = "XsrfId"; private IAuthenticationManager AuthenticationManager { get { return HttpContext.GetOwinContext().Authentication; } } private void AddErrors(IdentityResult result) { foreach (var error in result.Errors) { ModelState.AddModelError("", error); } } private ActionResult RedirectToLocal(string returnUrl) { if (Url.IsLocalUrl(returnUrl)) { return Redirect(returnUrl); } return RedirectToAction("Index", "Home"); } internal class ChallengeResult : HttpUnauthorizedResult { public ChallengeResult(string provider, string redirectUri) : this(provider, redirectUri, null) { } public ChallengeResult(string provider, string redirectUri, string userId) { LoginProvider = provider; RedirectUri = redirectUri; UserId = userId; } public string LoginProvider { get; set; } public string RedirectUri { get; set; } public string UserId { get; set; } public override void ExecuteResult(ControllerContext context) { var properties = new AuthenticationProperties { RedirectUri = RedirectUri }; if (UserId != null) { properties.Dictionary[XsrfKey] = UserId; } context.HttpContext.GetOwinContext().Authentication.Challenge(properties, LoginProvider); } } #endregion } }
36.178423
172
0.555167
[ "MIT" ]
alanfoandrade/IceCloud-BeeBapp
src/IceCloud.BeebApp.UI.SiteSolucao/Controllers/AccountController.cs
17,497
C#
using System; using System.Collections.Generic; using System.Text; namespace Nglib.APP.LOG { /// <summary> /// Model pour monitorer /// </summary> [Obsolete("DevSoon")] public class AppWatch { } }
15.133333
33
0.621145
[ "MIT" ]
NueGy/NGLib
dev/Nglib/APP/LOG/AppWatch.cs
229
C#
using IRepository; using Library.Constant; using Library.DI; using System; using System.Collections.Generic; namespace Repository { /// <summary> /// 仓储实现类,提供实体工厂和存储过程执行 /// </summary> public class Repository : IRepository.IRepository { private IDataContext DbContext; private Dictionary<Type, object> baseRepository = new Dictionary<Type,object>(); public Repository() { this.DbContext = Di.GetInstance<Data.DB_Context>(DiKey.DBCONTEXT, true); } /// <summary> /// 实体工厂 /// </summary> /// <typeparam name="T">实体类型参数</typeparam> /// <returns>实体工厂</returns> public IBaseRepository<T> GetReposirotyFactory<T>() where T : class { Type type = typeof(T); if (!baseRepository.ContainsKey(type)) { baseRepository.Add(type, new BaseRepository<T>(DbContext)); } return (BaseRepository<T>)baseRepository[type]; } /// <summary> /// 存储过程 /// </summary> /// <returns>存储过程</returns> public IExecuteSp GetSpInstance() { return ExecuteSp.GetInstance(DbContext); } /// <summary> /// 持久化保存,新增,删除,修改都需要调用此方法来持久化数据 /// </summary> public int SaveChange() { return DbContext.SaveChanges(); } } }
26.12963
88
0.557052
[ "Apache-2.0" ]
huahuajjh/tms
src/api/TMS/Repository/Repository.cs
1,551
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class RadialBarProgress : MonoBehaviour { public Transform LoadingBar; public Transform txtPercent; // Use this for initialization [SerializeField] float currentAmount; [SerializeField] float speed = 0.01f; void Update () { if (currentAmount <100){ currentAmount += speed * Time.deltaTime; txtPercent.GetComponent<Text>().text = ((int)currentAmount).ToString() + "%"; } LoadingBar.GetComponent<Image>().fillAmount = currentAmount / 100; } }
26.166667
89
0.678344
[ "MIT" ]
aup84/Argeo
Assets/scripts/ArenaScene/RadialBarProgress.cs
630
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using RPG.Models; namespace RPG.Migrations { [DbContext(typeof(RPGDbContext))] [Migration("20170810223147_AddObsolete")] partial class AddObsolete { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.1.2") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Name") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("RoleId") .IsRequired(); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<string>("UserId") .IsRequired(); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<string>("UserId") .IsRequired(); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.Property<string>("UserId"); b.Property<string>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserToken<string>", b => { b.Property<string>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("RPG.Models.ApplicationUser", b => { b.Property<string>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasAnnotation("MaxLength", 256); b.Property<bool>("EmailConfirmed"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasAnnotation("MaxLength", 256); b.Property<string>("NormalizedUserName") .HasAnnotation("MaxLength", 256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasAnnotation("MaxLength", 256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("RPG.Models.Item", b => { b.Property<int>("ItemId") .ValueGeneratedOnAdd(); b.Property<int>("LocationId"); b.Property<string>("Name"); b.HasKey("ItemId"); b.HasIndex("LocationId"); b.ToTable("Items"); }); modelBuilder.Entity("RPG.Models.Location", b => { b.Property<int>("LocationId") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.HasKey("LocationId"); b.ToTable("Locations"); }); modelBuilder.Entity("RPG.Models.Player", b => { b.Property<int>("PlayerId") .ValueGeneratedOnAdd(); b.Property<string>("ApplicationUserId"); b.Property<byte[]>("Avatar"); b.Property<int>("Health"); b.Property<int>("LocationId"); b.Property<string>("Name"); b.Property<int>("Strength"); b.Property<string>("UserId"); b.HasKey("PlayerId"); b.HasIndex("ApplicationUserId"); b.HasIndex("LocationId"); b.ToTable("Players"); }); modelBuilder.Entity("RPG.Models.PlayerItem", b => { b.Property<int>("InventoryId") .ValueGeneratedOnAdd(); b.Property<int>("ItemId"); b.Property<int>("PlayerId"); b.HasKey("InventoryId"); b.HasIndex("ItemId"); b.HasIndex("PlayerId"); b.ToTable("PlayerItems"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRoleClaim<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Claims") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserClaim<string>", b => { b.HasOne("RPG.Models.ApplicationUser") .WithMany("Claims") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserLogin<string>", b => { b.HasOne("RPG.Models.ApplicationUser") .WithMany("Logins") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityUserRole<string>", b => { b.HasOne("Microsoft.AspNetCore.Identity.EntityFrameworkCore.IdentityRole") .WithMany("Users") .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("RPG.Models.ApplicationUser") .WithMany("Roles") .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("RPG.Models.Item", b => { b.HasOne("RPG.Models.Location", "ItemLocation") .WithMany("LocationItems") .HasForeignKey("LocationId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("RPG.Models.Player", b => { b.HasOne("RPG.Models.ApplicationUser", "ApplicationUser") .WithMany() .HasForeignKey("ApplicationUserId"); b.HasOne("RPG.Models.Location", "PlayerLocation") .WithMany() .HasForeignKey("LocationId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("RPG.Models.PlayerItem", b => { b.HasOne("RPG.Models.Item", "Item") .WithMany("PlayerItems") .HasForeignKey("ItemId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("RPG.Models.Player", "Player") .WithMany("PlayerItems") .HasForeignKey("PlayerId") .OnDelete(DeleteBehavior.Cascade); }); } } }
33.281734
117
0.462605
[ "MIT" ]
mcarlin27/RPG
src/RPG/Migrations/20170810223147_AddObsolete.Designer.cs
10,752
C#
using Discord; namespace nomoretrolls.Messaging { internal record DiscordMessageContext : IDiscordMessageContext { public DiscordMessageContext(IMessage message) { Message = message; } public IMessage Message { get; init; } } }
18.25
66
0.626712
[ "MIT" ]
tonycknight/nomoretrolls
src/nomoretrolls/Messaging/DiscordMessageContext.cs
294
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using System; using UnityEngine.SceneManagement; #if UNITY_WSA using Microsoft.MixedReality.Toolkit.Input; #endif // This component is a MonoBehaviour so we can add references to prefabs and scene stuff in the inspector public class SimulationManagerComponent : MonoBehaviour { // A local reference to the Singleton manager private SimulationManager manager; [SerializeField] private GameObject networkControllerPrefab; [SerializeField] private GameObject interactionControllerPrefab; [SerializeField] private GameObject celestialSpherePrefab; [SerializeField] private GameObject mainUIPrefab; [SerializeField] private GameObject infoPanelPrefab; [SerializeField] private Material starMaterial; // Celestial Sphere scene-specific settings [SerializeField] private int maxStars = 10000; [SerializeField] private float radius = 50; [SerializeField] private float magnitudeScale = 0.5f; [SerializeField] private float magnitudeThreshold = 4.5f; [SerializeField] private bool showHorizonView = false; [SerializeField] private float simulationTimeScale = 10f; [SerializeField] private bool colorByConstellation = false; [SerializeField] private bool showConstellationConnections = false; // Settings for markers [SerializeField] private bool showMarkers; [SerializeField] private bool showPoleLine; [SerializeField] private bool showEquator; [SerializeField] float markerLineWidth = .1f; [SerializeField] float markerScale = 1f; [SerializeField] float annotationWidthMultiplier = 1f; // Settings for constellations [SerializeField] private float lineWidth = .035f; [SerializeField] private StarComponent starPrefab; [SerializeField] private SceneLoader sceneLoaderPrefab; private SceneLoader sceneLoader; // Settings for menu [SerializeField] private bool allowMovement = true; [SerializeField] private float rotateSpeed = 10f; private void Awake() { manager = SimulationManager.Instance; if (!manager.IsReady) { TextAsset colorList = Resources.Load("colors") as TextAsset; TextAsset animalList = Resources.Load("animals") as TextAsset; char[] lineDelim = new char[] { '\r', '\n' }; string[] colorsFull = colorList.text.Split(lineDelim, StringSplitOptions.RemoveEmptyEntries); List<string> colors = new List<string>(); List<Color> colorValues = new List<Color>(); foreach (string c in colorsFull) { colors.Add(c.Split(':')[0]); Color color; ColorUtility.TryParseHtmlString(c.Split(':')[1], out color); colorValues.Add(color); } manager.ColorNames = colors; manager.ColorValues = colorValues; manager.AnimalNames = animalList.text.Split(lineDelim, StringSplitOptions.RemoveEmptyEntries); manager.IsReady = true; CCDebug.Log("Manager ready"); } else { CCDebug.Log("Manager configuration already set"); } CCDebug.Log("Applying scene settings"); Setup(); } void Setup() { SceneLoader existingLoader = FindObjectOfType<SceneLoader>(); if (existingLoader != null) { sceneLoader = existingLoader; } else { sceneLoader = Instantiate(sceneLoaderPrefab); } if (manager.NetworkControllerComponent == null) { if (FindObjectOfType<NetworkController>() != null) { manager.NetworkControllerComponent = FindObjectOfType<NetworkController>(); } else { CCDebug.Log("Creating new network object"); manager.NetworkControllerComponent = Instantiate(networkControllerPrefab).GetComponent<NetworkController>(); } } if (manager.InteractionControllerObject == null) { if (FindObjectOfType<InteractionController>() != null) { manager.InteractionControllerObject = FindObjectOfType<InteractionController>().gameObject; } else { CCDebug.Log("Creating new Interaction controller object"); manager.InteractionControllerObject = Instantiate(interactionControllerPrefab); } } if (manager.CelestialSphereObject == null) { CCDebug.Log("Creating new Celestial Sphere"); manager.CelestialSphereObject = Instantiate(celestialSpherePrefab); if (this.starPrefab != null) { manager.DataControllerComponent.starPrefab = this.starPrefab; } if (!starMaterial) starMaterial = starPrefab.GetComponent<Renderer>().material; // When creating, set parameters before Init manager.DataControllerComponent.SetSceneParameters(maxStars, magnitudeScale, magnitudeThreshold, showHorizonView, simulationTimeScale, radius, colorByConstellation, showConstellationConnections, starMaterial); // Create all the stars manager.DataControllerComponent.Init(); // Set up the markers with a reference to the dataController for parameters like current radius manager.MarkersControllerComponent.Init(); manager.MarkersControllerComponent.SetSceneParameters(markerLineWidth, markerScale, showMarkers, showPoleLine, showEquator); // Show/hide Marker items toggles visibility of existing objects manager.ConstellationsControllerComponent.SetSceneParameters(lineWidth, showConstellationConnections); AnnotationTool annotationTool = FindObjectOfType<AnnotationTool>(); annotationTool.Init(); annotationTool.annotationWidthMultiplier = annotationWidthMultiplier; annotationTool.scaleFactor = manager.CurrentScaleFactor(radius); manager.DataControllerComponent.UpdateOnSceneLoad(); } else { // Applying scene-specific settings if (manager.DataControllerComponent) { if (!starMaterial) starMaterial = starPrefab.GetComponent<Renderer>().material; manager.DataControllerComponent.SetSceneParameters(maxStars, magnitudeScale, magnitudeThreshold, showHorizonView, simulationTimeScale, radius, colorByConstellation, showConstellationConnections, starMaterial); manager.DataControllerComponent.UpdateOnSceneLoad(); } if (manager.MarkersControllerComponent) { manager.MarkersControllerComponent.SetSceneParameters(markerLineWidth, markerScale, showMarkers, showPoleLine, showEquator); } if (manager.ConstellationsControllerComponent) { manager.ConstellationsControllerComponent.SetSceneParameters(lineWidth, showConstellationConnections); } AnnotationTool annotationTool = FindObjectOfType<AnnotationTool>(); annotationTool.annotationWidthMultiplier = annotationWidthMultiplier; annotationTool.scaleFactor = manager.CurrentScaleFactor(radius); } if (!manager.MainMenu) { MenuController sceneMenu = FindObjectOfType<MenuController>(); if (!sceneMenu) { Instantiate(mainUIPrefab); sceneMenu = FindObjectOfType<MenuController>(); } manager.MainMenu = sceneMenu; manager.NetworkControllerComponent.Setup(); } manager.MainMenu.movementButton.SetActive(allowMovement); manager.MainMenu.rotateSpeed = rotateSpeed; if (!manager.InfoPanel) { InfoPanelController sceneInfoPanel = FindObjectOfType<InfoPanelController>(); if (!sceneInfoPanel) { Instantiate(infoPanelPrefab); } else { manager.InfoPanel = sceneInfoPanel; } } sceneLoader.SetupCameras(); } #if UNITY_WSA public void HandleEarthInteraction(InputEventData inputEvent) { Debug.LogWarning(inputEvent); if (manager.InteractionControllerObject) { manager.InteractionControllerObject.GetComponent<InteractionController>().SetEarthLocationPin(inputEvent.selectedObject.transform.position); } } #endif }
36.987395
152
0.64887
[ "MIT" ]
concord-consortium/CEASAR
Assets/Scripts/SimulationManagerComponent.cs
8,805
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.Windows.Forms; namespace SistemaEstoque.Telas { public partial class frmListaMovimento: Form { private DataTable dtGrid = new DataTable(); private BindingSource bsGrid = new BindingSource(); public frmListaMovimento() { InitializeComponent(); PreencheGrid(); } private void btnFechar_Click(object sender, EventArgs e) { this.Close(); } private void PreencheGrid() { SistemaEstoque.Banco.tbMovimentacao Movimentacao = new Banco.tbMovimentacao(); dtGrid = Movimentacao.Consulta(); bsGrid.DataSource = dtGrid; grd.DataSource = bsGrid; grd.Columns["id"].HeaderText = "Código Movimentação"; grd.Columns["id_produto"].HeaderText = "Código Produto"; grd.Columns["Nome_produto"].HeaderText = "Produto"; grd.Columns["id_localEstoque"].HeaderText = "Código Local de Estoque"; grd.Columns["Nome_LocalEstoque"].HeaderText = "Local Estoque"; grd.Columns["datahora"].HeaderText = "Data e Hora"; grd.Columns["quantidade"].HeaderText = "Quantidade"; grd.Columns["saida"].HeaderText = "Movimentação de Saída"; grd.Columns["descricao"].HeaderText = "Descrição"; } private void txtFiltro_TextChanged(object sender, EventArgs e) { bsGrid.Filter = "descricao like '%" + txtFiltro.Text + "%'"; } private void btnNovo_Click(object sender, EventArgs e) { frmMovimento frm = new frmMovimento(false, null); frm.ShowDialog(); PreencheGrid(); } private void btnAlterar_Click(object sender, EventArgs e) { DataRowView drv = (DataRowView)bsGrid.Current; Banco.tbMovimentacao Movimentacao = new Banco.tbMovimentacao(); Movimentacao.id = Convert.ToInt16(drv["id"]); Movimentacao.id_produto = Convert.ToInt16(drv["id_produto"]); Movimentacao.id_localEstoque = Convert.ToInt16(drv["id_localEstoque"]); Movimentacao.dataHora = Convert.ToDateTime(drv["dataHora"]); Movimentacao.quantidade = Convert.ToDecimal(drv["quantidade"]); Movimentacao.saida = Convert.ToBoolean(drv["saida"]); Movimentacao.descricao = Convert.ToString(drv["descricao"]); frmMovimento frm = new frmMovimento(true, Movimentacao); frm.ShowDialog(); PreencheGrid(); } private void btnExcluir_Click(object sender, EventArgs e) { if (MessageBox.Show("Deseja realmente excluir o movimento?", "Confirmação", MessageBoxButtons.YesNo ) == DialogResult.Yes) { DataRowView drv = (DataRowView)bsGrid.Current; Banco.tbMovimentacao Movimentacao = new Banco.tbMovimentacao(); Movimentacao.id = Convert.ToInt16(drv["id"]); Movimentacao.Excluir(); PreencheGrid(); } } } }
32.762376
134
0.608643
[ "Apache-2.0" ]
marcospmoliveira/sistema_estoque-1.0
SistemaEstoque.Telas/frmListaMovimento.cs
3,323
C#
using AdminAssistant.UI; using Microsoft.AspNetCore.Components; using Syncfusion.Blazor.Spinner; namespace AdminAssistant.Blazor.Client.Shared; public abstract class AdminAssistantComponentBase<TViewModel> : ComponentBase where TViewModel : IViewModelBase { #pragma warning disable CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. [Inject] protected TViewModel vm { get; set; } #pragma warning restore CS8618 // Non-nullable field is uninitialized. Consider declaring as nullable. protected SfSpinner SfSpinner { get; set; } = new(); protected override void OnInitialized() { vm.PropertyChanged += (o, e) => StateHasChanged(); vm.IsBusyChanged += (sender, isBusy) => { //if (this.SfSpinner is null) // throw new System.NullReferenceException("Loading spinner reference not set on component base"); if (isBusy) SfSpinner.ShowAsync(); else SfSpinner.HideAsync(); }; base.OnInitialized(); } protected override Task OnAfterRenderAsync(bool firstRender) => base.OnAfterRenderAsync(firstRender); protected override Task OnInitializedAsync() => vm.OnInitializedAsync(); }
34.405405
117
0.680283
[ "MIT" ]
SimonGeering/AdminAssistant
src/AdminAssistant.Blazor.Client/Shared/AdminAssistantComponentBase.cs
1,273
C#
// Copyright (c) Six Labors and contributors. // Licensed under the Apache License, Version 2.0. using System; using SixLabors.ImageSharp.ColorSpaces; using SixLabors.ImageSharp.ColorSpaces.Conversion; using Xunit; namespace SixLabors.ImageSharp.Tests.Colorspaces.Conversion { /// <summary> /// Tests <see cref="CieLch"/>-<see cref="Hsl"/> conversions. /// </summary> public class CieLchAndHslConversionTests { private static readonly ApproximateColorSpaceComparer ColorSpaceComparer = new ApproximateColorSpaceComparer(.0002F); private static readonly ColorSpaceConverter Converter = new ColorSpaceConverter(); /// <summary> /// Tests conversion from <see cref="CieLch"/> to <see cref="Hsl"/>. /// </summary> [Theory] [InlineData(0, 0, 0, 0, 0, 0)] [InlineData(36.0555, 103.6901, 10.01514, 341.959, 1, 0.4207301)] public void Convert_CieLch_to_Hsl(float l, float c, float h, float h2, float s, float l2) { // Arrange var input = new CieLch(l, c, h); var expected = new Hsl(h2, s, l2); Span<CieLch> inputSpan = new CieLch[5]; inputSpan.Fill(input); Span<Hsl> actualSpan = new Hsl[5]; // Act var actual = Converter.ToHsl(input); Converter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } /// <summary> /// Tests conversion from <see cref="Hsl"/> to <see cref="CieLch"/>. /// </summary> [Theory] [InlineData(341.959, 1, 0.4207301, 46.13444, 78.0637, 22.90503)] public void Convert_Hsl_to_CieLch(float h2, float s, float l2, float l, float c, float h) { // Arrange var input = new Hsl(h2, s, l2); var expected = new CieLch(l, c, h); Span<Hsl> inputSpan = new Hsl[5]; inputSpan.Fill(input); Span<CieLch> actualSpan = new CieLch[5]; // Act var actual = Converter.ToCieLch(input); Converter.Convert(inputSpan, actualSpan); // Assert Assert.Equal(expected, actual, ColorSpaceComparer); for (int i = 0; i < actualSpan.Length; i++) { Assert.Equal(expected, actualSpan[i], ColorSpaceComparer); } } } }
33.384615
125
0.571045
[ "Apache-2.0" ]
GyleIverson/ImageSharp
tests/ImageSharp.Tests/Colorspaces/Conversion/CieLchAndHslConversionTests.cs
2,606
C#
// Copyright © 2010-2017 The CefSharp Authors. All rights reserved. // // Use of this source code is governed by a BSD-style license that can be found in the LICENSE file. namespace CefSharp.Structs { /// <summary> /// Represents a rectangle /// </summary> public struct Rect { /// <summary> /// X coordinate /// </summary> public int X { get; private set; } /// <summary> /// Y coordinate /// </summary> public int Y { get; private set; } /// <summary> /// Width /// </summary> public int Width { get; private set; } /// <summary> /// Height /// </summary> public int Height { get; private set; } public Rect(int x, int y, int width, int height) : this() { X = x; Y = y; Width = width; Height = height; } } }
23.238095
100
0.469262
[ "Unlicense", "MIT" ]
Rex-22/OSIRTv2
packages/CefSharp.Common.65.0.0-pre01/src/CefSharp/Structs/Rect.cs
979
C#
using Newtonsoft.Json; namespace Nest { [JsonObject] public class CatAliasesRecord : ICatRecord { [JsonProperty("alias")] public string Alias { get; set; } [JsonProperty("index")] public string Index { get; set; } [JsonProperty("filter")] public string Filter { get; set; } [JsonProperty("routing.index")] public string IndexRouting { get; set; } [JsonProperty("routing.search")] public string SearchRouting { get; set; } } }
19.782609
43
0.683516
[ "Apache-2.0" ]
Entroper/elasticsearch-net
src/Nest/Domain/Cat/CatAliasesRecord.cs
457
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("SIPSorcery.XMPP.TestClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("Microsoft")] [assembly: AssemblyProduct("SIPSorcery.XMPP.TestClient")] [assembly: AssemblyCopyright("Copyright © Microsoft 2011")] [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("f361e44c-5ea1-4259-bbea-1cf0ecc05db9")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
39.972973
85
0.732252
[ "BSD-3-Clause" ]
Rehan-Mirza/sipsorcery
sipsorcery-xmpp/SIPSorcery.XMPP.TestClient/Properties/AssemblyInfo.cs
1,482
C#
using System; using System.Collections.Generic; using Sol2E.Utils; namespace Sol2E.Core { /// <summary> /// A logical representation of an entity (or game object). /// /// This class doesn't contain any fields except for one single identifier. /// However it does contain methods for data acccess as well as lifecycle, /// persistency, ownership and data management. /// The methods themself do not perform any actions, but wrap the functionality /// of the unterlying database to make it accessible in a way to be easily /// understood by clients. /// /// The behaviour of an entity is solely defined by the components it contains. /// As stated above, the entity actually does not contain any components, but they /// are associated to its id. These relations are managed by the database. /// </summary> [Serializable] public class Entity { #region Fields // identifier public int Id { get; private set; } #if DEBUG // reference to database. this is only used for debugging // to be able to inspect it with intellisense [NonSerialized] private Database _dbRef = Database.Instance; #endif #endregion #region Lifecycle Methods /// <summary> /// Creates a new instance of entity. /// </summary> /// <returns>new instance</returns> public static Entity Create() { return Database.Instance.EntityCreate(); } /// <summary> /// Destroys the given entity. /// </summary> /// <param name="entity">entity to destroy</param> public static void Destroy(Entity entity) { if (entity == null) return; // fire scene changed event. If entity doesn't belong to a scene, nothing happens. SceneChangedEvent.Invoke(entity.GetHostingScene(), SceneEventType.EntityRemoved, entity); Database.Instance.EntityDestroy(entity); } // private default constructor to hide it from everybody else private Entity() { } /// <summary> /// Internal constructor. Gets called by EntityCreate in Database. /// </summary> /// <param name="entityId">id assigned to this entity</param> internal Entity(int entityId) { Id = entityId; } #endregion #region Instance Access Methods /// <summary> /// Returns the entity instance associated with the given id. /// </summary> /// <param name="entityId">id of entity to get</param> /// <returns>entity associated with given id</returns> public static Entity GetInstance(int entityId) { return Database.Instance.EntityGetInstance(entityId); } /// <summary> /// Returns all entity instances which own a component of given type. /// </summary> /// <param name="componentType">type of required component</param> /// <returns>list of entitis wich own the required component</returns> public static IEnumerable<Entity> GetInstances(Type componentType) { return Database.Instance.EntityGetInstances(componentType); } /// <summary> /// Returns all entity instances which own all components of given types. /// </summary> /// <param name="componentTypes">list of types of required components</param> /// <returns>list of entitis wich own the required components</returns> public static IEnumerable<Entity> GetInstances(IEnumerable<Type> componentTypes) { return Database.Instance.EntityGetInstances(componentTypes); } /// <summary> /// Returns the number of entities in this game. /// </summary> /// <returns>number of entities</returns> public static int Count() { return Database.Instance.EntityCount; } /// <summary> /// Returns the number of entities in given scene. /// </summary> /// <param name="scene">scene to inspect</param> /// <returns>number of entities</returns> public static int Count(Scene scene) { return Database.Instance.EntityCountInScene(scene); } #endregion #region Persistency Methods /// <summary> /// Takes a snap shot of this entity and all its content. /// </summary> /// <returns>a snap shot of this entity</returns> public EntityState SaveState() { return Database.Instance.EntitySaveState(Id); } /// <summary> /// Restores this entity from a given snap shot. /// </summary> /// <param name="state">snap shot to restore entity from</param> public void RestoreState(EntityState state) { Database.Instance.EntityRestoreState(Id, state); } #endregion #region Ownership Methods /// <summary> /// Assigns this entity to given scene. /// </summary> /// <param name="scene">scene to assign this entity to</param> public void AssignToScene(Scene scene) { var oldScene = GetHostingScene(); if (oldScene == scene) return; SceneChangedEvent.Invoke(oldScene, SceneEventType.EntityRemoved, this); Database.Instance.EntityAssignToScene(Id, scene.Id); SceneChangedEvent.Invoke(scene, SceneEventType.EntityAdded, this); } /// <summary> /// Returns the scene this entity is currently assigned to. /// </summary> /// <returns>instance of hosting scene</returns> public Scene GetHostingScene() { int sceneId = Database.Instance.EntityGetIdOfHostingScene(Id); return (sceneId != IDPool.InvalidID) ? Scene.GetInstance(sceneId) : null; } /// <summary> /// Adds the given component to this entity. /// </summary> /// <param name="component">component to add</param> public void AddComponent(Component component) { if (Database.Instance.EntityHasComponent(Id, component.GetType())) throw new InvalidOperationException( string.Format("Entity {0} already contains a component of type {1}", Id, component.GetType().Name)); component.AssignToEntity(this); } #endregion #region Data Access Methods /// <summary> /// Predicate of a component of given type is existent within this entity. /// </summary> /// <typeparam name="T">component type parameter</typeparam> /// <returns>true if component is existent, else false</returns> public bool Has<T>() where T : Component { return Database.Instance.EntityHasComponent(Id, typeof(T)); } /// <summary> /// Returns the component of given type as T. /// (That way, its members can be directly accessed without casting.) /// </summary> /// <typeparam name="T">component type parameter</typeparam> /// <returns>component as T or null if not existent</returns> public T Get<T>() where T : Component { return Database.Instance.EntityGetComponent<T>(Id, typeof(T)); } /// <summary> /// Gets all components in this scene. /// </summary> /// <returns>all components in this scene</returns> public IEnumerable<Component> GetAll() { return Database.Instance.EntityGetAllComponents(Id); } #endregion } }
34.678112
102
0.574134
[ "MIT" ]
chriskapffer/Sol2E
source/Core/Entity.cs
8,082
C#
using System.IO; using System.Text; using IronRuby.Builtins; using Microsoft.Scripting.Hosting; using zlib; namespace Gemini { abstract class Ruby { private static ScriptRuntime _rubyRuntime; private static ScriptEngine _rubyEngine; private static ScriptScope _rubyScope; /// <summary> /// Creates instances of the Ruby engine and Ruby scope /// </summary> public static void CreateRuntime() { _rubyRuntime = IronRuby.Ruby.CreateRuntime(); _rubyEngine = IronRuby.Ruby.GetEngine(_rubyRuntime); _rubyScope = _rubyEngine.CreateScope(); _rubyEngine.Execute(@"load_assembly 'IronRuby.Libraries', 'IronRuby.StandardLibrary.Zlib'", _rubyScope); } public static byte[] MarshalDump(object data) { _rubyScope.SetVariable("data", data); MutableString result = _rubyEngine.Execute(@"Marshal.dump(data)", _rubyScope); _rubyScope.RemoveVariable("data"); return result.ToByteArray(); } public static object MarshalLoad(byte[] data) { _rubyScope.SetVariable("data", MutableString.CreateBinary(data)); object result = _rubyEngine.Execute(@"Marshal.load(data)", _rubyScope); _rubyScope.RemoveVariable("data"); return result; } /// <summary> /// Inflates the compressed string using Ruby's Zlib module /// </summary> /// <param name="data">The Ruby string to decompress</param> /// <returns>The decompressed Ruby string as a System.String</returns> public static string ZlibInflate(MutableString data) { _rubyScope.SetVariable("data", data); MutableString result = _rubyEngine.Execute(@"Zlib::Inflate.inflate(data)", _rubyScope); _rubyScope.RemoveVariable("data"); return ConvertString(result); } /// <summary> /// Deflate a string using zlib.net library since IronRuby's Deflate module is buggy, fuck /// </summary> /// <param name="data">The string to compress</param> /// <returns>The decompressed string as a Ruby string</returns> public static MutableString ZlibDeflate(string data) { using (MemoryStream outMemoryStream = new MemoryStream()) using (ZOutputStream outZStream = new ZOutputStream(outMemoryStream, zlibConst.Z_BEST_COMPRESSION)) { byte[] bytes = Encoding.UTF8.GetBytes(data); outZStream.Write(bytes, 0, bytes.Length); outZStream.finish(); return MutableString.CreateBinary(outMemoryStream.ToArray()); } } public static string ConvertString(MutableString rubyString) { return rubyString.ToString(Encoding.UTF8); } public static MutableString ConvertString(string csString) { return MutableString.Create(csString, RubyEncoding.UTF8); } } }
33.707317
110
0.68958
[ "MIT" ]
terabin/Gemini
src/classes/Ruby.cs
2,766
C#
using Cosmos.Core; using Cosmos.HAL.Network; using System; using System.Collections.Generic; using static Cosmos.Core.INTs; namespace Cosmos.HAL.Drivers.PCI.Network { public class RTL8139 : NetworkDevice { protected PCIDevice pciCard; protected MACAddress mac; protected bool mInitDone; protected ManagedMemoryBlock rxBuffer; protected int rxBufferOffset; protected ushort capr; protected Queue<byte[]> mRecvBuffer; protected Queue<byte[]> mTransmitBuffer; private int mNextTXDesc; const ushort RxBufferSize = 32768; private uint Base; public RTL8139(PCIDevice device) { if (device == null) { throw new ArgumentException("PCI Device is null. Unable to get Realtek 8139 card"); } pciCard = device; Base = device.BaseAddressBar[0].BaseAddress; // We are handling this device pciCard.Claimed = true; // Setup interrupt handling INTs.SetIrqHandler(device.InterruptLine, HandleNetworkInterrupt); // Get IO Address from PCI Bus // Enable the card pciCard.EnableDevice(); // Turn on the card OutB(Base + 0x52, 0x01); //Do a software reset SoftwareReset(); // Get the MAC Address byte[] eeprom_mac = new byte[6]; for (uint b = 0; b < 6; b++) { eeprom_mac[b] = Inb(Base + b); } this.mac = new MACAddress(eeprom_mac); // Get a receive buffer and assign it to the card rxBuffer = new ManagedMemoryBlock(RxBufferSize + 2048 + 16, 4); RBStartRegister = (uint)rxBuffer.Offset; // Setup receive Configuration RecvConfigRegister = 0xF381; // Setup Transmit Configuration TransmitConfigRegister = 0x3000300; // Setup Interrupts IntMaskRegister = 0x7F; IntStatusRegister = 0xFFFF; // Setup our Receive and Transmit Queues mRecvBuffer = new Queue<byte[]>(); mTransmitBuffer = new Queue<byte[]>(); } private static byte Inb(uint port) { return new IOPort((ushort)port).Byte; } private static void OutB(uint port, byte val) { new IOPort((ushort)port).Byte = val; } private static ushort Inb16(uint port) { return new IOPort((ushort)port).Word; } private static void Out16(uint port, ushort val) { new IOPort((ushort)port).Word = val; } private static uint Inb32(uint port) { return new IOPort((ushort)port).DWord; } private static void Out32(uint port, uint val) { new IOPort((ushort)port).DWord = val; } public static List<RTL8139> FindAll() { //Console.WriteLine("Scanning for Realtek 8139 cards..."); List<RTL8139> cards = new List<RTL8139>(); foreach (var xDevice in HAL.PCI.Devices) { if ((xDevice.VendorID == 0x10EC) && (xDevice.DeviceID == 0x8139) && (xDevice.Claimed == false)) { RTL8139 nic = new RTL8139(xDevice); cards.Add(nic); } } return cards; } protected void HandleNetworkInterrupt(ref IRQContext aContext) { ushort cur_status = IntStatusRegister; //Console.WriteLine("RTL8139 Interrupt: ISR=" + cur_status.ToString()); if ((cur_status & 0x01) != 0) { while ((CommandRegister & 0x01) == 0) { //UInt32 packetHeader = BitConverter.ToUInt32(rxBuffer, rxBufferOffset + capr); uint packetHeader = rxBuffer.Read32(capr); ushort packetLen = (ushort)(packetHeader >> 16); if ((packetHeader & 0x3E) != 0x00) { CommandRegister = 0x04; // TX Only; capr = CurBufferAddressRegister; CommandRegister = 0x0C; // RX and TX Enabled } else if ((packetHeader & 0x01) == 0x01) { ReadRawData(packetLen); } CurAddressPointerReadRegister = (ushort)(capr - 0x10); } } if ((cur_status & 0x10) != 0) { CurAddressPointerReadRegister = (ushort)(CurBufferAddressRegister - 0x10); cur_status = (ushort)(cur_status | 0x01); } IntStatusRegister = cur_status; } #region Register Access protected uint RBStartRegister { get { return Inb32(Base + 0x30); } set { Out32(Base + 0x30, value); } } internal uint RecvConfigRegister { get { return Inb32(Base + 0x44); } set { Out32(Base + 0x44, value); } } internal ushort CurAddressPointerReadRegister { get { return Inb16(Base + 0x38); } set { Out16(Base + 0x38, value); } } internal ushort CurBufferAddressRegister { get { return Inb16(Base + 0x3A); } set { Out16(Base + 0x3A, value); } } internal ushort IntMaskRegister { get { return Inb16(Base + 0x3C); } set { Out16(Base + 0x3C, value); } } internal ushort IntStatusRegister { get { return Inb16(Base + 0x3E); } set { Out16(Base + 0x3E, value); } } internal byte CommandRegister { get { return Inb(Base + 0x37); } set { OutB(Base + 0x37, value); } } protected byte MediaStatusRegister { get { return Inb(Base + 0x58); } set { OutB(Base + 0x58, value); } } protected byte Config1Register { get { return Inb(Base + 0x52); } set { OutB(Base + 0x52, value); } } internal uint TransmitConfigRegister { get { return Inb32(Base + 0x40); } set { Out32(Base + 0x40, value); } } internal uint TransmitAddress1Register { get { return Inb32(Base + 0x20); } set { Out32(Base + 0x20, value); } } internal uint TransmitAddress2Register { get { return Inb32(Base + 0x24); } set { Out32(Base + 0x24, value); } } internal uint TransmitAddress3Register { get { return Inb32(Base + 0x28); } set { Out32(Base + 0x28, value); } } internal uint TransmitAddress4Register { get { return Inb32(Base + 0x2C); } set { Out32(Base + 0x2C, value); } } internal uint TransmitDescriptor1Register { get { return Inb32(Base + 0x10); } set { Out32(Base + 0x10, value); } } internal uint TransmitDescriptor2Register { get { return Inb32(Base + 0x14); } set { Out32(Base + 0x14, value); } } internal uint TransmitDescriptor3Register { get { return Inb32(Base + 0x18); } set { Out32(Base + 0x18, value); } } internal uint TransmitDescriptor4Register { get { return Inb32(Base + 0x1C); } set { Out32(Base + 0x1C, value); } } #endregion protected bool CmdBufferEmpty { get { return ((CommandRegister & 0x01) == 0x01); } } #region Network Device Implementation public override MACAddress MACAddress { get { return this.mac; } } public override bool Enable() { // Enable Receiving and Transmitting of data CommandRegister = 0x0C; while (this.Ready == false) { } return true; } public override bool Ready { get { return ((Config1Register & 0x20) == 0); } } public override bool QueueBytes(byte[] buffer, int offset, int length) { byte[] data = new byte[length]; for (int b = 0; b < length; b++) { data[b] = buffer[b + offset]; } //Console.WriteLine("Try sending"); if (SendBytes(ref data) == false) { //Console.WriteLine("Queuing"); mTransmitBuffer.Enqueue(data); } return true; } public override bool ReceiveBytes(byte[] buffer, int offset, int max) { throw new NotImplementedException(); } public override byte[] ReceivePacket() { if (mRecvBuffer.Count < 1) { return null; } byte[] data = mRecvBuffer.Dequeue(); return data; } public override int BytesAvailable() { if (mRecvBuffer.Count < 1) { return 0; } return mRecvBuffer.Peek().Length; } public override bool IsSendBufferFull() { return false; } public override bool IsReceiveBufferFull() { return false; } public override string Name { get { return "Realtek 8139 Chipset NIC"; } } public override CardType CardType => CardType.Ethernet; #endregion #region Helper Functions private void ReadRawData(ushort packetLen) { int recv_size = packetLen - 4; byte[] recv_data = new byte[recv_size]; for (uint b = 0; b < recv_size; b++) { recv_data[b] = rxBuffer[(uint)(capr + 4 + b)]; } if (DataReceived != null) { DataReceived(recv_data); } else { if (mRecvBuffer == null) { } mRecvBuffer.Enqueue(recv_data); } capr += (ushort)((packetLen + 4 + 3) & 0xFFFFFFFC); if (capr > RxBufferSize) { capr -= RxBufferSize; } } protected void SoftwareReset() { CommandRegister = 0x10; while ((CommandRegister & 0x10) != 0) { } } protected bool SendBytes(ref byte[] aData) { int txd = mNextTXDesc++; if (mNextTXDesc >= 4) { mNextTXDesc = 0; } ManagedMemoryBlock txBuffer; if (aData.Length < 64) { txBuffer = new ManagedMemoryBlock(64); for (uint b = 0; b < aData.Length; b++) { txBuffer[b] = aData[b]; } } else { txBuffer = new ManagedMemoryBlock((uint)aData.Length); for (uint i = 0; i < aData.Length; i++) { txBuffer[i] = aData[i]; } } switch (txd) { case 0: TransmitAddress1Register = (uint)txBuffer.Offset; TransmitDescriptor1Register = txBuffer.Size; break; case 1: TransmitAddress2Register = (uint)txBuffer.Offset; TransmitDescriptor2Register = txBuffer.Size; break; case 2: TransmitAddress3Register = (uint)txBuffer.Offset; TransmitDescriptor3Register = txBuffer.Size; break; case 3: TransmitAddress4Register = (uint)txBuffer.Offset; TransmitDescriptor4Register = txBuffer.Size; break; default: return false; } return true; } #endregion } }
32.774869
111
0.48099
[ "BSD-3-Clause" ]
AsertCreator/Cosmos
source/Cosmos.HAL2/Drivers/PCI/Network/RTL8139.cs
12,522
C#
// Copyright © Tanner Gooding and Contributors. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from um/winioctl.h in the Windows SDK for Windows 10.0.19041.0 // Original source is Copyright © Microsoft. All rights reserved. using NUnit.Framework; using System.Runtime.InteropServices; namespace TerraFX.Interop.UnitTests { /// <summary>Provides validation of the <see cref="READ_USN_JOURNAL_DATA_V1" /> struct.</summary> public static unsafe class READ_USN_JOURNAL_DATA_V1Tests { /// <summary>Validates that the <see cref="READ_USN_JOURNAL_DATA_V1" /> struct is blittable.</summary> [Test] public static void IsBlittableTest() { Assert.That(Marshal.SizeOf<READ_USN_JOURNAL_DATA_V1>(), Is.EqualTo(sizeof(READ_USN_JOURNAL_DATA_V1))); } /// <summary>Validates that the <see cref="READ_USN_JOURNAL_DATA_V1" /> struct has the right <see cref="LayoutKind" />.</summary> [Test] public static void IsLayoutSequentialTest() { Assert.That(typeof(READ_USN_JOURNAL_DATA_V1).IsLayoutSequential, Is.True); } /// <summary>Validates that the <see cref="READ_USN_JOURNAL_DATA_V1" /> struct has the correct size.</summary> [Test] public static void SizeOfTest() { Assert.That(sizeof(READ_USN_JOURNAL_DATA_V1), Is.EqualTo(48)); } } }
40.361111
145
0.685478
[ "MIT" ]
Ethereal77/terrafx.interop.windows
tests/Interop/Windows/um/winioctl/READ_USN_JOURNAL_DATA_V1Tests.cs
1,455
C#
using System; namespace LightningPay { /// <summary> /// Exception thrown by LightningPay /// </summary> public class LightningPayException : Exception { /// <summary>Gets or sets the http status code.</summary> /// <value>The http status code.</value> public ErrorCode Code { get; set; } /// <summary>Gets or sets the response data.</summary> /// <value>The response data.</value> public string ResponseData { get; set; } /// <summary> /// Initializes a new instance of the <see cref="LightningPayException"/> class. /// </summary> public LightningPayException() { } /// <summary> /// Initializes a new instance of the <see cref="LightningPayException"/> class. /// </summary> /// <param name="message">The message that describes the error.</param> public LightningPayException(string message) : base(message) { } /// <summary>Initializes a new instance of the <see cref="LightningPayException" /> class.</summary> /// <param name="message">The message.</param> /// <param name="code">The code.</param> /// <param name="responseData">The response data.</param> /// <param name="innerException">The inner exception.</param> public LightningPayException(string message, ErrorCode code, string responseData = null, Exception innerException = null) : base(message, innerException) { this.Code = code; this.ResponseData = responseData; } /// <summary> /// Initializes a new instance of the <see cref="LightningPayException"/> class. /// </summary> /// <param name="message">The error message that explains the reason for the exception.</param> /// <param name="innerException">The exception that is the cause of the current exception, or a null reference (Nothing in Visual Basic) if no inner exception is specified.</param> public LightningPayException(string message, Exception innerException) : base(message, innerException) { } /// <summary> /// LightningPay error code /// </summary> public enum ErrorCode { /// <summary>Bad configuration</summary> BAD_CONFIGURATION, /// <summary>Unauthorized Access</summary> UNAUTHORIZED, /// <summary>Bad request</summary> BAD_REQUEST, /// <summary>Internal error</summary> INTERNAL_ERROR } } }
36.027027
188
0.586272
[ "MIT" ]
khan202122/LightningPay
src/LightningPay.Abstractions/Model/Exception/LightningPayException.cs
2,668
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. using System; using System.IO; using System.Net.Http; using Microsoft.Identity.Client; using Microsoft.Identity.Client.Core; using Microsoft.Identity.Client.Instance; using Microsoft.Identity.Test.Common; using Microsoft.Identity.Test.Common.Core.Mocks; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Identity.Test.Unit.CoreTests.InstanceTests { [TestClass] [DeploymentItem("Resources\\OpenidConfiguration-B2C.json")] [DeploymentItem("Resources\\OpenidConfiguration-B2CLogin.json")] public class B2CAuthorityTests : TestBase { [TestMethod] public void NotEnoughPathSegmentsTest() { try { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); var instance = Authority.CreateAuthority(serviceBundle, "https://login.microsoftonline.in/tfp/"); Assert.IsNotNull(instance); Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.B2C); var resolver = new AuthorityEndpointResolutionManager(serviceBundle); var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, null, new RequestContext(serviceBundle, Guid.NewGuid())) .GetAwaiter().GetResult(); Assert.Fail("test should have failed"); } catch (Exception exc) { Assert.IsInstanceOfType(exc, typeof(ArgumentException)); Assert.AreEqual(MsalErrorMessage.B2cAuthorityUriInvalidPath, exc.Message); } } [TestMethod] public void TenantTest() { AuthorityTestHelper.AuthorityDoesNotUpdateTenant( "https://sometenantid.b2clogin.com/tfp/sometenantid/policy/", "sometenantid"); AuthorityTestHelper.AuthorityDoesNotUpdateTenant( "https://catsareamazing.com/tfp/catsareamazing/policy/", "catsareamazing"); AuthorityTestHelper.AuthorityDoesNotUpdateTenant( "https://sometenantid.b2clogin.de/tfp/tid/policy/", "tid"); } [TestMethod] public void B2CLoginAuthorityCreateAuthority() { using (var httpManager = new MockHttpManager()) { var appConfig = new ApplicationConfiguration() { HttpManager = httpManager, AuthorityInfo = AuthorityInfo.FromAuthorityUri(TestConstants.B2CLoginAuthority, false) }; var serviceBundle = ServiceBundle.Create(appConfig); // add mock response for tenant endpoint discovery httpManager.AddMockHandler( new MockHttpMessageHandler { ExpectedMethod = HttpMethod.Get, ExpectedUrl = "https://sometenantid.b2clogin.com/tfp/sometenantid/policy/v2.0/.well-known/openid-configuration", ResponseMessage = MockHelpers.CreateSuccessResponseMessage( File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("OpenidConfiguration-B2CLogin.json"))) }); Authority instance = Authority.CreateAuthority( serviceBundle, TestConstants.B2CLoginAuthority); Assert.IsNotNull(instance); Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.B2C); var resolver = new AuthorityEndpointResolutionManager(serviceBundle); var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, null, new RequestContext(serviceBundle, Guid.NewGuid())) .GetAwaiter().GetResult(); Assert.AreEqual( "https://sometenantid.b2clogin.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/policy/oauth2/v2.0/authorize", endpoints.AuthorizationEndpoint); Assert.AreEqual( "https://sometenantid.b2clogin.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/policy/oauth2/v2.0/token", endpoints.TokenEndpoint); Assert.AreEqual("https://sometenantid.b2clogin.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/v2.0/", endpoints.SelfSignedJwtAudience); } } [TestMethod] [Ignore] // https://github.com/AzureAD/microsoft-authentication-library-for-dotnet/issues/1038 public void B2CMicrosoftOnlineCreateAuthority() { using (var harness = CreateTestHarness()) { // add mock response for tenant endpoint discovery harness.HttpManager.AddMockHandler( new MockHttpMessageHandler { ExpectedMethod = HttpMethod.Get, ExpectedUrl = "https://login.microsoftonline.com/tfp/mytenant.com/my-policy/v2.0/.well-known/openid-configuration", ResponseMessage = MockHelpers.CreateSuccessResponseMessage( File.ReadAllText(ResourceHelper.GetTestResourceRelativePath("OpenidConfiguration-B2C.json"))) }); Authority instance = Authority.CreateAuthority( harness.ServiceBundle, "https://login.microsoftonline.com/tfp/mytenant.com/my-policy/"); Assert.IsNotNull(instance); Assert.AreEqual(instance.AuthorityInfo.AuthorityType, AuthorityType.B2C); var resolver = new AuthorityEndpointResolutionManager(harness.ServiceBundle); var endpoints = resolver.ResolveEndpointsAsync( instance.AuthorityInfo, null, new RequestContext(harness.ServiceBundle, Guid.NewGuid())) .GetAwaiter().GetResult(); Assert.AreEqual( "https://login.microsoftonline.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/my-policy/oauth2/v2.0/authorize", endpoints.AuthorizationEndpoint); Assert.AreEqual( "https://login.microsoftonline.com/6babcaad-604b-40ac-a9d7-9fd97c0b779f/my-policy/oauth2/v2.0/token", endpoints.TokenEndpoint); Assert.AreEqual("https://sts.windows.net/6babcaad-604b-40ac-a9d7-9fd97c0b779f/", endpoints.SelfSignedJwtAudience); } } [TestMethod] public void CanonicalAuthorityInitTest() { var serviceBundle = TestCommon.CreateDefaultServiceBundle(); const string UriNoPort = TestConstants.B2CAuthority; const string UriNoPortTailSlash = TestConstants.B2CAuthority; const string UriDefaultPort = "https://login.microsoftonline.in:443/tfp/tenant/policy"; const string UriCustomPort = "https://login.microsoftonline.in:444/tfp/tenant/policy"; const string UriCustomPortTailSlash = "https://login.microsoftonline.in:444/tfp/tenant/policy/"; const string UriVanityPort = TestConstants.B2CLoginAuthority; var authority = new B2CAuthority(serviceBundle, new AuthorityInfo(AuthorityType.B2C, UriNoPort, true)); Assert.AreEqual(UriNoPortTailSlash, authority.AuthorityInfo.CanonicalAuthority); authority = new B2CAuthority(serviceBundle, new AuthorityInfo(AuthorityType.B2C, UriDefaultPort, true)); Assert.AreEqual(UriNoPortTailSlash, authority.AuthorityInfo.CanonicalAuthority); authority = new B2CAuthority(serviceBundle, new AuthorityInfo(AuthorityType.B2C, UriCustomPort, true)); Assert.AreEqual(UriCustomPortTailSlash, authority.AuthorityInfo.CanonicalAuthority); authority = new B2CAuthority(serviceBundle, new AuthorityInfo(AuthorityType.B2C, UriVanityPort, true)); Assert.AreEqual(UriVanityPort, authority.AuthorityInfo.CanonicalAuthority); } } }
47.591954
145
0.623596
[ "MIT" ]
davidjohnoliver/microsoft-authentication-library-for-dotnet
tests/Microsoft.Identity.Test.Unit.net45/CoreTests/InstanceTests/B2cAuthorityTests.cs
8,283
C#
using GeometricAlgebraNumericsLib.Exceptions; using GeometricAlgebraNumericsLib.Maps.Bilinear; using GeometricAlgebraNumericsLib.Multivectors.Numeric; using GeometricAlgebraNumericsLib.Multivectors.Numeric.Factories; using GeometricAlgebraStructuresLib.Frames; namespace GeometricAlgebraNumericsLib.Products.Euclidean { public sealed class GaNumEuclideanLcp : GaNumBilinearProductEuclidean { public override GaNumSarMultivector this[GaNumSarMultivector mv1, GaNumSarMultivector mv2] { get { if (mv1.GaSpaceDimension != DomainGaSpaceDimension || mv2.GaSpaceDimension != DomainGaSpaceDimension2) throw new GaNumericsException("Multivector size mismatch"); return mv1.GetGbtELcpTerms(mv2).SumAsSarMultivector(TargetVSpaceDimension); } } public override GaNumDgrMultivector this[GaNumDgrMultivector mv1, GaNumDgrMultivector mv2] { get { if (mv1.GaSpaceDimension != DomainGaSpaceDimension || mv2.GaSpaceDimension != DomainGaSpaceDimension2) throw new GaNumericsException("Multivector size mismatch"); return mv1.GetGbtELcpTerms(mv2).SumAsDgrMultivector(TargetVSpaceDimension); } } internal GaNumEuclideanLcp(int targetVSpaceDim) : base(targetVSpaceDim, GaNumMapBilinearAssociativity.NoneAssociative) { } public override GaNumTerm MapToTerm(ulong id1, ulong id2) { return GaNumTerm.Create( TargetVSpaceDimension, id1 ^ id2, GaFrameUtils.IsNonZeroELcp(id1, id2) ? (GaFrameUtils.IsNegativeEGp(id1, id2) ? -1.0d : 1.0d) : 0.0d ); } } }
36.156863
118
0.649675
[ "MIT" ]
ga-explorer/GMac
GeometricAlgebraNumericsLib/GeometricAlgebraNumericsLib/Products/Euclidean/GaNumEuclideanLcp.cs
1,846
C#
using GraphQLDotNet.Mobile.ViewModels; namespace GraphQLDotNet.Mobile.OpenWeather.Persistence { internal sealed class WeatherLocations { public WeatherSummaryViewModel[] WeatherSummaries { get; set; } = new WeatherSummaryViewModel[0]; } }
26.1
105
0.754789
[ "MIT" ]
Sankra/GraphQLDotNet
src/Mobile/GraphQLDotNet.Mobile/OpenWeather/Persistence/WeatherLocations.cs
263
C#
// ---------------------------------------------------------------------------------------------------------------------- // Author: Tanveer Yousuf (@tanveery) // ---------------------------------------------------------------------------------------------------------------------- // Copyright © Ejyle Technologies (P) Ltd. All rights reserved. // Licensed under the MIT license. See the LICENSE file in the project's root directory for complete license information. // ---------------------------------------------------------------------------------------------------------------------- using Ejyle.DevAccelerate.Core; using System; namespace Ejyle.DevAccelerate.EnterpriseSecurity.Subscriptions { public interface IDaSubscriptionFeatureUser<TKey> : IDaEntity<TKey> where TKey : IEquatable<TKey> { TKey SubscriptionFeatureId { get; set; } TKey UserId { get; set; } bool IsEnabled { get; set; } } }
41.304348
122
0.436842
[ "MIT" ]
devaccelerate/DevAccelerateNet
src/EnterpriseSecurity/Ejyle.DevAccelerate.EnterpriseSecurity/Subscriptions/IDaSubscriptionFeatureUser.cs
953
C#
using Mono.Cecil; using System; namespace SoftCube.Aspects { /// <summary> /// パラメーターレベルアスペクト。 /// </summary> public abstract class ParameterLevelAspect : Attribute { #region コンストラクター /// <summary> /// コンストラクター。 /// </summary> public ParameterLevelAspect() { } #endregion #region メソッド /// <summary> /// アドバイスを注入します。 /// </summary> /// <param name="parameter">ターゲットパラメーター。</param> protected abstract void InjectAdvice(ParameterDefinition parameter); #endregion } }
18.636364
76
0.544715
[ "MIT" ]
kenjiro-yamasaki/Aspect
Aspects/Attributes/ParameterLevelAspect.cs
737
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.SceneManagement; public class LevelLoadTrigger : MonoBehaviour { public string levelToLoad; public Vector3 startingPoint; private void OnTriggerEnter2D(Collider2D collision) { if(collision.gameObject.tag != "Player") { return; } PlayerManager.Instance.PlayerEquipment.gameObject.GetComponent<Transform>().position = startingPoint; SceneManager.LoadScene(levelToLoad); } }
24.727273
109
0.715074
[ "CC0-1.0" ]
MufasaDoodle/GMD-Project
Assets/Scripts/Misc/LevelLoadTrigger.cs
544
C#
using System; using System.Collections; using c = Far.Core; namespace Far.Data { public class UserLogTableGetRecordsByAccountP : c.AbstractDataTable { #region static IDataField IdField public static c.IDataField IdField { get { return new IdFieldClass(); } } #endregion #region static IDataField UserIdField public static c.IDataField UserIdField { get { return new UserIdFieldClass(); } } #endregion #region static IDataField CreatedField public static c.IDataField CreatedField { get { return new CreatedFieldClass(); } } #endregion #region static IDataField User_FullNameField public static c.IDataField User_FullNameField { get { return new User_FullNameFieldClass(); } } #endregion #region static IDataField SelectedField public static c.IDataField SelectedField { get { return new SelectedRecord(); } } #endregion #region constructor public UserLogTableGetRecordsByAccountP(ArrayList rows, int totalCount) : base(rows, totalCount) {} #endregion #region int FieldCount public override int FieldCount { get { return 4; } } #endregion #region UserLogRowGetRecordsByAccountP this[int row] public UserLogRowGetRecordsByAccountP this[int row] { get { return (UserLogRowGetRecordsByAccountP)Rows[row]; } } #endregion #region private private class IdFieldClass : c.IDataField { public string DataField { get { return "Id"; } } public string SortExpression { get { return "UserLog.Id"; } } public string Display { get { return "Id"; } } } private class UserIdFieldClass : c.IDataField { public string DataField { get { return "UserId"; } } public string SortExpression { get { return "UserLog.UserId"; } } public string Display { get { return "UserId"; } } } private class CreatedFieldClass : c.IDataField { public string DataField { get { return "Created"; } } public string SortExpression { get { return "UserLog.Created"; } } public string Display { get { return "Created"; } } } private class User_FullNameFieldClass : c.IDataField { public string DataField { get { return "User_FullName"; } } public string SortExpression { get { return "LastName"; } } public string Display { get { return "User"; } } } private class SelectedRecord : c.IDataField { public string DataField { get { return "Selected"; } } public string SortExpression { get { return "Selected"; } } public string Display { get { return "Selected"; } } } #endregion } public class UserLogRowGetRecordsByAccountP : c.IDataRow { #region int Id public int Id { get { return id; } set { id = value; } } #endregion #region int UserId public int UserId { get { return userId; } set { userId = value; } } #endregion #region DateTime Created public DateTime Created { get { return created; } set { created = value; } } #endregion #region string User_FullName public string User_FullName { get { return user_FullName; } set { user_FullName = value; } } #endregion #region bool Selected public bool Selected { get { return selected; } set { selected = value; } } #endregion #region private private int id; private int userId; private DateTime created; private string user_FullName; private bool selected; #endregion } }
25.79845
115
0.698618
[ "MIT" ]
ic4f/codegenerator
demo/generated_code/uni_accounts.cs/UserLogTableGetRecordsByAccountP.cs
3,328
C#
using System; using System.Net.Http; using XFArchitecture.Core.Utilities; using XFArchitecture.Core.Contracts.Repository; namespace XFArchitecture.Core.Services.Repository { public class RepositoryService : IRepositoryService { public RepositoryService() { } } }
18.875
55
0.718543
[ "MIT" ]
JosueDM94/XFArchitecture
XFArchitecture.Core/Services/Repository/RepositoryService.cs
304
C#
using System; using Ayehu.Sdk.ActivityCreation.Interfaces; using Ayehu.Sdk.ActivityCreation.Extension; using Ayehu.Sdk.ActivityCreation.Helpers; using System.Net; using System.Net.Http; using System.Text; using System.Collections.Generic; namespace Ayehu.Github { public class GH_List_users : IActivityAsync { public string Jsonkeypath = "users"; public string Accept = ""; public string password1 = ""; public string Username = ""; public string since = ""; public string per_page = ""; private bool omitJsonEmptyorNull = true; private string contentType = "application/json"; private string endPoint = "https://api.github.com"; private string httpMethod = "GET"; private string _uriBuilderPath; private string _postData; private System.Collections.Generic.Dictionary<string, string> _headers; private System.Collections.Generic.Dictionary<string, string> _queryStringArray; private string uriBuilderPath { get { if (string.IsNullOrEmpty(_uriBuilderPath)) { _uriBuilderPath = "/users"; } return _uriBuilderPath; } set { this._uriBuilderPath = value; } } private string postData { get { if (string.IsNullOrEmpty(_postData)) { _postData = ""; } return _postData; } set { this._postData = value; } } private System.Collections.Generic.Dictionary<string, string> headers { get { if (_headers == null) { _headers = new Dictionary<string, string>() { {"User-Agent","" + Username},{"Accept",Accept},{"authorization","token " + password1} }; } return _headers; } set { this._headers = value; } } private System.Collections.Generic.Dictionary<string, string> queryStringArray { get { if (_queryStringArray == null) { _queryStringArray = new Dictionary<string, string>() { {"since",since},{"per_page",per_page} }; } return _queryStringArray; } set { this._queryStringArray = value; } } public GH_List_users() { } public GH_List_users(string Jsonkeypath, string Accept, string password1, string Username, string since, string per_page) { this.Jsonkeypath = Jsonkeypath; this.Accept = Accept; this.password1 = password1; this.Username = Username; this.since = since; this.per_page = per_page; } public async System.Threading.Tasks.Task<ICustomActivityResult> Execute() { HttpClient client = new HttpClient(); ServicePointManager.Expect100Continue = true; ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12; ServicePointManager.ServerCertificateValidationCallback = new System.Net.Security.RemoteCertificateValidationCallback(AcceptAllCertifications); UriBuilder UriBuilder = new UriBuilder(endPoint); UriBuilder.Path = uriBuilderPath; UriBuilder.Query = AyehuHelper.queryStringBuilder(queryStringArray); HttpRequestMessage myHttpRequestMessage = new HttpRequestMessage(new HttpMethod(httpMethod), UriBuilder.ToString()); if (contentType == "application/x-www-form-urlencoded") myHttpRequestMessage.Content = AyehuHelper.formUrlEncodedContent(postData); else if (string.IsNullOrEmpty(postData) == false) if (omitJsonEmptyorNull) myHttpRequestMessage.Content = new StringContent(AyehuHelper.omitJsonEmptyorNull(postData), Encoding.UTF8, "application/json"); else myHttpRequestMessage.Content = new StringContent(postData, Encoding.UTF8, contentType); foreach (KeyValuePair<string, string> headeritem in headers) client.DefaultRequestHeaders.Add(headeritem.Key, headeritem.Value); HttpResponseMessage response = client.SendAsync(myHttpRequestMessage).Result; switch (response.StatusCode) { case HttpStatusCode.NoContent: case HttpStatusCode.Created: case HttpStatusCode.Accepted: case HttpStatusCode.OK: { if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false) return this.GenerateActivityResult(response.Content.ReadAsStringAsync().Result, Jsonkeypath); else return this.GenerateActivityResult("Success"); } default: { if (string.IsNullOrEmpty(response.Content.ReadAsStringAsync().Result) == false) throw new Exception(response.Content.ReadAsStringAsync().Result); else if (string.IsNullOrEmpty(response.ReasonPhrase) == false) throw new Exception(response.ReasonPhrase); else throw new Exception(response.StatusCode.ToString()); } } } public bool AcceptAllCertifications(object sender, System.Security.Cryptography.X509Certificates.X509Certificate certification, System.Security.Cryptography.X509Certificates.X509Chain chain, System.Net.Security.SslPolicyErrors sslPolicyErrors) { return true; } } }
34.969136
251
0.61218
[ "MIT" ]
Ayehu/custom-activities
Github/users/GH List users/GH List users.cs
5,665
C#
using System; using System.Web; namespace IpData.Helpers.Extensions { internal static class UriExtenstions { public static Uri AddParameter(this Uri url, string paramName, string paramValue) { var uriBuilder = new UriBuilder(url); var query = HttpUtility.ParseQueryString(string.Empty); query[paramName] = paramValue; uriBuilder.Query = query.ToString(); return uriBuilder.Uri; } } }
26.777778
89
0.630705
[ "MIT" ]
drozhkov/IpData
src/IpData/Helpers/Extensions/UriExtenstions.cs
484
C#
/* * This message is auto generated by ROS#. Please DO NOT modify. * Note: * - Comments from the original code will be written in their own line * - Variable sized arrays will be initialized to array of size 0 * Please report any issues at * <https://github.com/siemens/ros-sharp> */ namespace RosSharp.RosBridgeClient.MessageTypes.Nav { public class GetMapResponse : Message { public const string RosMessageName = "nav_msgs/GetMap"; public OccupancyGrid map { get; set; } public GetMapResponse() { this.map = new OccupancyGrid(); } public GetMapResponse(OccupancyGrid map) { this.map = map; } } }
24.62069
71
0.628852
[ "Apache-2.0" ]
1441048907/ros-sharp
Libraries/RosBridgeClient/MessageTypes/Nav/srv/GetMapResponse.cs
714
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using CommonsPattern; // DEPRECATED // Use Living Zone in the complementary area instead, to allow big objects to be cleaned up // after completely leaving the screen public class DeadZone : MonoBehaviour { private void OnTriggerEnter2D(Collider2D other) { var pooledObject = other.GetComponent<IPooledObject>(); pooledObject?.Release(); } }
25.055556
91
0.747228
[ "MIT" ]
hsandt/dragon-raid
Assets/Scripts/InGame/DeadZone/DeadZone.cs
451
C#
using System; namespace EventStore.Projections.Core.Services.Processing { public class ResultWriter : IResultWriter { private readonly IResultEventEmitter _resultEventEmitter; private readonly IEmittedEventWriter _coreProjectionCheckpointManager; private readonly bool _producesRunningResults; private readonly CheckpointTag _zeroCheckpointTag; private readonly string _partitionCatalogStreamName; public ResultWriter( IResultEventEmitter resultEventEmitter, IEmittedEventWriter coreProjectionCheckpointManager, bool producesRunningResults, CheckpointTag zeroCheckpointTag, string partitionCatalogStreamName) { _resultEventEmitter = resultEventEmitter; _coreProjectionCheckpointManager = coreProjectionCheckpointManager; _producesRunningResults = producesRunningResults; _zeroCheckpointTag = zeroCheckpointTag; _partitionCatalogStreamName = partitionCatalogStreamName; } public void WriteEofResult( Guid subscriptionId, string partition, string resultBody, CheckpointTag causedBy, Guid causedByGuid, string correlationId) { if (resultBody != null) WriteResult(partition, resultBody, causedBy, causedByGuid, correlationId); } public void WritePartitionMeasured(Guid subscriptionId, string partition, int size) { // intentionally does nothing } private void WriteResult( string partition, string resultBody, CheckpointTag causedBy, Guid causedByGuid, string correlationId) { var resultEvents = ResultUpdated(partition, resultBody, causedBy); if (resultEvents != null) _coreProjectionCheckpointManager.EventsEmitted(resultEvents, causedByGuid, correlationId); } public void WriteRunningResult(EventProcessedResult result) { if (!_producesRunningResults) return; var oldState = result.OldState; var newState = result.NewState; var resultBody = newState.Result; if (oldState.Result != resultBody) { var partition = result.Partition; var causedBy = newState.CausedBy; WriteResult( partition, resultBody, causedBy, result.CausedBy, result.CorrelationId); } } private EmittedEventEnvelope[] ResultUpdated(string partition, string result, CheckpointTag causedBy) { return _resultEventEmitter.ResultUpdated(partition, result, causedBy); } protected EmittedEventEnvelope[] RegisterNewPartition(string partition, CheckpointTag at) { return new[] { new EmittedEventEnvelope( new EmittedDataEvent( _partitionCatalogStreamName, Guid.NewGuid(), "$partition", false, partition, null, at, null)) }; } public void AccountPartition(EventProcessedResult result) { if (_producesRunningResults) if (result.Partition != "" && result.OldState.CausedBy == _zeroCheckpointTag) { var resultEvents = RegisterNewPartition(result.Partition, result.CheckpointTag); if (resultEvents != null) _coreProjectionCheckpointManager.EventsEmitted( resultEvents, Guid.Empty, correlationId: null); } } public void EventsEmitted( EmittedEventEnvelope[] scheduledWrites, Guid causedBy, string correlationId) { _coreProjectionCheckpointManager.EventsEmitted( scheduledWrites, causedBy, correlationId); } public void WriteProgress(Guid subscriptionId, float progress) { // intentionally does nothing } } }
39.862745
113
0.630349
[ "Apache-2.0" ]
bartelink/EventStore
src/EventStore.Projections.Core/Services/Processing/ResultWriter.cs
4,066
C#
// Copyright (c) Microsoft Open Technologies, Inc. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System.Collections.Generic; using System.Collections.Immutable; using System.Diagnostics; using Microsoft.CodeAnalysis.CSharp.Symbols; using Microsoft.CodeAnalysis.CSharp.Syntax; using Roslyn.Utilities; namespace Microsoft.CodeAnalysis.CSharp { /// <summary> /// A binder that knows no symbols and will not delegate further. /// </summary> internal partial class BuckStopsHereBinder : Binder { internal BuckStopsHereBinder(CSharpCompilation compilation) : base(compilation) { } public override ConsList<LocalSymbol> ImplicitlyTypedLocalsBeingBound { get { return ConsList<LocalSymbol>.Empty; } } internal override ConsList<Imports> ImportsList { get { return ConsList<Imports>.Empty; } } protected override SourceLocalSymbol LookupLocal(SyntaxToken nameToken) { return null; } internal override bool IsAccessible(Symbol symbol, TypeSymbol accessThroughType, out bool failedThroughTypeCheck, ref HashSet<DiagnosticInfo> useSiteDiagnostics, ConsList<Symbol> basesBeingResolved = null) { failedThroughTypeCheck = false; return this.IsSymbolAccessibleConditional(symbol, Compilation.Assembly, ref useSiteDiagnostics); } internal override ConstantFieldsInProgress ConstantFieldsInProgress { get { return ConstantFieldsInProgress.Empty; } } internal override ConsList<FieldSymbol> FieldsBeingBound { get { return ConsList<FieldSymbol>.Empty; } } internal override LocalSymbol LocalInProgress { get { return null; } } protected override bool IsUnboundTypeAllowed(GenericNameSyntax syntax) { return false; } internal override bool IsDirectlyInIterator { get { return false; } } internal override bool IsIndirectlyInIterator { get { return false; } } internal override GeneratedLabelSymbol BreakLabel { get { return null; } } internal override GeneratedLabelSymbol ContinueLabel { get { return null; } } // This should only be called in the context of syntactically incorrect programs. In other // contexts statements are surrounded by some enclosing method or lambda. internal override TypeSymbol GetIteratorElementType(YieldStatementSyntax node, DiagnosticBag diagnostics) { // There's supposed to be an enclosing method or lambda. throw ExceptionUtilities.Unreachable; } internal override Symbol ContainingMemberOrLambda { get { return null; } } internal override Binder GetBinder(CSharpSyntaxNode node) { return null; } internal override ImmutableArray<LocalSymbol> GetDeclaredLocalsForScope(CSharpSyntaxNode node) { throw ExceptionUtilities.Unreachable; } internal override BoundStatement BindSwitchExpressionAndSections(SwitchStatementSyntax node, Binder originalBinder, DiagnosticBag diagnostics) { // There's supposed to be a SwitchBinder (or other overrider of this method) in the chain. throw ExceptionUtilities.Unreachable; } internal override BoundForStatement BindForParts(DiagnosticBag diagnostics, Binder originalBinder) { // There's supposed to be a ForLoopBinder (or other overrider of this method) in the chain. throw ExceptionUtilities.Unreachable; } internal override BoundStatement BindForEachParts(DiagnosticBag diagnostics, Binder originalBinder) { // There's supposed to be a ForEachLoopBinder (or other overrider of this method) in the chain. throw ExceptionUtilities.Unreachable; } internal override BoundWhileStatement BindWhileParts(DiagnosticBag diagnostics, Binder originalBinder) { // There's supposed to be a WhileBinder (or other overrider of this method) in the chain. throw ExceptionUtilities.Unreachable; } internal override BoundDoStatement BindDoParts(DiagnosticBag diagnostics, Binder originalBinder) { // There's supposed to be a WhileBinder (or other overrider of this method) in the chain. throw ExceptionUtilities.Unreachable; } internal override BoundStatement BindUsingStatementParts(DiagnosticBag diagnostics, Binder originalBinder) { // There's supposed to be a UsingStatementBinder (or other overrider of this method) in the chain. throw ExceptionUtilities.Unreachable; } internal override BoundStatement BindLockStatementParts(DiagnosticBag diagnostics, Binder originalBinder) { // There's supposed to be a LockBinder (or other overrider of this method) in the chain. throw ExceptionUtilities.Unreachable; } internal override BoundIfStatement BindIfParts(DiagnosticBag diagnostics, Binder originalBinder) { // There's supposed to be a IfBinder (or other overrider of this method) in the chain. throw ExceptionUtilities.Unreachable; } internal override ImmutableArray<LocalSymbol> Locals { get { // There's supposed to be a LocalScopeBinder (or other overrider of this method) in the chain. throw ExceptionUtilities.Unreachable; } } internal override ImmutableArray<LabelSymbol> Labels { get { // There's supposed to be a LocalScopeBinder (or other overrider of this method) in the chain. throw ExceptionUtilities.Unreachable; } } internal override ImmutableHashSet<Symbol> LockedOrDisposedVariables { get { return ImmutableHashSet.Create<Symbol>(); } } } }
32.835749
213
0.614389
[ "Apache-2.0" ]
semihokur/pattern-matching-csharp
Src/Compilers/CSharp/Portable/Binder/BuckStopsHereBinder.cs
6,799
C#