content
stringlengths
5
1.04M
avg_line_length
float64
1.75
12.9k
max_line_length
int64
2
244k
alphanum_fraction
float64
0
0.98
licenses
list
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
using System; using System.Collections.Generic; using System.Linq; using System.Reflection; using Voodoo.CodeGeneration.Models.Reflection; using Voodoo.CodeGeneration.Models.VisualStudio; using Voodoo.Infrastructure.Notations; namespace Voodoo.CodeGeneration.Helpers { public class MappingFactory { private List<Mapping> mappings; private TypeFacade type; private ProjectFacade[] projects; private List<Type> includedTypes = new List<Type>(); private List<string> includedTypeNames = new List<string>(); public MappingFactory(TypeFacade type, params ProjectFacade[] projects) { this.type = type; this.projects = projects; } private void addMapping(TypeFacade messageType, List<GeneratedProperty> properties, string name) { if (messageType != null && includedTypes.Contains(messageType.SystemType)) return; if (name != null && includedTypeNames.Contains(name)) return; if (messageType == null) mappings.Add(new Mapping(type, properties, name)); else mappings.Add(new Mapping(type, messageType, name)); includedTypes.AddIfNotNull(messageType?.SystemType); includedTypeNames.AddIfNotNull(name); } public static List<Mapping> GetMappings(TypeFacade type, params ProjectFacade[] projects) { return new MappingFactory(type, projects).Build(); } public List<Mapping> Build() { mappings = new List<Mapping>(); var projectMappings = projects.SelectMany(c=>c.MappingTypes).Distinct().ToArray(); foreach (var map in projectMappings) { var attribute = map.GetCustomAttribute<MapsToAttribute>(); if (attribute.Type.FullName == type.SystemType.FullName) { var facade = new TypeFacade(map); mappings.Add(new Mapping(type, facade, type.Name)); includedTypes.Add(map); includedTypeNames.Add(map.FullName); } } var messageType = Vs.Helper.FindType(type.RowMessageName); var properties = messageType == null ? type.MessageProperties : messageType.buildGeneratedProperty(messageType.Properties.ToList()); addMapping(messageType, properties, type.RowMessageName); var detailType = Vs.Helper.FindType(type.DetailMessageName); properties = detailType == null ? type.DetailMessageProperties : detailType.buildGeneratedProperty(detailType.Properties.ToList()); addMapping(detailType, properties, type.DetailMessageName); return mappings; } public class Mapping { public string ModelTypeName { get; set; } public string MessageTypeName { get; set; } public string Namespace { get; set; } public PropertyFacade[] Properties { get; set; } public PropertyFacade[] PropertiesWithoutId { get; set; } public Mapping(TypeFacade entity, TypeFacade message, string name = null) { ModelTypeName = entity.Name; MessageTypeName = message.Name; name = name ?? message.Name; var properties = new TypeComparer(entity, message); Properties = properties.ScalarProperties; PropertiesWithoutId = properties.ScalarPropertiesWithoutId; Namespace = message.SystemType.Namespace; } public Mapping(TypeFacade entity, List<GeneratedProperty> messageProperties, string name) { ModelTypeName = entity.Name; MessageTypeName = name; Properties = messageProperties.Select(c => c.Property).ToArray(); PropertiesWithoutId = messageProperties.Select(c => c.Property).Where(c => c.Name != "Id").ToArray(); } } } }
38.935185
117
0.593817
[ "MIT" ]
MiniverCheevy/spa-starter-kit
dev-tools/Voodoo.CodeGeneration/Helpers/MappingFactory.cs
4,205
C#
using Itinero.LocalGeo; using Xunit; namespace Itinero.VectorTiles.Test { public class LocalGeoExtensionsTests { /// <summary> /// Tests the intersections of the line. /// </summary> [Fact] public void LineSegmentIntersectionTests() { // double segments. var segment1 = new Line(new Coordinate(0, 0), new Coordinate(5, 0)); var segment2 = new Line(new Coordinate(0, 0), new Coordinate(0, 5)); var segment3 = new Line(new Coordinate(0, 3), new Coordinate(3, 0)); var segment4 = new Line(new Coordinate(1, 1), new Coordinate(2, 2)); var segment5 = new Line(new Coordinate(3, 3), new Coordinate(4, 4)); var segment6 = new Line(new Coordinate(3, 1), new Coordinate(3, -1)); var primitive = segment1.Intersection(segment2, true); Assert.NotNull(primitive); Assert.Equal(0, primitive.Value.Latitude); Assert.Equal(0, primitive.Value.Longitude); primitive = segment1.Intersection(segment3, true); Assert.NotNull(primitive); //Assert.AreEqual(new PointF2D(3, 0), primitive as PointF2D); //primitive = segment2.Intersection(segment3); //Assert.IsNotNull(primitive); //Assert.IsInstanceOf<PointF2D>(primitive); //Assert.AreEqual(new PointF2D(0, 3), primitive as PointF2D); //primitive = segment3.Intersection(segment4); //Assert.IsNotNull(primitive); //Assert.IsInstanceOf<PointF2D>(primitive); //Assert.AreEqual(new PointF2D(1.5, 1.5), primitive as PointF2D); //primitive = segment5.Intersection(segment1); //Assert.IsNull(primitive); //primitive = segment5.Intersection(segment2); //Assert.IsNull(primitive); //primitive = segment5.Intersection(segment3); //Assert.IsNull(primitive); //primitive = segment5.Intersection(segment4); //Assert.IsNull(primitive); //primitive = segment5.Intersection(segment6); //Assert.IsNull(primitive); //primitive = segment6.Intersection(segment3); //Assert.IsNotNull(primitive); //Assert.IsInstanceOf<PointF2D>(primitive); //Assert.AreEqual(new PointF2D(3, 0), primitive as PointF2D); //primitive = segment6.Intersection(segment1); //Assert.IsNotNull(primitive); //Assert.IsInstanceOf<PointF2D>(primitive); //Assert.AreEqual(new PointF2D(3, 0), primitive as PointF2D); //primitive = segment6.Intersection(segment3); //Assert.IsNotNull(primitive); //Assert.IsInstanceOf<PointF2D>(primitive); //Assert.AreEqual(new PointF2D(3, 0), primitive as PointF2D); //// half segments. //LineF2D segment7 = new LineF2D(1.5, 2, 1.5, 0, true, false); // only closed upwards. //LineF2D segment9 = new LineF2D(1.5, 2, 1.5, 4, true, false); // only closed downwards. //LineF2D segment8 = new LineF2D(1.5, 1, 1.5, 0, true, false); // only closed upwards. //LineF2D segment10 = new LineF2D(1.5, 1, 1.5, 4, true, false); // only closed downwards. //primitive = segment7.Intersection(segment3); //Assert.IsNotNull(primitive); //Assert.IsInstanceOf<PointF2D>(primitive); //Assert.AreEqual(new PointF2D(1.5, 1.5), primitive as PointF2D); //primitive = segment3.Intersection(segment7); //Assert.IsNotNull(primitive); //Assert.IsInstanceOf<PointF2D>(primitive); //Assert.AreEqual(new PointF2D(1.5, 1.5), primitive as PointF2D); //primitive = segment9.Intersection(segment3); //Assert.IsNull(primitive); //primitive = segment3.Intersection(segment9); //Assert.IsNull(primitive); //primitive = segment10.Intersection(segment3); //Assert.IsNotNull(primitive); //Assert.IsInstanceOf<PointF2D>(primitive); //Assert.AreEqual(new PointF2D(1.5, 1.5), primitive as PointF2D); //primitive = segment3.Intersection(segment10); //Assert.IsNotNull(primitive); //Assert.IsInstanceOf<PointF2D>(primitive); //Assert.AreEqual(new PointF2D(1.5, 1.5), primitive as PointF2D); //primitive = segment8.Intersection(segment3); //Assert.IsNull(primitive); //primitive = segment3.Intersection(segment8); //Assert.IsNull(primitive); //LineF2D segment11 = new LineF2D(-1, 1, 0, 1, true, false); //LineF2D segment12 = new LineF2D(0, 3, 3, 0, true, true); //primitive = segment11.Intersection(segment12); //Assert.IsNotNull(primitive); //Assert.IsInstanceOf<PointF2D>(primitive); //Assert.AreEqual(new PointF2D(2, 1), primitive as PointF2D); //primitive = segment12.Intersection(segment11); //Assert.IsNotNull(primitive); //Assert.IsInstanceOf<PointF2D>(primitive); //Assert.AreEqual(new PointF2D(2, 1), primitive as PointF2D); } } }
46.743363
101
0.596176
[ "MIT" ]
itinero/vector-tiles
test/Itinero.VectorTiles.Test/LocalGeoExtensionsTests.cs
5,284
C#
// Copyright 2020 The Tilt Brush Authors // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using System.Collections.Generic; using UnityEngine; namespace TiltBrush { // N children, each of which follows the same periodic path through space. // Each child is offset by some phase; phases are distributed equally. public class PlaitBrush : ParentBrush { const float TWOPI = 2 * Mathf.PI; protected class PbChildPlait : PbChild { protected PlaitBrush m_owner; // Phase is a number in [0, 1) protected int m_strand; protected PlaitBrush O { get { return m_owner; } } public PbChildPlait(PlaitBrush owner, int strand) { m_owner = owner; m_strand = strand; } // This is the where the magic lies. // It should be some function with a period of 1. protected Vector2 SomePeriodicFunction(float t01) { if (O.NumStrands % 2 == 0) { // The default doesn't look very good with an even # of strands return new Vector2(Mathf.Sin(TWOPI * t01), Mathf.Sin(TWOPI * t01 * 1.5f)); } else { return new Vector2(Mathf.Sin(TWOPI * t01), Mathf.Sin(TWOPI * t01 * 2)); } } protected override TrTransform CalculateChildXf(List<PbKnot> parentKnots) { PbKnot lastKnot = parentKnots[parentKnots.Count - 1]; float distanceMeters = lastKnot.m_distance * App.UNITS_TO_METERS; float t = O.CyclesPerMeter * distanceMeters + (float)m_strand / O.NumStrands; // Our periodic function makes the plait look pretty square; maybe add // some rotation to break things up a bit? float rotations = (O.CyclesPerMeter * distanceMeters) * O.RotationsPerCycle; float amplitude = lastKnot.m_pressuredSize / 2; // /2 because size is diameter, not radius. TrTransform action = TrTransform.R(rotations * 360, Vector3.forward) * TrTransform.T(SomePeriodicFunction(t) * amplitude); TrTransform actionInCanvasSpace = action.TransformBy(lastKnot.GetFrame(AttachFrame.LineTangent)); return actionInCanvasSpace * lastKnot.m_pointer; } } [SerializeField] protected BrushDescriptor m_baseBrush; [Range(3, 9)] [SerializeField] protected float m_numStrands = 3; [Range(0, 3)] [SerializeField] protected int m_recursionLimit = 0; [SerializeField] protected Color32[] m_colors = { new Color32(255, 30, 30, 255), new Color32(230, 200, 200, 255), new Color32(20, 180, 20, 255), }; // Child size is determined mostly automatically; this fine-tunes it. [Range(0.25f, 4)] [SerializeField] protected float m_childScaleFineTune = 1; [SerializeField] protected float m_cyclesPerMeterAtUnitSize = 3; // This adds some extra rotation to the periodic function; it can help break // up the silhouette. [SerializeField] protected float m_rotationsPerCycle = 0; // Cycles per meter per brushsize public float CyclesPerMeter { get { return m_cyclesPerMeterAtUnitSize / BaseSize_LS; } } public float RotationsPerCycle { get { return m_rotationsPerCycle; } } public float NumStrands { get { return m_numStrands; } } protected override void MaybeCreateChildrenImpl() { // Only create children once if (m_children.Count > 0) { return; } if (m_recursionLevel >= m_recursionLimit) { for (int i = 0; i < NumStrands; ++i) { InitializeAndAddChild( new PbChildPlait(this, i), m_baseBrush, m_colors[i % m_colors.Length], relativeSize: m_childScaleFineTune / NumStrands); } } else { int numMiddleStrands = 3 + m_recursionLimit - m_recursionLevel; for (int i = 0; i < numMiddleStrands; ++i) { InitializeAndAddChild( new PbChildPlait(this, i), m_Desc, m_colors[i % m_colors.Length], relativeSize: 0.7f * m_childScaleFineTune / numMiddleStrands); } } } } } // namespace TiltBrush
40.96124
113
0.573429
[ "Apache-2.0" ]
Baflee/crypto-art-gallery-redo
Assets/Scripts/Brushes/PlaitBrush.cs
5,284
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 Assignmentt9 { public partial class AddCustomer : Form { ReadWriteHandler ReadWriteHandler = new ReadWriteHandler(); List<Flight> fligtCollection = ReadWriteHandler.ReadJson(@"d:\temp\as8.json"); public AddCustomer() { InitializeComponent(); } public void addCustomer(object sender, EventArgs e) { if ((this.customerId.Text == "") || (this.firstName.Text == "") || (this.lastName.Text == "") || (this.phoneNumber.Text == "") || (this.flightId.Text == "")) { this.error.Text = "Please fill all fields (customer id, name, phone number, flight id)"; } else { var flight = fligtCollection.FirstOrDefault(f => f.Id == this.flightId.Text); flight.CustomerList.Add(new Customer(this.customerId.Text, this.firstName.Text, this.lastName.Text, this.phoneNumber.Text)); this.flightId.Text = ""; this.customerId.Text = ""; this.firstName.Text = ""; this.lastName.Text = ""; this.phoneNumber.Text = ""; this.error.Text = ""; writeData(); } } public void writeData() { ReadWriteHandler.WriteJson(@"d:\temp\as8.json", fligtCollection); } } }
34.978261
169
0.569919
[ "MIT" ]
anhminh10a2hoa/Window-programming
Assignmentt9/Assignmentt9/AddCustomer.cs
1,611
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace TelegramApi.core { public class T { } }
13.846154
33
0.727778
[ "MIT" ]
miladsoft/TelegramApi
TelegramApi/TelegramApi.core/T.cs
182
C#
using CommandLine; namespace ForEachShell { public partial class Options { [Option('i', "input", Required = true, HelpText = "Input directory.")] public string Input { get; set; } = ""; [Option('c', "command", Required = true, HelpText = "Input command.")] public string Command { get; set; } = ""; [Option('a', "argument", Required = true, HelpText = "Input argument.")] public string Argument { get; set; } = ""; [Option('t', "time", Required = false, HelpText = "time interval (unit seconds)")] public int TimeInterval { get; set; } = 0; public static void HandleParseError(IEnumerable<Error> errs) { foreach (var err in errs) { Console.WriteLine(err.ToString()); } } } }
28.758621
90
0.547962
[ "Apache-2.0" ]
elky84/ForEachShell
Options.cs
836
C#
using Centaurus.Models; using System; using System.Collections.Generic; using System.Linq; using System.Text; namespace Centaurus.Domain { public static class AccountExtensions { /// <summary> /// Checks if the account has balance for the specified asset. /// </summary> /// <param name="account">Account record</param> /// <param name="asset">Asset id</param> /// <returns></returns> public static bool HasBalance(this Account account, int asset) { return account.Balances.Any(b => b.Asset == asset); } /// <summary> /// Creates and adds created balance to the acount /// </summary> /// <param name="account">Account record</param> /// <param name="asset">Asset id</param> /// <returns>Created balance</returns> public static Balance CreateBalance(this Account account, int asset) { var balance = new Balance { Asset = asset }; account.Balances.Add(balance); account.Balances = account.Balances.OrderBy(b => b.Asset).ToList(); return balance; } /// <summary> /// Retrieve account balance. /// </summary> /// <param name="account">Account record</param> /// <param name="asset">Asset id</param> /// <returns></returns> public static Balance GetBalance(this Account account, int asset) { return account.Balances.Find(b => b.Asset == asset); } } }
32.291667
79
0.574839
[ "MIT" ]
PinkDiamond1/centaurus
Centaurus.Domain/accounts/AccountExtensions.cs
1,552
C#
using JSC_LMS.Application.Response; using MediatR; using System; using System.Collections.Generic; using System.Text; namespace JSC_LMS.Application.Features.Class.Queries.GetClassList { public class GetClassListQuery : IRequest<Response<IEnumerable<GetClassListDto>>> { } }
20.571429
84
0.788194
[ "Apache-2.0" ]
ashishneosoftmail/JSC_LMS
src/Core/JSC_LMS.Application/Features/Class/Queries/GetClassList/GetClassListQuery.cs
290
C#
using MediatR; using Microsoft.EntityFrameworkCore; using OnionArchitecture.Application.Interfaces; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading; using System.Threading.Tasks; namespace OnionArchitecture.Application.Features.Products.Commands.DeleteProductById { public class DeleteProductByIdCommand : IRequest<int> { public int Id { get; set; } public class DeleteProductByIdCommandHandler : IRequestHandler<DeleteProductByIdCommand, int> { private readonly IApplicationDbContext _context; public DeleteProductByIdCommandHandler(IApplicationDbContext context) { _context = context; } public async Task<int> Handle(DeleteProductByIdCommand command, CancellationToken cancellationToken) { var product = await _context.Products.Where(a => a.Id == command.Id).FirstOrDefaultAsync(); if (product == null) return default; _context.Products.Remove(product); await _context.SaveChangesAsync(); return product.Id; } } } }
35.441176
112
0.670539
[ "MIT" ]
raihanM95/OnionArchitecture
OnionArchitecture.Application/Features/Products/Commands/DeleteProductById/DeleteProductByIdCommand.cs
1,207
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Threading; using Autofac; using Autofac.Core; using MarkDoc.Core; using MarkDoc.Helpers; namespace MarkDoc.MVVM.Helpers { public static class PluginManager { public static Lazy<IReadOnlyDictionary<string, IPlugin>> Plugins { get; } /// <summary> /// Default constructor /// </summary> static PluginManager() => Plugins = new Lazy<IReadOnlyDictionary<string, IPlugin>>(() => TypeResolver.Resolve<IEnumerable<IPlugin>>().ToDictionary(plugin => plugin.Id, Linq.XtoX, StringComparer.InvariantCultureIgnoreCase), LazyThreadSafetyMode.ExecutionAndPublication); public static void RegisterModules(ContainerBuilder builder) { var path = Path.GetFullPath("Plugins"); var assemblies = Directory .EnumerateFiles(path, "MarkDoc.Plugins.*.dll", SearchOption.TopDirectoryOnly) .Select(Assembly.LoadFrom) .ToArray(); foreach (var assembly in assemblies) { var modules = assembly.GetTypes() .Where(p => typeof(IModule).IsAssignableFrom(p) && !p.IsAbstract) .Select(Activator.CreateInstance) .OfType<IModule>(); // Registers each module foreach (var module in modules) builder.RegisterModule(module); } } public static IPlugin GetPlugin(string id) { if (Plugins.Value.TryGetValue(id, out var plugin)) return plugin; throw new KeyNotFoundException($"Plugin with the Id '{id}' not found."); } } }
30.207547
252
0.681449
[ "MIT" ]
hailstorm75/MarkDoc.Core
src/Libraries/Helpers/MarkDoc.MVVM.Helpers/PluginManager.cs
1,603
C#
using GameFramework; using System.IO; using UnityEditor; using UnityEngine; using UnityGameFramework.Editor.AssetBundleTools; namespace StarForce.Editor { public sealed class StarForceBuildEventHandler : IBuildEventHandler { public void PreProcessBuildAll(string productName, string companyName, string gameIdentifier, string applicableGameVersion, int internalResourceVersion, string unityVersion, BuildAssetBundleOptions buildOptions, bool zip, string outputDirectory, string workingPath, string outputPackagePath, string outputFullPath, string outputPackedPath, string buildReportPath) { string streamingAssetsPath = Utility.Path.GetCombinePath(Application.dataPath, "StreamingAssets"); string[] fileNames = Directory.GetFiles(streamingAssetsPath, "*", SearchOption.AllDirectories); foreach (string fileName in fileNames) { if (fileName.Contains(".gitkeep")) { continue; } File.Delete(fileName); } Utility.Path.RemoveEmptyDirectory(streamingAssetsPath); } public void PostProcessBuildAll(string productName, string companyName, string gameIdentifier, string applicableGameVersion, int internalResourceVersion, string unityVersion, BuildAssetBundleOptions buildOptions, bool zip, string outputDirectory, string workingPath, string outputPackagePath, string outputFullPath, string outputPackedPath, string buildReportPath) { } public void PreProcessBuild(BuildTarget buildTarget, string workingPath, string outputPackagePath, string outputFullPath, string outputPackedPath) { } public void PostProcessBuild(BuildTarget buildTarget, string workingPath, string outputPackagePath, string outputFullPath, string outputPackedPath) { if (buildTarget != BuildTarget.StandaloneWindows) { return; } string streamingAssetsPath = Utility.Path.GetCombinePath(Application.dataPath, "StreamingAssets"); string[] fileNames = Directory.GetFiles(outputPackagePath, "*", SearchOption.AllDirectories); foreach (string fileName in fileNames) { string destFileName = Utility.Path.GetCombinePath(streamingAssetsPath, fileName.Substring(outputPackagePath.Length)); FileInfo destFileInfo = new FileInfo(destFileName); if (!destFileInfo.Directory.Exists) { destFileInfo.Directory.Create(); } File.Copy(fileName, destFileName); } } } }
42.492308
155
0.670529
[ "MIT" ]
W8023Y2014/StarForce
Assets/GameMain/Scripts/Editor/StarForceBuildEventHandler.cs
2,764
C#
// Copyright Dirk Lemstra https://github.com/dlemstra/Magick.NET. // Licensed under the Apache License, Version 2.0. namespace ImageMagick { /// <summary> /// Draws a cubic Bezier curve from the current point to (x, y) using (x1,y1) as the control point /// at the beginning of the curve and (x2, y2) as the control point at the end of the curve using /// relative coordinates. At the end of the command, the new current point becomes the final (x, y) /// coordinate pair used in the polybezier. /// </summary> public sealed class PathCurveToRel : IPath, IDrawingWand { private readonly PointD _controlPointStart; private readonly PointD _controlPointEnd; private readonly PointD _end; /// <summary> /// Initializes a new instance of the <see cref="PathCurveToRel"/> class. /// </summary> /// <param name="x1">X coordinate of control point for curve beginning.</param> /// <param name="y1">Y coordinate of control point for curve beginning.</param> /// <param name="x2">X coordinate of control point for curve ending.</param> /// <param name="y2">Y coordinate of control point for curve ending.</param> /// <param name="x">X coordinate of the end of the curve.</param> /// <param name="y">Y coordinate of the end of the curve.</param> public PathCurveToRel(double x1, double y1, double x2, double y2, double x, double y) : this(new PointD(x1, y1), new PointD(x2, y2), new PointD(x, y)) { } /// <summary> /// Initializes a new instance of the <see cref="PathCurveToRel"/> class. /// </summary> /// <param name="controlPointStart">Coordinate of control point for curve beginning.</param> /// <param name="controlPointEnd">Coordinate of control point for curve ending.</param> /// <param name="end">Coordinate of the end of the curve.</param> public PathCurveToRel(PointD controlPointStart, PointD controlPointEnd, PointD end) { _controlPointStart = controlPointStart; _controlPointEnd = controlPointEnd; _end = end; } /// <summary> /// Draws this instance with the drawing wand. /// </summary> /// <param name="wand">The want to draw on.</param> void IDrawingWand.Draw(DrawingWand wand) => wand?.PathCurveToRel(_controlPointStart, _controlPointEnd, _end); } }
48.529412
117
0.638788
[ "Apache-2.0" ]
brianpopow/Magick.NET
src/Magick.NET/Drawables/Paths/PathCurveToRel.cs
2,475
C#
using SCGraphTheory.Search.Classic; using System; using System.Collections.Generic; using System.Diagnostics; using WorldGraph = SCGraphTheory.Search.TestGraphs.GridGraph<SCGraphTheory.Search.Visualizer.World.Terrain>; namespace SCGraphTheory.Search.Visualizer { /// <summary> /// Search visualizer world model. /// </summary> public class World { private static readonly Dictionary<Terrain, float> TerrainCosts = new () { [Terrain.Floor] = 1f, [Terrain.Water] = 3f, }; private readonly Stopwatch searchTimer = new (); private readonly WorldGraph graph; private (int X, int Y) startPosition; private (int X, int Y) targetPosition; private Action recreateSearch; /// <summary> /// Initializes a new instance of the <see cref="World"/> class. /// </summary> /// <param name="size">The size of the world.</param> public World((int X, int Y) size) { Size = size; graph = new WorldGraph(size, (from, to) => from != Terrain.Wall && to != Terrain.Wall); Target = (0, 0); Start = (size.X - 1, size.Y - 1); RecreateSearch = MakeAStarSearch; } /// <summary> /// An enumeration of possible terrain types. /// </summary> public enum Terrain { /// <summary> /// Floor - cheap terrain type to travel on. /// </summary> Floor, /// <summary> /// Floor - expensive terrain type to travel on. /// </summary> Water, /// <summary> /// Wall - impassable terrain. /// </summary> Wall, } /// <summary> /// Gets the size of the world. /// </summary> public (int X, int Y) Size { get; } /// <summary> /// Gets the current search. /// </summary> public ISearch<WorldGraph.Node, WorldGraph.Edge> LatestSearch { get; private set; } /// <summary> /// Gets or sets the current start position. /// </summary> public (int X, int Y) Start { get => startPosition; set { startPosition = value; recreateSearch?.Invoke(); } } /// <summary> /// Gets or sets the current target position. /// </summary> public (int X, int Y) Target { get => targetPosition; set { targetPosition = value; recreateSearch?.Invoke(); } } /// <summary> /// Gets the duration of the current search. /// </summary> public TimeSpan SearchDuration => searchTimer.Elapsed; /// <summary> /// Sets the delegate used to recreate the current search (and invokes it immediately). Invoked whenever some aspect of the world changes. /// </summary> public Action RecreateSearch { set { recreateSearch = value; recreateSearch?.Invoke(); } } /// <summary> /// Gets an index of node values by position. /// </summary> /// <param name="x">The x-ordinate of the node to retrieve.</param> /// <param name="y">The y-ordinate of the node to retrieve.</param> public Terrain this[int x, int y] { get => graph[x, y].Value; set { if (x < 0 || x >= Size.X || y < 0 || y >= Size.Y) { return; } graph[x, y].Value = value; recreateSearch?.Invoke(); } } /// <summary> /// Recreates the active search using the A* algorithm. /// </summary> public void MakeAStarSearch() { searchTimer.Restart(); LatestSearch = new AStarSearch<WorldGraph.Node, WorldGraph.Edge>( graph[Start.X, Start.Y], t => t.Coordinates == Target, EuclideanEdgeCost, n => ManhattanDistance(n.Coordinates, Target)); LatestSearch.Complete(); searchTimer.Stop(); } /// <summary> /// Recreates the active search using Dijkstra's algorithm. /// </summary> public void MakeDijkstraSearch() { searchTimer.Restart(); LatestSearch = new DijkstraSearch<WorldGraph.Node, WorldGraph.Edge>( graph[Start.X, Start.Y], t => t.Coordinates == Target, EuclideanEdgeCost); LatestSearch.Complete(); searchTimer.Stop(); } /// <summary> /// Recreates the active search using the breadth-first algorithm. /// </summary> public void MakeBreadthFirstSearch() { searchTimer.Restart(); LatestSearch = new BreadthFirstSearch<WorldGraph.Node, WorldGraph.Edge>( graph[Start.X, Start.Y], t => t.Coordinates == Target); LatestSearch.Complete(); searchTimer.Stop(); } /// <summary> /// Recreates the active search using the depth-first algorithm. /// </summary> public void MakeDepthFirstSearch() { searchTimer.Restart(); LatestSearch = new DepthFirstSearch<WorldGraph.Node, WorldGraph.Edge>( graph[Start.X, Start.Y], t => t.Coordinates == Target); LatestSearch.Complete(); searchTimer.Stop(); } private static float EuclideanDistance((int X, int Y) a, (int X, int Y) b) { return (float)Math.Sqrt((a.X - b.X) * (a.X - b.X) + (a.Y - b.Y) * (a.Y - b.Y)); } private static float ManhattanDistance((int X, int Y) a, (int X, int Y) b) { return Math.Abs(a.X - b.X) + Math.Abs(a.Y - b.Y); } private static float EuclideanEdgeCost(WorldGraph.Edge edge) { return EuclideanDistance(edge.From.Coordinates, edge.To.Coordinates) * 0.5f * (TerrainCosts[edge.From.Value] + TerrainCosts[edge.To.Value]); } } }
31.062802
152
0.505443
[ "MIT" ]
sdcondon/SCGraphTheory.Search
src/Search.Visualizer/World.cs
6,432
C#
using System.Configuration; namespace Thinktecture.Relay.OnPremiseConnectorService.Configuration { public sealed class OnPremiseInProcTargetElement : OnPremiseTargetElement { private readonly ConfigurationProperty _typeName = new ConfigurationProperty("typeName", typeof(string), null, ConfigurationPropertyOptions.IsRequired); public OnPremiseInProcTargetElement() { Properties.Add(_typeName); } public string TypeName => (string)this[_typeName]; } }
27.705882
154
0.808917
[ "BSD-3-Clause" ]
embedcard/relayserver
Thinktecture.Relay.OnPremiseConnectorService/Configuration/OnPremiseInProcTargetElement.cs
471
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Web; namespace InternshipLink.Web.Data { public class Student { [Key] public long ID { get; set; } [Required, MaxLength(40)] public string FirstName { get; set; } [MaxLength(40)] public string MiddleName { get; set; } public int? StartYear { get; set; } public int MajorID { get; set; } public int? Group { get; set; } [MaxLength(40)] public string LastName { get; set; } [ForeignKey(nameof(MajorID))] public Major Major { get; set; } public string FullName { get { return $"{FirstName} {LastName}"; } } public int UserID { get; set; } [ForeignKey(nameof(UserID))] public ApplicationUser User; //public bool Active { get; set; } = true; //public DateTime CreatedOn { get; set; } = DateTime.Now; //public string CreateBy { get; set; } //public DateTime ModifiedOn { get; set; } = DateTime.Now; //public string ModifiedBy { get; set; } } }
23.377358
76
0.590799
[ "Apache-2.0" ]
scalefocus/internship-link
src/InternshipLink.Web/Data/Student.cs
1,241
C#
using System; using CryEngine; using FairyGUI.Utils; namespace FairyGUI { /// <summary> /// GProgressBar class. /// </summary> public class GProgressBar : GComponent { double _max; double _value; ProgressTitleType _titleType; bool _reverse; GTextField _titleObject; GMovieClip _aniObject; GObject _barObjectH; GObject _barObjectV; float _barMaxWidth; float _barMaxHeight; float _barMaxWidthDelta; float _barMaxHeightDelta; float _barStartX; float _barStartY; bool _tweening; public GProgressBar() { _value = 50; _max = 100; } /// <summary> /// /// </summary> public ProgressTitleType titleType { get { return _titleType; } set { if (_titleType != value) { _titleType = value; Update(_value); } } } /// <summary> /// /// </summary> public double max { get { return _max; } set { if (_max != value) { _max = value; Update(_value); } } } /// <summary> /// /// </summary> public double value { get { return _value; } set { if (_tweening) { GTween.Kill(this, TweenPropType.Progress, true); _tweening = false; } if (_value != value) { _value = value; Update(_value); } } } public bool reverse { get { return _reverse; } set { _reverse = value; } } /// <summary> /// 动态改变进度值。 /// </summary> /// <param name="value"></param> /// <param name="duration"></param> public GTweener TweenValue(double value, float duration) { double oldValule; if (_tweening) { GTweener twener = GTween.GetTween(this, TweenPropType.Progress); oldValule = twener.value.d; twener.Kill(false); } else oldValule = _value; _value = value; _tweening = true; return GTween.ToDouble(oldValule, _value, duration) .SetEase(EaseType.Linear) .SetTarget(this, TweenPropType.Progress) .OnComplete(() => { _tweening = false; }); } /// <summary> /// /// </summary> /// <param name="newValue"></param> public void Update(double newValue) { float percent = _max != 0 ? (float)Math.Min(newValue / _max, 1) : 0; if (_titleObject != null) { switch (_titleType) { case ProgressTitleType.Percent: _titleObject.text = (int)Math.Round(percent * 100) + "%"; break; case ProgressTitleType.ValueAndMax: _titleObject.text = Math.Round(newValue) + "/" + Math.Round(max); break; case ProgressTitleType.Value: _titleObject.text = "" + Math.Round(newValue); break; case ProgressTitleType.Max: _titleObject.text = "" + Math.Round(_max); break; } } float fullWidth = this.width - _barMaxWidthDelta; float fullHeight = this.height - _barMaxHeightDelta; if (!_reverse) { if (_barObjectH != null) { if ((_barObjectH is GImage) && ((GImage)_barObjectH).fillMethod != FillMethod.None) ((GImage)_barObjectH).fillAmount = percent; else if ((_barObjectH is GLoader) && ((GLoader)_barObjectH).fillMethod != FillMethod.None) ((GLoader)_barObjectH).fillAmount = percent; else _barObjectH.width = (int)Math.Round(fullWidth * percent); } if (_barObjectV != null) { if ((_barObjectV is GImage) && ((GImage)_barObjectV).fillMethod != FillMethod.None) ((GImage)_barObjectV).fillAmount = percent; else if ((_barObjectV is GLoader) && ((GLoader)_barObjectV).fillMethod != FillMethod.None) ((GLoader)_barObjectV).fillAmount = percent; else _barObjectV.height = (int)Math.Round(fullHeight * percent); } } else { if (_barObjectH != null) { if ((_barObjectH is GImage) && ((GImage)_barObjectH).fillMethod != FillMethod.None) ((GImage)_barObjectH).fillAmount = 1 - percent; else if ((_barObjectH is GLoader) && ((GLoader)_barObjectH).fillMethod != FillMethod.None) ((GLoader)_barObjectH).fillAmount = 1 - percent; else { _barObjectH.width = (int)Math.Round(fullWidth * percent); _barObjectH.x = _barStartX + (fullWidth - _barObjectH.width); } } if (_barObjectV != null) { if ((_barObjectV is GImage) && ((GImage)_barObjectV).fillMethod != FillMethod.None) ((GImage)_barObjectV).fillAmount = 1 - percent; else if ((_barObjectV is GLoader) && ((GLoader)_barObjectV).fillMethod != FillMethod.None) ((GLoader)_barObjectV).fillAmount = 1 - percent; else { _barObjectV.height = (int)Math.Round(fullHeight * percent); _barObjectV.y = _barStartY + (fullHeight - _barObjectV.height); } } } if (_aniObject != null) _aniObject.frame = (int)Math.Round(percent * 100); } override protected void ConstructExtension(ByteBuffer buffer) { buffer.Seek(0, 6); _titleType = (ProgressTitleType)buffer.ReadByte(); _reverse = buffer.ReadBool(); _titleObject = GetChild("title") as GTextField; _barObjectH = GetChild("bar"); _barObjectV = GetChild("bar_v"); _aniObject = GetChild("ani") as GMovieClip; if (_barObjectH != null) { _barMaxWidth = _barObjectH.width; _barMaxWidthDelta = this.width - _barMaxWidth; _barStartX = _barObjectH.x; } if (_barObjectV != null) { _barMaxHeight = _barObjectV.height; _barMaxHeightDelta = this.height - _barMaxHeight; _barStartY = _barObjectV.y; } } override public void Setup_AfterAdd(ByteBuffer buffer, int beginPos) { base.Setup_AfterAdd(buffer, beginPos); if (!buffer.Seek(beginPos, 6)) { Update(_value); return; } if ((ObjectType)buffer.ReadByte() != packageItem.objectType) { Update(_value); return; } _value = buffer.ReadInt(); _max = buffer.ReadInt(); Update(_value); } override protected void HandleSizeChanged() { base.HandleSizeChanged(); if (_barObjectH != null) _barMaxWidth = this.width - _barMaxWidthDelta; if (_barObjectV != null) _barMaxHeight = this.height - _barMaxHeightDelta; if (!this.underConstruct) Update(_value); } public override void Dispose() { if (_tweening) GTween.Kill(this); base.Dispose(); } } }
23.053191
96
0.598985
[ "MIT" ]
fairygui/FairyGUI-cryengine
FairyGUI/Scripts/UI/GProgressBar.cs
6,519
C#
using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.Extensions.Logging; using okta_aspnetcore_mvc_example.Models; namespace okta_aspnetcore_mvc_example.Controllers { public class HomeController : Controller { private readonly ILogger<HomeController> _logger; public HomeController(ILogger<HomeController> logger) { _logger = logger; } public IActionResult Index() { return View(); } public IActionResult Privacy() { return View(); } [ResponseCache(Duration = 0, Location = ResponseCacheLocation.None, NoStore = true)] public IActionResult Error() { return View(new ErrorViewModel { RequestId = Activity.Current?.Id ?? HttpContext.TraceIdentifier }); } [Authorize] public IActionResult Profile() { return View(HttpContext.User.Claims); } } }
25
112
0.644444
[ "Apache-2.0" ]
Jaboo9/okta
samples-aspnetcore-3x/self-hosted-login/okta-aspnetcore-mvc-example/Controllers/HomeController.cs
1,127
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the evidently-2021-02-01.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Net; using System.Text; using System.Xml.Serialization; using Amazon.CloudWatchEvidently.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.CloudWatchEvidently.Model.Internal.MarshallTransformations { /// <summary> /// Response Unmarshaller for Experiment Object /// </summary> public class ExperimentUnmarshaller : IUnmarshaller<Experiment, XmlUnmarshallerContext>, IUnmarshaller<Experiment, JsonUnmarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> Experiment IUnmarshaller<Experiment, XmlUnmarshallerContext>.Unmarshall(XmlUnmarshallerContext context) { throw new NotImplementedException(); } /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="context"></param> /// <returns></returns> public Experiment Unmarshall(JsonUnmarshallerContext context) { context.Read(); if (context.CurrentTokenType == JsonToken.Null) return null; Experiment unmarshalledObject = new Experiment(); int targetDepth = context.CurrentDepth; while (context.ReadAtDepth(targetDepth)) { if (context.TestExpression("arn", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Arn = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("createdTime", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.CreatedTime = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("description", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Description = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("execution", targetDepth)) { var unmarshaller = ExperimentExecutionUnmarshaller.Instance; unmarshalledObject.Execution = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("lastUpdatedTime", targetDepth)) { var unmarshaller = DateTimeUnmarshaller.Instance; unmarshalledObject.LastUpdatedTime = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("metricGoals", targetDepth)) { var unmarshaller = new ListUnmarshaller<MetricGoal, MetricGoalUnmarshaller>(MetricGoalUnmarshaller.Instance); unmarshalledObject.MetricGoals = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("name", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Name = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("onlineAbDefinition", targetDepth)) { var unmarshaller = OnlineAbDefinitionUnmarshaller.Instance; unmarshalledObject.OnlineAbDefinition = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("project", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Project = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("randomizationSalt", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.RandomizationSalt = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("samplingRate", targetDepth)) { var unmarshaller = LongUnmarshaller.Instance; unmarshalledObject.SamplingRate = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("schedule", targetDepth)) { var unmarshaller = ExperimentScheduleUnmarshaller.Instance; unmarshalledObject.Schedule = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("status", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Status = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("statusReason", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.StatusReason = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("tags", targetDepth)) { var unmarshaller = new DictionaryUnmarshaller<string, string, StringUnmarshaller, StringUnmarshaller>(StringUnmarshaller.Instance, StringUnmarshaller.Instance); unmarshalledObject.Tags = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("treatments", targetDepth)) { var unmarshaller = new ListUnmarshaller<Treatment, TreatmentUnmarshaller>(TreatmentUnmarshaller.Instance); unmarshalledObject.Treatments = unmarshaller.Unmarshall(context); continue; } if (context.TestExpression("type", targetDepth)) { var unmarshaller = StringUnmarshaller.Instance; unmarshalledObject.Type = unmarshaller.Unmarshall(context); continue; } } return unmarshalledObject; } private static ExperimentUnmarshaller _instance = new ExperimentUnmarshaller(); /// <summary> /// Gets the singleton. /// </summary> public static ExperimentUnmarshaller Instance { get { return _instance; } } } }
42.361702
180
0.574209
[ "Apache-2.0" ]
EbstaLimited/aws-sdk-net
sdk/src/Services/CloudWatchEvidently/Generated/Model/Internal/MarshallTransformations/ExperimentUnmarshaller.cs
7,964
C#
/* * Copyright (c) 2018 THL A29 Limited, a Tencent company. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, * software distributed under the License is distributed on an * "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY * KIND, either express or implied. See the License for the * specific language governing permissions and limitations * under the License. */ namespace TencentCloud.Clb.V20180317.Models { using Newtonsoft.Json; using System.Collections.Generic; using TencentCloud.Common; public class TargetGroupBackend : AbstractModel { /// <summary> /// Target group ID /// </summary> [JsonProperty("TargetGroupId")] public string TargetGroupId{ get; set; } /// <summary> /// Real server type. Valid values: CVM, ENI (coming soon) /// </summary> [JsonProperty("Type")] public string Type{ get; set; } /// <summary> /// Unique real server ID /// </summary> [JsonProperty("InstanceId")] public string InstanceId{ get; set; } /// <summary> /// Listening port of real server /// </summary> [JsonProperty("Port")] public ulong? Port{ get; set; } /// <summary> /// Forwarding weight of real server. Value range: [0, 100]. Default value: 10. /// </summary> [JsonProperty("Weight")] public ulong? Weight{ get; set; } /// <summary> /// Public IP of real server /// Note: this field may return null, indicating that no valid values can be obtained. /// </summary> [JsonProperty("PublicIpAddresses")] public string[] PublicIpAddresses{ get; set; } /// <summary> /// Private IP of real server /// Note: this field may return null, indicating that no valid values can be obtained. /// </summary> [JsonProperty("PrivateIpAddresses")] public string[] PrivateIpAddresses{ get; set; } /// <summary> /// Real server instance name /// Note: this field may return null, indicating that no valid values can be obtained. /// </summary> [JsonProperty("InstanceName")] public string InstanceName{ get; set; } /// <summary> /// Real server binding time /// Note: this field may return null, indicating that no valid values can be obtained. /// </summary> [JsonProperty("RegisteredTime")] public string RegisteredTime{ get; set; } /// <summary> /// Unique ENI ID /// Note: this field may return null, indicating that no valid values can be obtained. /// </summary> [JsonProperty("EniId")] public string EniId{ get; set; } /// <summary> /// AZ ID of the real server /// Note: This field may return `null`, indicating that no valid values can be obtained. /// </summary> [JsonProperty("ZoneId")] public ulong? ZoneId{ get; set; } /// <summary> /// For internal usage only. DO NOT USE IT. /// </summary> public override void ToMap(Dictionary<string, string> map, string prefix) { this.SetParamSimple(map, prefix + "TargetGroupId", this.TargetGroupId); this.SetParamSimple(map, prefix + "Type", this.Type); this.SetParamSimple(map, prefix + "InstanceId", this.InstanceId); this.SetParamSimple(map, prefix + "Port", this.Port); this.SetParamSimple(map, prefix + "Weight", this.Weight); this.SetParamArraySimple(map, prefix + "PublicIpAddresses.", this.PublicIpAddresses); this.SetParamArraySimple(map, prefix + "PrivateIpAddresses.", this.PrivateIpAddresses); this.SetParamSimple(map, prefix + "InstanceName", this.InstanceName); this.SetParamSimple(map, prefix + "RegisteredTime", this.RegisteredTime); this.SetParamSimple(map, prefix + "EniId", this.EniId); this.SetParamSimple(map, prefix + "ZoneId", this.ZoneId); } } }
36.675
99
0.604863
[ "Apache-2.0" ]
TencentCloud/tencentcloud-sdk-dotnet-intl-en
TencentCloud/Clb/V20180317/Models/TargetGroupBackend.cs
4,401
C#
using System.Collections.Generic; namespace Pglet.Controls { public class BarChartData : Control { IList<BarChartDataPoint> _points = new List<BarChartDataPoint>(); protected override string ControlName => "data"; public IList<BarChartDataPoint> Points { get { return _points; } set { _points = value; } } protected override IEnumerable<Control> GetChildren() { return _points; } } }
21.782609
73
0.590818
[ "MIT" ]
pglet/pglet-powershell
src/Pglet/Controls/BarChartData.cs
503
C#
using System; using System.Collections.Generic; using System.Text; using PagarMe.Enumeration; namespace PagarMe.Model { public class BulkAnticipation : Base.Model { protected override string Endpoint { get { return "/bulk_anticipations"; } } public BulkAnticipation() : this(null) { } public BulkAnticipation(PagarMeService service) : base(service) { } public BulkAnticipation(PagarMeService service, string endpointPrefix = "") :base(service, endpointPrefix) { } public BulkAnticipationStatus Status { get { return GetAttribute<BulkAnticipationStatus>("status"); } } public TimeFrame Timeframe { get { return GetAttribute<TimeFrame>("timeframe"); } set { SetAttribute("timeframe", value); } } public DateTime PaymentDate { get { return GetAttribute<DateTime>("payment_date"); } set { SetAttribute("payment_date", Utils.ConvertToUnixTimeStamp(value)); } } public int Amount { get { return GetAttribute<int>("amount"); } } public int RequestedAmount { set { SetAttribute("requested_amount", value); } internal get { return GetAttribute<int>("requested_amount"); } } public int Fee { get { return GetAttribute<int>("fee"); } } public int AnticipationFee { get { return GetAttribute<int>("anticipation_fee"); } } public bool Build { set { if (value == false) SetAttribute("build", ""); else SetAttribute("build", "true"); } get { return Boolean.Parse(GetAttribute<string>("build")); } } } }
28.269841
118
0.582257
[ "MIT" ]
EduardoPires/pagarme-net
PagarMe.Shared/Model/BulkAnticipation.cs
1,783
C#
using System.Collections.Generic; using MetaGame; using UnityEngine; namespace MetaGame { [ObjectSystem] public class UiAwakeSystem : AwakeSystem<UI, string, GameObject> { public override void Awake(UI self, string name, GameObject gameObject) { self.Awake(name, gameObject); } } [HideInHierarchy] public sealed class UI: Entity { public string Name { get; private set; } public Dictionary<string, UI> children = new Dictionary<string, UI>(); public void Awake(string name, GameObject gameObject) { this.children.Clear(); gameObject.AddComponent<ComponentView>().Component = this; gameObject.layer = LayerMask.NameToLayer(LayerNames.UI); this.Name = name; this.GameObject = gameObject; } public override void Dispose() { if (this.IsDisposed) { return; } base.Dispose(); foreach (UI ui in this.children.Values) { ui.Dispose(); } UnityEngine.Object.Destroy(GameObject); children.Clear(); } public void SetAsFirstSibling() { this.GameObject.transform.SetAsFirstSibling(); } public void Add(UI ui) { this.children.Add(ui.Name, ui); ui.Parent = this; } public void Remove(string name) { UI ui; if (!this.children.TryGetValue(name, out ui)) { return; } this.children.Remove(name); ui.Dispose(); } public UI Get(string name) { UI child; if (this.children.TryGetValue(name, out child)) { return child; } GameObject childGameObject = this.GameObject.transform.Find(name)?.gameObject; if (childGameObject == null) { return null; } child = ComponentFactory.Create<UI, string, GameObject>(name, childGameObject); this.Add(child); return child; } } }
19.322222
82
0.6682
[ "Apache-2.0" ]
lukaozi/MetaGame
client/Assets/Scripts/CSharp/Game/Libs/UI/UI.cs
1,741
C#
#nullable enable using System; using Cinling.Lib.FileLogger; using Cinling.Lib.Options; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Options; namespace Cinling.Lib.Services { public interface ILogService : ILogger<LogService> { } /// <summary> /// 日志服务 /// </summary> public class LogService : ILogService { /// <summary> /// /// </summary> private readonly ILogger<LogService> logger; public LogService(ILoggerFactory loggerFactory, IOptions<LogServiceOptions> iLogServiceOptions, IOptions<FileLoggerOptions> iFileLoggerOptions) { iLogServiceOptions.Value.InitLoggerFactoryAction(loggerFactory, iFileLoggerOptions.Value); logger = loggerFactory.CreateLogger<LogService>(); } /// <summary> /// /// </summary> /// <param name="logLevel"></param> /// <param name="eventId"></param> /// <param name="state"></param> /// <param name="exception"></param> /// <param name="formatter"></param> /// <typeparam name="TState"></typeparam> public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter) { logger.Log(logLevel, eventId, state, exception, formatter); } /// <summary> /// /// </summary> /// <param name="logLevel"></param> /// <returns></returns> public bool IsEnabled(LogLevel logLevel) { return logger.IsEnabled(logLevel); } /// <summary> /// /// </summary> /// <param name="state"></param> /// <typeparam name="TState"></typeparam> /// <returns></returns> public IDisposable BeginScope<TState>(TState state) { return logger.BeginScope(state); } } }
31.442623
153
0.587591
[ "MIT" ]
cinling/dotnet-lib
src/Services/LogService.cs
1,928
C#
/* * Copyright 2014 Mikhail Shiryaev * * 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. * * * Product : Rapid SCADA * Module : SCADA-Server Service * Summary : Main server logic implementation. Derived types * * Author : Mikhail Shiryaev * Created : 2013 * Modified : 2013 */ using System; using System.IO; using Scada.Data; namespace Scada.Server.Svc { partial class MainLogic { /// <summary> /// Типы срезов /// </summary> internal enum SrezTypes { /// <summary> /// Текущий /// </summary> Cur, /// <summary> /// Минутный /// </summary> Min, /// <summary> /// Часовой /// </summary> Hour } /// <summary> /// Входной канал /// </summary> /// <remarks>Класс содержит только те свойства, которые используются приложением</remarks> private class InCnl { /// <summary> /// Получить или установить номер входного канала /// </summary> public int CnlNum { get; set; } /// <summary> /// Получить или установить идентификатор типа канала /// </summary> public int CnlTypeID { get; set; } /// <summary> /// Получить или установить номер объекта /// </summary> public int ObjNum { get; set; } /// <summary> /// Получить или установить номер КП /// </summary> public int KPNum { get; set; } /// <summary> /// Получить или установить признак использования формулы /// </summary> public bool FormulaUsed { get; set; } /// <summary> /// Получить или установить формулу /// </summary> public string Formula { get; set; } /// <summary> /// Получить или установить признак усреднения /// </summary> public bool Averaging { get; set; } /// <summary> /// Получить или установить идентификатор параметра /// </summary> public int ParamID { get; set; } /// <summary> /// Получить или установить признак записи событий /// </summary> public bool EvEnabled { get; set; } /// <summary> /// Получить или установить признак записи событий по изменению /// </summary> public bool EvOnChange { get; set; } /// <summary> /// Получить или установить признак записи событий по неопределённому состоянию /// </summary> public bool EvOnUndef { get; set; } /// <summary> /// Получить или установить нижнюю аварийную границу /// </summary> public double LimLowCrash { get; set; } /// <summary> /// Получить или установить нижнюю границу /// </summary> public double LimLow { get; set; } /// <summary> /// Получить или установить верхнюю границу /// </summary> public double LimHigh { get; set; } /// <summary> /// Получить или установить верхнюю аварийную границу /// </summary> public double LimHighCrash { get; set; } /// <summary> /// Метод вычисления данных входного канала /// </summary> public Calculator.CalcCnlDataDelegate CalcCnlData; } /// <summary> /// Канал управления /// </summary> /// <remarks>Класс содержит только те свойства, которые используются приложением</remarks> internal class CtrlCnl { /// <summary> /// Получить или установить номер канала управления /// </summary> public int CtrlCnlNum { get; set; } /// <summary> /// Получить или установить идентификатор типа команды /// </summary> public int CmdTypeID { get; set; } /// <summary> /// Получить или установить номер объекта /// </summary> public int ObjNum { get; set; } /// <summary> /// Получить или установить номер КП /// </summary> public int KPNum { get; set; } /// <summary> /// Получить или установить номер команды /// </summary> public int CmdNum { get; set; } /// <summary> /// Получить или установить признак использования формулы /// </summary> public bool FormulaUsed { get; set; } /// <summary> /// Получить или установить формулу /// </summary> public string Formula { get; set; } /// <summary> /// Получить или установить признак записи событий /// </summary> public bool EvEnabled { get; set; } /// <summary> /// Метод вычисления значения команды /// </summary> public Calculator.CalcCmdValDelegate CalcCmdVal; /// <summary> /// Клонировать канал управления /// </summary> public CtrlCnl Clone() { return new CtrlCnl() { CtrlCnlNum = this.CtrlCnlNum, CmdTypeID = this.CmdTypeID, ObjNum = this.ObjNum, KPNum = this.KPNum, CmdNum = this.CmdNum, FormulaUsed = this.FormulaUsed, Formula = this.Formula, EvEnabled = this.EvEnabled, CalcCmdVal = this.CalcCmdVal }; } } /// <summary> /// Пользователь /// </summary> /// <remarks>Класс содержит только те свойства, которые используются приложением</remarks> internal class User { /// <summary> /// Получить или установить имя /// </summary> public string Name { get; set; } /// <summary> /// Получить или установить пароль /// </summary> public string Password { get; set; } /// <summary> /// Получить или установить идентификатор роли /// </summary> public int RoleID { get; set; } /// <summary> /// Клонировать пользователя /// </summary> public User Clone() { return new User() { Name = this.Name, Password = this.Password, RoleID = this.RoleID }; } } /// <summary> /// Кэш таблиц срезов /// </summary> private class SrezTableCache { /// <summary> /// Конструктор /// </summary> private SrezTableCache() { } /// <summary> /// Конструктор /// </summary> public SrezTableCache(DateTime date) { AccessDT = DateTime.Now; Date = date; SrezTable = new SrezTable(); SrezTableCopy = new SrezTable(); SrezAdapter = new SrezAdapter(); SrezCopyAdapter = new SrezAdapter(); } /// <summary> /// Получить или установить дату и время последнего доступа к объекту /// </summary> public DateTime AccessDT { get; set; } /// <summary> /// Получить дату таблиц среза /// </summary> public DateTime Date { get; private set; } /// <summary> /// Получить таблицу срезов /// </summary> public SrezTable SrezTable { get; private set; } /// <summary> /// Получить таблицу копий срезов /// </summary> public SrezTable SrezTableCopy { get; private set; } /// <summary> /// Получить адаптер таблицы срезов /// </summary> public SrezAdapter SrezAdapter { get; private set; } /// <summary> /// Получить адаптер таблицы копий срезов /// </summary> public SrezAdapter SrezCopyAdapter { get; private set; } /// <summary> /// Заполнить таблицу срезов или таблицу копий срезов данного кэша /// </summary> public void FillSrezTable(bool copy = false) { if (copy) FillSrezTable(SrezTableCopy, SrezCopyAdapter); else FillSrezTable(SrezTable, SrezAdapter); } /// <summary> /// Заполнить таблицу срезов /// </summary> public static void FillSrezTable(SrezTable srezTable, SrezAdapter srezAdapter) { string fileName = srezAdapter.FileName; if (File.Exists(fileName)) { // определение времени последнего изменения файла таблицы срезов DateTime fileModTime = File.GetLastWriteTime(fileName); // загрузка данных, если файл был изменён if (srezTable.FileModTime != fileModTime) { srezAdapter.Fill(srezTable); srezTable.FileModTime = fileModTime; } } else { srezTable.Clear(); } } } /// <summary> /// Данные для усреднения /// </summary> private struct AvgData { /// <summary> /// Сумма значений канала /// </summary> public double Sum { get; set; } /// <summary> /// Количество значений канала /// </summary> public int Cnt { get; set; } } } }
33.949686
103
0.482308
[ "Apache-2.0" ]
AMM-VSU/SCADA
ScadaServer/ScadaServerSvc/MainLogic.Types.cs
12,614
C#
// This software is part of the Autofac IoC container // Copyright © 2015 Autofac Contributors // https://autofac.org // // Permission is hereby granted, free of charge, to any person // obtaining a copy of this software and associated documentation // files (the "Software"), to deal in the Software without // restriction, including without limitation the rights to use, // copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the // Software is furnished to do so, subject to the following // conditions: // // The above copyright notice and this permission notice shall be // included in all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES // OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT // HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, // WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING // FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR // OTHER DEALINGS IN THE SOFTWARE. using System; using System.Diagnostics.CodeAnalysis; using System.Threading.Tasks; using Autofac.Core; using Microsoft.Extensions.DependencyInjection; namespace Autofac.Extensions.DependencyInjection { /// <summary> /// Autofac implementation of the ASP.NET Core <see cref="IServiceProvider"/>. /// </summary> /// <seealso cref="System.IServiceProvider" /> /// <seealso cref="Microsoft.Extensions.DependencyInjection.ISupportRequiredService" /> public partial class AutofacServiceProvider : IServiceProvider, ISupportRequiredService, IDisposable, IAsyncDisposable { private readonly ILifetimeScope _lifetimeScope; private bool _disposed; /// <summary> /// Initializes a new instance of the <see cref="AutofacServiceProvider"/> class. /// </summary> /// <param name="lifetimeScope"> /// The lifetime scope from which services will be resolved. /// </param> public AutofacServiceProvider(ILifetimeScope lifetimeScope) { _lifetimeScope = lifetimeScope; } /// <summary> /// Gets service of type <paramref name="serviceType" /> from the /// <see cref="AutofacServiceProvider" /> and requires it be present. /// </summary> /// <param name="serviceType"> /// An object that specifies the type of service object to get. /// </param> /// <returns> /// A service object of type <paramref name="serviceType" />. /// </returns> /// <exception cref="Autofac.Core.Registration.ComponentNotRegisteredException"> /// Thrown if the <paramref name="serviceType" /> isn't registered with the container. /// </exception> /// <exception cref="Autofac.Core.DependencyResolutionException"> /// Thrown if the object can't be resolved from the container. /// </exception> public object GetRequiredService(Type serviceType) { return _lifetimeScope.Resolve(serviceType); } /// <summary> /// Gets the service object of the specified type. /// </summary> /// <param name="serviceType"> /// An object that specifies the type of service object to get. /// </param> /// <returns> /// A service object of type <paramref name="serviceType" />; or <see langword="null" /> /// if there is no service object of type <paramref name="serviceType" />. /// </returns> public object GetService(Type serviceType) { return _lifetimeScope.ResolveOptional(serviceType); } /// <summary> /// Gets the underlying instance of <see cref="ILifetimeScope" />. /// </summary> public ILifetimeScope LifetimeScope => _lifetimeScope; /// <summary> /// Releases unmanaged and - optionally - managed resources. /// </summary> /// <param name="disposing"> /// <see langword="true" /> to release both managed and unmanaged resources; /// <see langword="false" /> to release only unmanaged resources. /// </param> protected virtual void Dispose(bool disposing) { if (!_disposed) { _disposed = true; if (disposing) { _lifetimeScope.Dispose(); } } } /// <summary> /// Performs application-defined tasks associated with freeing, releasing, or resetting unmanaged resources. /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Performs a dispose operation asynchronously. /// </summary> [SuppressMessage( "Usage", "CA1816:Dispose methods should call SuppressFinalize", Justification = "DisposeAsync should also call SuppressFinalize (see various .NET internal implementations).")] public async ValueTask DisposeAsync() { if (!_disposed) { _disposed = true; await _lifetimeScope.DisposeAsync().ConfigureAwait(false); GC.SuppressFinalize(this); } } } }
38.734266
123
0.624661
[ "MIT" ]
alistairjevans/Autofac.Extensions.DependencyInjection
src/Autofac.Extensions.DependencyInjection/AutofacServiceProvider.cs
5,542
C#
using System.Threading.Tasks; using Armory.People.Domain; namespace Armory.People.Application.Update { public class PersonUpdater { private readonly IPeopleRepository _repository; public PersonUpdater(IPeopleRepository repository) { _repository = repository; } public async Task Update(Person person, string newFirstName, string newSecondName, string newLastname, string newSecondLastName) { person.Update(newFirstName, newSecondName, newLastname, newSecondLastName); await _repository.Update(person); } } }
27.26087
110
0.674641
[ "MIT" ]
cantte/Armory.Api
src/Armory/People/Application/Update/PersonUpdater.cs
627
C#
using System; using System.IO; using System.Reflection; namespace ILG.Codex.CodexR4.GMLiceseManger { class DSLicenseJsonFile { private string _licenseDirectory; private string _licenseFullFilename; private readonly string configFilename = "CodexDSProduction.json"; public DSCodexLicenseFileBase _codexlicensefile; private string GetDSLicDirectory() { string codeBase = Assembly.GetExecutingAssembly().CodeBase; UriBuilder uri = new UriBuilder(codeBase); string path = Uri.UnescapeDataString(uri.Path); return Path.GetDirectoryName(path); } public DSLicenseJsonFile() { _licenseDirectory = GetDSLicDirectory(); _licenseFullFilename = Path.Combine(_licenseDirectory, configFilename); _codexlicensefile = new DSCodexLicenseFileBase(_licenseFullFilename); } public bool CreateIfNotExists() { if (File.Exists(_licenseFullFilename) == false) { var codexlicensefile = new DSCodexLicenseFileBase(_licenseFullFilename); codexlicensefile.WritetoFile(); return true; } else return false; } public void ReadInfo() { _codexlicensefile.ReadFromFile(_licenseFullFilename); } public void SaveInfo() { _codexlicensefile.WritetoFile(); } } }
27.87037
88
0.614618
[ "Unlicense" ]
IrakliLomidze/CodexDS16
CodexDS16.U1.Prev1/TrialRetialUtility/DSLicenseGenerator/DSLicenseGenerator/GMLiceseManger/DSLicenseJsonFile.cs
1,507
C#
using System; namespace WindowsInput.Native { #pragma warning disable 649 /// <summary> /// The MOUSEINPUT structure contains information about a simulated mouse event. (see: http://msdn.microsoft.com/en-us/library/ms646273(VS.85).aspx) /// Declared in Winuser.h, include Windows.h /// </summary> /// <remarks> /// If the mouse has moved, indicated by MOUSEEVENTF_MOVE, dx and dy specify information about that movement. The information is specified as absolute or relative integer values. /// If MOUSEEVENTF_ABSOLUTE value is specified, dx and dy contain normalized absolute coordinates between 0 and 65,535. The event procedure maps these coordinates onto the display surface. Coordinate (0,0) maps onto the upper-left corner of the display surface; coordinate (65535,65535) maps onto the lower-right corner. In a multimonitor system, the coordinates map to the primary monitor. /// Windows 2000/XP: If MOUSEEVENTF_VIRTUALDESK is specified, the coordinates map to the entire virtual desktop. /// If the MOUSEEVENTF_ABSOLUTE value is not specified, dx and dy specify movement relative to the previous mouse event (the last reported position). Positive values mean the mouse moved right (or down); negative values mean the mouse moved left (or up). /// Relative mouse motion is subject to the effects of the mouse speed and the two-mouse threshold values. A user sets these three values with the Pointer Speed slider of the Control Panel's Mouse Properties sheet. You can obtain and set these values using the SystemParametersInfo function. /// The system applies two tests to the specified relative mouse movement. If the specified distance along either the x or y axis is greater than the first mouse threshold value, and the mouse speed is not zero, the system doubles the distance. If the specified distance along either the x or y axis is greater than the second mouse threshold value, and the mouse speed is equal to two, the system doubles the distance that resulted from applying the first threshold test. It is thus possible for the system to multiply specified relative mouse movement along the x or y axis by up to four times. /// </remarks> internal struct MOUSEINPUT { /// <summary> /// Specifies the absolute position of the mouse, or the amount of motion since the last mouse event was generated, depending on the value of the dwFlags member. Absolute data is specified as the x coordinate of the mouse; relative data is specified as the number of pixels moved. /// </summary> public Int32 X; /// <summary> /// Specifies the absolute position of the mouse, or the amount of motion since the last mouse event was generated, depending on the value of the dwFlags member. Absolute data is specified as the y coordinate of the mouse; relative data is specified as the number of pixels moved. /// </summary> public Int32 Y; /// <summary> /// If dwFlags contains MOUSEEVENTF_WHEEL, then mouseData specifies the amount of wheel movement. A positive value indicates that the wheel was rotated forward, away from the user; a negative value indicates that the wheel was rotated backward, toward the user. One wheel click is defined as WHEEL_DELTA, which is 120. /// Windows Vista: If dwFlags contains MOUSEEVENTF_HWHEEL, then dwData specifies the amount of wheel movement. A positive value indicates that the wheel was rotated to the right; a negative value indicates that the wheel was rotated to the left. One wheel click is defined as WHEEL_DELTA, which is 120. /// Windows 2000/XP: IfdwFlags does not contain MOUSEEVENTF_WHEEL, MOUSEEVENTF_XDOWN, or MOUSEEVENTF_XUP, then mouseData should be zero. /// If dwFlags contains MOUSEEVENTF_XDOWN or MOUSEEVENTF_XUP, then mouseData specifies which X buttons were pressed or released. This value may be any combination of the following flags. /// </summary> public UInt32 MouseData; /// <summary> /// A set of bit flags that specify various aspects of mouse motion and button clicks. The bits in this member can be any reasonable combination of the following values. /// The bit flags that specify mouse button status are set to indicate changes in status, not ongoing conditions. For example, if the left mouse button is pressed and held down, MOUSEEVENTF_LEFTDOWN is set when the left button is first pressed, but not for subsequent motions. Similarly, MOUSEEVENTF_LEFTUP is set only when the button is first released. /// You cannot specify both the MOUSEEVENTF_WHEEL flag and either MOUSEEVENTF_XDOWN or MOUSEEVENTF_XUP flags simultaneously in the dwFlags parameter, because they both require use of the mouseData field. /// </summary> public UInt32 Flags; /// <summary> /// Time stamp for the event, in milliseconds. If this parameter is 0, the system will provide its own time stamp. /// </summary> public UInt32 Time; /// <summary> /// Specifies an additional value associated with the mouse event. An application calls GetMessageExtraInfo to obtain this extra information. /// </summary> public IntPtr ExtraInfo; } #pragma warning restore 649 }
94.928571
600
0.74304
[ "Apache-2.0", "MIT" ]
4364354235654345u5432576865432/keeweb
helper/win32/src/KeeWebHelper/WindowsInput/Native/MOUSEINPUT.cs
5,318
C#
namespace FlyweightGame.Contracts { using UI; public interface IRenderable { int X { get; } int Y { get; } AssetType Type { get; } } }
12.785714
34
0.52514
[ "MIT" ]
Supbads/Softuni-Education
03. HighQualityCode 12.15/Demos/18. Design-Patterns-Demo/Design Patterns/Structural/FlyweightGame/Contracts/IRenderable.cs
181
C#
using System; using System.Runtime.Serialization; namespace Commanigy.Iquomi.Api { /// <summary> /// /// </summary> [Serializable()] public enum ResponseStatus { Success, Failure, Rollback, NotAttempted } }
15.733333
36
0.648305
[ "MIT" ]
theill/iquomi
Commanigy.Iquomi.Sdk/ResponseStatus.cs
236
C#
using System.Collections.Generic; using Essensoft.Paylink.Alipay.Response; namespace Essensoft.Paylink.Alipay.Request { /// <summary> /// alipay.overseas.tuition.schoolcredit.confirm /// </summary> public class AlipayOverseasTuitionSchoolcreditConfirmRequest : IAlipayRequest<AlipayOverseasTuitionSchoolcreditConfirmResponse> { /// <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; private Dictionary<string, string> udfParams; //add user-defined text parameters 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 "alipay.overseas.tuition.schoolcredit.confirm"; } public void SetApiVersion(string apiVersion) { this.apiVersion = apiVersion; } public string GetApiVersion() { return apiVersion; } public void PutOtherTextParam(string key, string value) { if (udfParams == null) { udfParams = new Dictionary<string, string>(); } udfParams.Add(key, value); } public IDictionary<string, string> GetParameters() { var parameters = new AlipayDictionary { { "biz_content", BizContent } }; if (udfParams != null) { parameters.AddAll(udfParams); } return parameters; } public AlipayObject GetBizModel() { return bizModel; } public void SetBizModel(AlipayObject bizModel) { this.bizModel = bizModel; } #endregion } }
23.855072
131
0.545261
[ "MIT" ]
Frunck8206/payment
src/Essensoft.Paylink.Alipay/Request/AlipayOverseasTuitionSchoolcreditConfirmRequest.cs
3,318
C#
using System; using System.Collections.Generic; using System.Data; using System.Linq; namespace Jbpc.Common.Excel { public class WorksheetDataTable { private object[,] matrix; private readonly DataTable dataTable = new DataTable(); public DataTable CopyUsedRangeIntoDataTable(string fullyQualifiedWorkbookName, string worksheetName = null) { matrix = WorksheetValues.GetEntireSheet(fullyQualifiedWorkbookName, worksheetName); AddDataTableColumn(); PopulateRows(); return dataTable; } private void PopulateRows() { var names = ColumnHeaders(); for (int i = 2; i < matrix.GetLength(0)+1; i++) { var dataRow = dataTable.Rows.Add(); for (int j = 1; j < names.Count+1; j++) { var cell = matrix[i, j]; var columnName = names[j - 1]; dataRow[columnName] = cell == null ? DBNull.Value : Convert.ChangeType(cell, cell.GetType()); } } } private void AddDataTableColumn() { var columnHeadings = ColumnHeaders(); foreach (var columnName in columnHeadings) dataTable.Columns.Add(columnName); } private List<string> ColumnHeaders() { var list = new List<string>(); for (int i = 1; i < matrix.GetLength(1)+1; i++) { if (matrix[1, i] == null) { break; } list.Add(matrix[1, i].ToString()); } var q = Enumerable.Range(1, list.Count).Zip(list, (x, y) => new {NthCol = x, Name = y}).ToList(); var missingHeader = q.Where(x => x.Name == "").ToList(); var msg = string.Join(", ", missingHeader.Select(x => $"{x.NthCol}) {x.Name}")); if (missingHeader.Any()) throw new ApplicationException($"Missing column headers for Excel import file={msg}"); return list; } } }
30.225352
123
0.514445
[ "MIT" ]
JaniceBPC/Common.Excel
Excel/Utilities/WorksheetDatatable.cs
2,148
C#
using System; namespace My2C2P.Org.BouncyCastle.Crypto.Prng { /// <remarks> /// Takes bytes generated by an underling RandomGenerator and reverses the order in /// each small window (of configurable size). /// <p> /// Access to internals is synchronized so a single one of these can be shared. /// </p> /// </remarks> public class ReversedWindowGenerator : IRandomGenerator { private readonly IRandomGenerator generator; private byte[] window; private int windowCount; public ReversedWindowGenerator( IRandomGenerator generator, int windowSize) { if (generator == null) throw new ArgumentNullException("generator"); if (windowSize < 2) throw new ArgumentException("Window size must be at least 2", "windowSize"); this.generator = generator; this.window = new byte[windowSize]; } /// <summary>Add more seed material to the generator.</summary> /// <param name="seed">A byte array to be mixed into the generator's state.</param> public virtual void AddSeedMaterial( byte[] seed) { lock (this) { windowCount = 0; generator.AddSeedMaterial(seed); } } /// <summary>Add more seed material to the generator.</summary> /// <param name="seed">A long value to be mixed into the generator's state.</param> public virtual void AddSeedMaterial( long seed) { lock (this) { windowCount = 0; generator.AddSeedMaterial(seed); } } /// <summary>Fill byte array with random values.</summary> /// <param name="bytes">Array to be filled.</param> public virtual void NextBytes( byte[] bytes) { doNextBytes(bytes, 0, bytes.Length); } /// <summary>Fill byte array with random values.</summary> /// <param name="bytes">Array to receive bytes.</param> /// <param name="start">Index to start filling at.</param> /// <param name="len">Length of segment to fill.</param> public virtual void NextBytes( byte[] bytes, int start, int len) { doNextBytes(bytes, start, len); } private void doNextBytes( byte[] bytes, int start, int len) { lock (this) { int done = 0; while (done < len) { if (windowCount < 1) { generator.NextBytes(window, 0, window.Length); windowCount = window.Length; } bytes[start + done++] = window[--windowCount]; } } } } }
23.767677
85
0.652784
[ "MIT" ]
2C2P/My2C2PPKCS7
My2C2PPKCS7/crypto/prng/ReversedWindowGenerator.cs
2,353
C#
using System.Collections.Generic; using Microsoft.VisualStudio.TestTools.UnitTesting; using Reusable.OneTo1; using Reusable.OneTo1.Converters; using Reusable.OneTo1.Converters.Collections.Generic; using Reusable.Utilities.MSTest; namespace Reusable.Tests.OneTo1 { [TestClass] public class HashSetTest : ConverterTest { [TestMethod] public void Convert_StringArray_HashSetInt32() { var result = TypeConverter.Empty .Add<StringToInt32Converter>() .Add<EnumerableToHashSetConverter>() .Convert(new[] { "3", "7" }, typeof(HashSet<int>)) as HashSet<int>; Assert.IsNotNull(result); Assert.That.Collection().CountEquals(2, result); Assert.IsTrue(result.Contains(3)); Assert.IsTrue(result.Contains(7)); } //[TestMethod] //public void Convert_StringArray_HashSetInt32_2() //{ // var result = // TypeConverter.Empty // .Add<StringToInt32Converter>() // .Add<EnumerableToHashSetConverter<int>>() // .Convert(new[] { "3", "7" }, typeof(HashSet<int>)) as HashSet<int>; // Assert.IsNotNull(result); // Assert.That.Collection().CountEquals(2, result); // Assert.IsTrue(result.Contains(3)); // Assert.IsTrue(result.Contains(7)); //} [TestMethod] public void Convert_Int32Array_HashSetString() { var result = TypeConverter.Empty .Add<Int32ToStringConverter>() .Add<EnumerableToHashSetConverter>() .Convert(new[] { 3, 7 }, typeof(HashSet<string>)) as HashSet<string>; Assert.IsNotNull(result); Assert.That.Collection().CountEquals(2, result); Assert.IsTrue(result.Contains("3")); Assert.IsTrue(result.Contains("7")); } } }
34.844828
89
0.566551
[ "MIT" ]
he-dev/DotNetBits
Reusable.Tests.MSTest/src/OneTo1/impl/Collections/Generic/HashSetTest.cs
2,021
C#
// Project: Daggerfall Tools For Unity // Copyright: Copyright (C) 2009-2020 Daggerfall Workshop // Web Site: http://www.dfworkshop.net // License: MIT License (http://www.opensource.org/licenses/mit-license.php) // Source Code: https://github.com/Interkarma/daggerfall-unity // Original Author: Gavin Clayton (interkarma@dfworkshop.net) // Contributors: // // Notes: // using UnityEngine; using System.Collections; using DaggerfallWorkshop.Utility; using Mirror; namespace DaggerfallWorkshop.Game { /// <summary> /// Peer this with Player and PlayerEnterExit to change ambient light based on player surroundings. /// For example, Daggerfall scales ambient light up and down in dungeons with castle blocks (e.g. Wayrest). /// Ambient light is dimmed when player leaves castle block and brightened on return. /// </summary> public class PlayerAmbientLight : NetworkBehaviour { public Color ExteriorNoonAmbientLight = new Color(0.9f, 0.9f, 0.9f); public Color ExteriorNightAmbientLight = new Color(0.25f, 0.25f, 0.25f); public Color InteriorAmbientLight = new Color(0.18f, 0.18f, 0.18f); public Color InteriorNightAmbientLight = new Color(0.20f, 0.18f, 0.20f); public Color DungeonAmbientLight = new Color(0.12f, 0.12f, 0.12f); public Color CastleAmbientLight = new Color(0.58f, 0.58f, 0.58f); public Color SpecialAreaLight = new Color(0.58f, 0.58f, 0.58f); public float FadeDuration = 3f; public float FadeStep = 0.1f; PlayerEnterExit playerEnterExit; SunlightManager sunlightManager; Color targetAmbientLight; bool fadeRunning; void Start() { playerEnterExit = GetComponent<PlayerEnterExit>(); sunlightManager = GameManager.Instance.SunlightManager; StartCoroutine(ManageAmbientLight()); } void Update() { if (UnityEngine.RenderSettings.ambientLight != targetAmbientLight && !fadeRunning) StartCoroutine(ChangeAmbientLight()); } // Polls PlayerEnterExit a few times each second to detect if player environment has changed IEnumerator ManageAmbientLight() { const float pollSpeed = 1f / 3f; while (playerEnterExit) { if (!playerEnterExit.IsPlayerInside && !playerEnterExit.IsPlayerInsideDungeon) { targetAmbientLight = CalcDaytimeAmbientLight(); } else if (playerEnterExit.IsPlayerInside && !playerEnterExit.IsPlayerInsideDungeon) { if (DaggerfallUnity.Instance.WorldTime.Now.IsNight) targetAmbientLight = InteriorNightAmbientLight; else targetAmbientLight = InteriorAmbientLight; } else if (playerEnterExit.IsPlayerInside && playerEnterExit.IsPlayerInsideDungeon) { if (playerEnterExit.IsPlayerInsideDungeonCastle) targetAmbientLight = CastleAmbientLight; else if (playerEnterExit.IsPlayerInsideSpecialArea) targetAmbientLight = SpecialAreaLight; else targetAmbientLight = DungeonAmbientLight * DaggerfallUnity.Settings.DungeonAmbientLightScale; } yield return new WaitForSeconds(pollSpeed); } } IEnumerator ChangeAmbientLight() { if (!playerEnterExit.IsPlayerInsideDungeon) { // Do not smoothly change ambient light outside of dungeons fadeRunning = false; RenderSettings.ambientLight = targetAmbientLight; yield break; } else { // Smoothly lerp ambient light inside dungeons when target ambient level changes fadeRunning = true; float progress = 0; float increment = FadeStep / FadeDuration; Color startColor = RenderSettings.ambientLight; while (progress < 1) { RenderSettings.ambientLight = Color.Lerp(startColor, targetAmbientLight, progress); progress += increment; yield return new WaitForSeconds(FadeStep); } RenderSettings.ambientLight = targetAmbientLight; fadeRunning = false; } } Color CalcDaytimeAmbientLight() { float scale = sunlightManager.DaylightScale * sunlightManager.ScaleFactor; Color startColor = ExteriorNightAmbientLight * DaggerfallUnity.Settings.NightAmbientLightScale; return Color.Lerp(startColor, ExteriorNoonAmbientLight, scale); } } }
41.516667
117
0.606985
[ "MIT" ]
smurf211/DaggerfallUnityMP
Assets/Scripts/Game/PlayerAmbientLight.cs
4,982
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; public class SpawnAsteroids : MonoBehaviour { public GameObject asteroidsPrefab; public float respawnTime = 5f; public Vector2 screenBounds; // Start is called before the first frame update void Start() { screenBounds = Camera.main.ScreenToWorldPoint(new Vector3(Screen.width, Screen.height, Camera.main.transform.position.z)); StartCoroutine(asteroidsWave()); } private void spawnAsteroids() { GameObject a = Instantiate(asteroidsPrefab) as GameObject; a.transform.position = new Vector2(screenBounds.x + 1, Random.Range(-screenBounds.y, screenBounds.y)); } IEnumerator asteroidsWave() { while(true) { yield return new WaitForSeconds(respawnTime); spawnAsteroids(); } } }
29.1
130
0.68614
[ "MIT" ]
wahudamon/AsteroidsInSpace
Assets/Scripts/SpawnAsteroids.cs
875
C#
using Microsoft.Extensions.Logging; using System.Threading.Tasks; namespace AzureDeveloperTemplates.FunctionAppWithDependencyInjection.Services { class MailService : IMailService { private readonly MailServiceSettings _mailServiceSettings; private readonly ILogger<MailService> _log; public MailService(MailServiceSettings mailServiceSettings, ILogger<MailService> log) { _mailServiceSettings = mailServiceSettings; _log = log; } public async Task SendInvitation(string emailAddress) { _log.LogInformation($"Email sent to: {emailAddress} from: {_mailServiceSettings.SMTPFromAddress}"); } } }
30.782609
111
0.70339
[ "MIT" ]
CurlyBytes/AzureDeveloperTemplates
src/azure-function-with-dependency-injection-template/AzureDeveloperTemplates.FunctionAppWithDependencyInjection/Services/MailService.cs
710
C#
using Coypu.Finders; using NSpec; using NUnit.Framework; namespace Coypu.Drivers.Tests { internal class When_finding_windows : DriverSpecs { [Test] public void Finds_by_name() { using (Driver) { OpenPopup(); var window = Window("popUpWindowName", Root, DefaultOptions); window.Text.should_contain("I am a pop up window"); FindPopUpLink(); } } private static void OpenPopup() { Driver.Click(FindPopUpLink()); } private static void OpenPopup2() { Driver.Click(FindPopUp2Link()); } private static ElementFound FindPopUpLink() { return Link("Open pop up window", Root, DefaultOptions); } private static ElementFound FindPopUp2Link() { return Link("Open pop up window 2", Root, DefaultOptions); } private static ElementFound FindPopUp() { return FindWindow("Pop Up Window"); } [Test] public void Finds_by_title() { using (Driver) { OpenPopup(); FindPopUp().Text.should_contain("I am a pop up window"); FindPopUpLink(); } } [Test] public void Finds_by_substring_title() { using (Driver) { OpenPopup2(); FindPopUp().Text.should_contain("I am a pop up window 2"); FindPopUp2Link(); } } [Test] public void Finds_by_exact_title_over_substring() { using (Driver) { OpenPopup(); OpenPopup2(); FindPopUp().Text.should_contain("I am a pop up window"); FindPopUpLink(); } } [Test] public void Finds_scoped_by_window() { using (Driver) { OpenPopup(); var popUp = new DriverScope(DefaultSessionConfiguration, new WindowFinder(Driver, "Pop Up Window", Root, DefaultOptions), Driver, null, null, null, DisambiguationStrategy); Id("popUpButtonId", popUp); FindPopUpLink(); } } [Test] public void Errors_on_no_such_window() { using (Driver) { OpenPopup(); Assert.Throws<MissingWindowException>(() => FindWindow("Not A Window")); } } private static ElementFound FindWindow(string locator) { return Window(locator, Root, DefaultOptions); } [Test] public void Errors_on_window_closed() { using (Driver) { OpenPopup(); var popUp = new DriverScope(DefaultSessionConfiguration, new WindowFinder(Driver, "Pop Up Window", Root, DefaultOptions), Driver, null, null, null, DisambiguationStrategy); Driver.ExecuteScript("self.close();", popUp); Assert.Throws<MissingWindowException>(() => FindPopUp()); } } } }
27.092308
138
0.465645
[ "Unlicense", "MIT" ]
KMASubhani/coypu
src/Coypu.Drivers.Tests/When_finding_windows.cs
3,524
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // 어셈블리에 대한 일반 정보는 다음 특성 집합을 통해 // 제어됩니다. 어셈블리와 관련된 정보를 수정하려면 // 이러한 특성 값을 변경하세요. [assembly: AssemblyTitle("PasswordFinder")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PasswordFinder")] [assembly: AssemblyCopyright("Copyright © 2018")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // ComVisible을 false로 설정하면 이 어셈블리의 형식이 COM 구성 요소에 // 표시되지 않습니다. COM에서 이 어셈블리의 형식에 액세스하려면 // 해당 형식에 대해 ComVisible 특성을 true로 설정하세요. [assembly: ComVisible(false)] // 이 프로젝트가 COM에 노출되는 경우 다음 GUID는 typelib의 ID를 나타냅니다. [assembly: Guid("e9c5fdf9-2687-4422-8b8a-013a437a634a")] // 어셈블리의 버전 정보는 다음 네 가지 값으로 구성됩니다. // // 주 버전 // 부 버전 // 빌드 번호 // 수정 버전 // // 모든 값을 지정하거나 아래와 같이 '*'를 사용하여 빌드 번호 및 수정 번호가 자동으로 // 지정되도록 할 수 있습니다. // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
28.72973
56
0.700847
[ "MIT" ]
Re-Coma/Password_Finder
PasswordFinder/Properties/AssemblyInfo.cs
1,504
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the kinesisanalyticsv2-2018-05-23.normal.json service model. */ using System; using Amazon.Runtime; using Amazon.Util.Internal; namespace Amazon.KinesisAnalyticsV2 { /// <summary> /// Configuration for accessing Amazon KinesisAnalyticsV2 service /// </summary> public partial class AmazonKinesisAnalyticsV2Config : ClientConfig { private static readonly string UserAgentString = InternalSDKUtils.BuildUserAgentString("3.7.5.1"); private string _userAgent = UserAgentString; /// <summary> /// Default constructor /// </summary> public AmazonKinesisAnalyticsV2Config() { this.AuthenticationServiceName = "kinesisanalytics"; } /// <summary> /// The constant used to lookup in the region hash the endpoint. /// </summary> public override string RegionEndpointServiceName { get { return "kinesisanalytics"; } } /// <summary> /// Gets the ServiceVersion property. /// </summary> public override string ServiceVersion { get { return "2018-05-23"; } } /// <summary> /// Gets the value of UserAgent property. /// </summary> public override string UserAgent { get { return _userAgent; } } } }
26.7875
116
0.598227
[ "Apache-2.0" ]
bgrainger/aws-sdk-net
sdk/src/Services/KinesisAnalyticsV2/Generated/AmazonKinesisAnalyticsV2Config.cs
2,143
C#
using Newtonsoft.Json; namespace Wikiled.Delfi.Readers.Comments { public class CommentsResult { [JsonProperty("data")] public Data Data { get; set; } } }
18.3
40
0.63388
[ "MIT" ]
AndMu/Wikiled.Delfi
src/Wikiled.Delfi/Readers/Comments/CommentsResult.cs
185
C#
//----------------------------------------------------------------------- // <copyright file="DB2EventsByTagSpec.cs" company="Akka.NET Project"> // Copyright (C) 2017-2017 NA <http://www.NA.com> // Copyright (C) 2013-2016 Akka.NET project <https://github.com/akkadotnet/akka.net> // </copyright> //----------------------------------------------------------------------- using Akka.Configuration; using Akka.Persistence.Query.Sql; using Akka.Persistence.Sql.TestKit; using Akka.Util.Internal; using Xunit; using Xunit.Abstractions; namespace Akka.Persistence.DB2.Tests.Query { [Collection("DB2Spec")] public class DB2EventsByTagSpec : EventsByTagSpec { public static Config Config => ConfigurationFactory.ParseString($@" akka.loglevel = INFO akka.test.single-expect-default = 10s akka.persistence.journal.plugin = ""akka.persistence.journal.DB2"" akka.persistence.journal.DB2 {{ event-adapters {{ color-tagger = ""Akka.Persistence.Sql.TestKit.ColorTagger, Akka.Persistence.Sql.TestKit"" }} event-adapter-bindings = {{ ""System.String"" = color-tagger }} class = ""Akka.Persistence.DB2.Journal.DB2Journal, Akka.Persistence.DB2"" plugin-dispatcher = ""akka.actor.default-dispatcher"" table-name = EventJournal schema-name = dbo auto-initialize = on connection-string-name = ""TestDb"" refresh-interval = 1s }}") .WithFallback(SqlReadJournal.DefaultConfiguration()); public DB2EventsByTagSpec(ITestOutputHelper output) : base(Config, output) { DbUtils.Initialize(); } protected override void Dispose(bool disposing) { base.Dispose(disposing); DbUtils.Clean(); } } }
37.826923
108
0.553127
[ "Apache-2.0" ]
askids/Akka.Persistence.DB2
src/Akka.Persistence.DB2.Tests/Query/DB2EventsByTagSpec.cs
1,969
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using MinerPlugin; using MinerPluginLoader; using System.IO.Compression; using MinerPluginToolkitV1; using MinerPluginToolkitV1.Interfaces; using NHM.Common.Enums; using MinerPluginToolkitV1.Configs; namespace MinerPluginsPacker { class Program { internal class MajorMinorVersion { internal MajorMinorVersion(int major, int minor) { this.major = major; this.minor = minor; } public int major { get; private set; } public int minor { get; private set; } } internal class PluginPackageInfoForJson : PluginPackageInfo { public new MajorMinorVersion PluginVersion { get; set; } } private static Dictionary<string, List<string>> TransformToPluginPackageInfoSupportedDevicesAlgorithms(Dictionary<DeviceType, List<AlgorithmType>> supportedDevicesAlgorithms) { var ret = new Dictionary<string, List<string>>(); foreach (var kvp in supportedDevicesAlgorithms) { var stringKey = kvp.Key.ToString(); var stringAlgos = kvp.Value.Select(algo => algo.ToString()).ToList(); ret[stringKey] = stringAlgos; } return ret; } private static List<PluginPackageInfoForJson> PluginPackageInfos = new List<PluginPackageInfoForJson>(); private static string GetPluginPackageName(IMinerPlugin plugin) { // TODO workaround to check if it is built with the Toolkit var isToolkitMiner = plugin is IInitInternals; var versionStr = $"v{plugin.Version.Major}.{plugin.Version.Minor}"; if (isToolkitMiner) { versionStr = $"{versionStr}_mptoolkitV1"; } var pluginZipFileName = $"{plugin.Name}_{versionStr}_{plugin.PluginUUID}.zip"; return pluginZipFileName; } private static void CheckPluginMetaData(IMinerPlugin plugin) { if (plugin is IPluginSupportedAlgorithmsSettings pluginSettings) { var supportedDevicesAlgorithms = pluginSettings.SupportedDevicesAlgorithmsDict(); var supportedDevicesAlgorithmsCount = supportedDevicesAlgorithms.Select(dict => dict.Value.Count).Sum(); if (supportedDevicesAlgorithmsCount == 0) throw new Exception($"{plugin.Name}-{plugin.PluginUUID} NO algorithms"); foreach (var kvp in supportedDevicesAlgorithms) { foreach (var algo in kvp.Value) { var name = pluginSettings.AlgorithmName(algo); if (string.IsNullOrEmpty(name) || string.IsNullOrWhiteSpace(name)) { throw new Exception($"{plugin.Name}-{plugin.PluginUUID} Invalid name '{name}' for algorithm type '{algo.ToString()}'"); } } } } } private static int[] _supportedMajorverLinks = new int[] { 3, 4, 5, 6, 7 }; private static bool IsMajorVersionLinkSupported(int major) { return _supportedMajorverLinks.Contains(major); } private static void AddPluginToPluginPackageInfos(IMinerPlugin plugin) { var version = new MajorMinorVersion(plugin.Version.Major, plugin.Version.Minor); string pluginPackageURL = null; if (IsMajorVersionLinkSupported(version.major)) { pluginPackageURL = $"https://github.com/nicehash/NHM_MinerPluginsDownloads/releases/download/v{version.major}.x/" + GetPluginPackageName(plugin); } else { throw new Exception($"Plugin version '{version.major}' not supported. Make sure you add the download link for this version"); } string minerPackageURL = null; if (plugin is IMinerBinsSource binsSource) { minerPackageURL = binsSource.GetMinerBinsUrlsForPlugin().FirstOrDefault(); } var binaryVersion = "N/A"; // TODO binary version if (plugin is IGetMinerBinaryVersion binVersionGetter) { binaryVersion = binVersionGetter.GetMinerBinaryVersion(); } PluginMetaInfo pluginMetaInfo = null; if (plugin is IGetPluginMetaInfo pluginMetaInfoGetter) { pluginMetaInfo = pluginMetaInfoGetter.GetPluginMetaInfo(); } if (pluginMetaInfo == null) return; var packageInfo = new PluginPackageInfoForJson { PluginUUID = plugin.PluginUUID, PluginAuthor = "info@nicehash.com", PluginName = plugin.Name, PluginVersion = version, PluginPackageURL = pluginPackageURL, MinerPackageURL = minerPackageURL, SupportedDevicesAlgorithms = TransformToPluginPackageInfoSupportedDevicesAlgorithms(pluginMetaInfo.SupportedDevicesAlgorithms), // TODO enhance this with the bins version PluginDescription = $"Miner Binary Version '{binaryVersion}'.\n\n" + pluginMetaInfo.PluginDescription }; PluginPackageInfos.Add(packageInfo); } // TODO add more options static void Main(string[] args) { PluginBase.IS_CALLED_FROM_PACKER = true; if (args.Length < 1) { Console.WriteLine("Set miner plugins root path"); return; } //var exePath = Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location); var exePath = Environment.CurrentDirectory; var pluginPackagesFolder = Path.Combine(exePath, "plugins_packages"); var pluginsSearchRoot = args[0]; // get all managed plugin dll's var dllFiles = Directory.GetFiles(pluginsSearchRoot, "*.dll", SearchOption.AllDirectories) .Where(filePath => !filePath.Contains("MinerPlugin") && filePath.Contains("net45") && filePath.Contains("Release") && !filePath.Contains("bin")).ToList(); var packedPlugins = new HashSet<string>(); if (Directory.Exists(pluginPackagesFolder)) { Console.WriteLine("Deleting old plugins packages"); Directory.Delete(pluginPackagesFolder, true); } if (!Directory.Exists(pluginPackagesFolder)) { Directory.CreateDirectory(pluginPackagesFolder); } // what plugins to bundle var bundlePlugins = new List<string> { "2257f160-7236-11e9-b20c-f9f12eb6d835", // CCMinerTpruvotPlugin "70984aa0-7236-11e9-b20c-f9f12eb6d835", // ClaymoreDual14Plugin //"92fceb00-7236-11e9-b20c-f9f12eb6d835", // CPUMinerPlugin "1b7019d0-7237-11e9-b20c-f9f12eb6d835", // GMinerPlugin "435f0820-7237-11e9-b20c-f9f12eb6d835", // LolMinerPlugin "59bba2c0-b1ef-11e9-8e4e-bb1e2c6e76b4", // MiniZPlugin "6c07f7a0-7237-11e9-b20c-f9f12eb6d835", // NBMinerPlugin "f5d4a470-e360-11e9-a914-497feefbdfc8", // PhoenixPlugin "abc3e2a0-7237-11e9-b20c-f9f12eb6d835", // TeamRedMinerPlugin "d47d9b00-7237-11e9-b20c-f9f12eb6d835", // TRexPlugin //"3d4e56b0-7238-11e9-b20c-f9f12eb6d835", // XmrStakPlugin "5532d300-7238-11e9-b20c-f9f12eb6d835", // ZEnemyPlugin //"4aec5ec0-10f8-11ea-bad3-8dea21141bbb", // XmrStakRxPlugin "1046ea50-c261-11e9-8e4e-bb1e2c6e76b4", // XMRig }; var bundlePluginsDlls = new Dictionary<string, string>(); foreach (var filePath in dllFiles) { var dllDir = Path.GetDirectoryName(filePath); var loaded = MinerPluginHost.LoadPlugin(dllDir); if (loaded.Count() == 0) { // log what we couldn't load and continue Console.WriteLine($"Skipping: {filePath}"); continue; } var newPlugins = MinerPluginHost.MinerPlugin .Where(kvp => packedPlugins.Contains(kvp.Key) == false) .Select(kvp => kvp.Value); foreach (var plugin in newPlugins) { try { CheckPluginMetaData(plugin); } catch (Exception e) { Console.WriteLine($"\t\tCheckPluginMetaData ERROR!!!!!!!!! {e.Message}"); } } foreach (var plugin in newPlugins) { try { if (bundlePlugins.Contains(plugin.PluginUUID)) { bundlePluginsDlls.Add(plugin.PluginUUID, filePath); } var pluginZipFileName = GetPluginPackageName(plugin); var dllPackageZip = Path.Combine(pluginPackagesFolder, pluginZipFileName); Console.WriteLine($"Packaging: {dllPackageZip}"); var fileName = Path.GetFileName(filePath); using (var archive = ZipFile.Open(dllPackageZip, ZipArchiveMode.Create)) { archive.CreateEntryFromFile(filePath, fileName); } packedPlugins.Add(plugin.PluginUUID); AddPluginToPluginPackageInfos(plugin); } catch(Exception e) { Console.WriteLine($"\t\t{e.Message}"); } } } try { var preinstalledDlls = Path.Combine(exePath, "miner_plugins"); if (!Directory.Exists(preinstalledDlls)) { Directory.CreateDirectory(preinstalledDlls); } foreach (var kvp in bundlePluginsDlls) { var preinstalledDllPlugin = Path.Combine(exePath, "miner_plugins", kvp.Key); var fileName = Path.GetFileName(kvp.Value); var dllPath = Path.Combine(preinstalledDllPlugin, fileName); if (!Directory.Exists(preinstalledDllPlugin)) { Directory.CreateDirectory(preinstalledDllPlugin); } File.Copy(kvp.Value, dllPath); } } catch (Exception e) { Console.WriteLine($"\t\t{e.Message}"); } // dump our plugin packages InternalConfigs.WriteFileSettings(Path.Combine(pluginPackagesFolder, "update.json"), PluginPackageInfos); try { var deleteFolder = Path.Combine(exePath, "miner_plugins", "BrokenMinerPluginUUID"); Directory.Delete(deleteFolder, true); } catch (Exception) { } } } }
41.498221
182
0.550982
[ "MIT" ]
ahelguerrero/NiceHashMiner
src/Tools/MinerPluginsPacker/Program.cs
11,663
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace _3Prime { class Program { static void Main(string[] args) { var n = int.Parse(Console.ReadLine()); var prime = 1; if (n > 1) { for (int currentN = 2; currentN < n; currentN++) { if (n % currentN == 0) { prime = 0; break; } } } else prime = 0; if (prime == 1) Console.WriteLine("Prime"); else Console.WriteLine("Not Prime"); } } }
20.973684
64
0.387704
[ "MIT" ]
viksuper555/Csharp-Programming
ComplicatedLoops12/3Prime/Program.cs
799
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace PrintScreenNinja.Views { /// <summary> /// Configuration.xaml の相互作用ロジック /// </summary> public partial class Configuration : Window { public Configuration() { InitializeComponent(); } } }
21.714286
47
0.712171
[ "MIT" ]
nin-neko/PrintScreenNinja
PrintScreenNinja/Views/Configuration.xaml.cs
628
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Общие сведения об этой сборке предоставляются следующим набором // набора атрибутов. Измените значения этих атрибутов, чтобы изменить сведения, // связанные со сборкой. [assembly: AssemblyTitle("IbmMqClient")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("IbmMqClient")] [assembly: AssemblyCopyright("Copyright © 2019")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми // для компонентов COM. Если необходимо обратиться к типу в этой сборке через // COM, задайте атрибуту ComVisible значение TRUE для этого типа. [assembly: ComVisible(false)] // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM [assembly: Guid("53e6d25c-e812-48b3-a3ef-ee67b7539730")] // Сведения о версии сборки состоят из следующих четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер сборки // Редакция // // Можно задать все значения или принять номер сборки и номер редакции по умолчанию. // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.513514
99
0.763509
[ "MIT" ]
mustaddon/IbmMqClient
IbmMqClient/Properties/AssemblyInfo.cs
2,005
C#
// Copyright (c) Brock Allen & Dominick Baier. All rights reserved. // Licensed under the Apache License, Version 2.0. See LICENSE in the project root for license information. using IdentityModel; using IdentityServer4.Configuration; using IdentityServer4.Extensions; using IdentityServer4.Models; using IdentityServer4.Services; using IdentityServer4.Stores; using Microsoft.Extensions.Logging; using System; using System.Collections.Specialized; using System.Diagnostics.Eventing.Reader; using System.IdentityModel.Tokens.Jwt; using System.Linq; using System.Security.Claims; using System.Security.Cryptography; using System.Threading.Tasks; using IdentityServer4.Logging.Models; namespace IdentityServer4.Validation { internal class AuthorizeRequestValidator : IAuthorizeRequestValidator { private readonly IdentityServerOptions _options; private readonly IClientStore _clients; private readonly ICustomAuthorizeRequestValidator _customValidator; private readonly IRedirectUriValidator _uriValidator; private readonly ScopeValidator _scopeValidator; private readonly IUserSession _userSession; private readonly JwtRequestValidator _jwtRequestValidator; private readonly JwtRequestUriHttpClient _jwtRequestUriHttpClient; private readonly ILogger _logger; private readonly ResponseTypeEqualityComparer _responseTypeEqualityComparer = new ResponseTypeEqualityComparer(); public AuthorizeRequestValidator( IdentityServerOptions options, IClientStore clients, ICustomAuthorizeRequestValidator customValidator, IRedirectUriValidator uriValidator, ScopeValidator scopeValidator, IUserSession userSession, JwtRequestValidator jwtRequestValidator, JwtRequestUriHttpClient jwtRequestUriHttpClient, ILogger<AuthorizeRequestValidator> logger) { _options = options; _clients = clients; _customValidator = customValidator; _uriValidator = uriValidator; _scopeValidator = scopeValidator; _jwtRequestValidator = jwtRequestValidator; _userSession = userSession; _jwtRequestUriHttpClient = jwtRequestUriHttpClient; _logger = logger; } public async Task<AuthorizeRequestValidationResult> ValidateAsync(NameValueCollection parameters, ClaimsPrincipal subject = null) { _logger.LogDebug("Start authorize request protocol validation"); var request = new ValidatedAuthorizeRequest { Options = _options, Subject = subject ?? Principal.Anonymous, Raw = parameters ?? throw new ArgumentNullException(nameof(parameters)) }; // load request object var roLoadResult = await LoadRequestObjectAsync(request); if (roLoadResult.IsError) { return roLoadResult; } // load client_id var loadClientResult = await LoadClientAsync(request); if (loadClientResult.IsError) { return loadClientResult; } // validate request object var roValidationResult = await ValidateRequestObjectAsync(request); if (roValidationResult.IsError) { return roValidationResult; } // validate client_id and redirect_uri var clientResult = await ValidateClientAsync(request); if (clientResult.IsError) { return clientResult; } // state, response_type, response_mode var mandatoryResult = ValidateCoreParameters(request); if (mandatoryResult.IsError) { return mandatoryResult; } // scope, scope restrictions and plausability var scopeResult = await ValidateScopeAsync(request); if (scopeResult.IsError) { return scopeResult; } // nonce, prompt, acr_values, login_hint etc. var optionalResult = await ValidateOptionalParametersAsync(request); if (optionalResult.IsError) { return optionalResult; } // custom validator _logger.LogDebug("Calling into custom validator: {type}", _customValidator.GetType().FullName); var context = new CustomAuthorizeRequestValidationContext { Result = new AuthorizeRequestValidationResult(request) }; await _customValidator.ValidateAsync(context); var customResult = context.Result; if (customResult.IsError) { LogError("Error in custom validation", customResult.Error, request); return Invalid(request, customResult.Error, customResult.ErrorDescription); } _logger.LogTrace("Authorize request protocol validation successful"); return Valid(request); } private async Task<AuthorizeRequestValidationResult> LoadRequestObjectAsync(ValidatedAuthorizeRequest request) { var jwtRequest = request.Raw.Get(OidcConstants.AuthorizeRequest.Request); var jwtRequestUri = request.Raw.Get(OidcConstants.AuthorizeRequest.RequestUri); if (jwtRequest.IsPresent() && jwtRequestUri.IsPresent()) { LogError("Both request and request_uri are present", request); return Invalid(request, description: "Only one request parameter is allowed"); } if (_options.Endpoints.EnableJwtRequestUri) { if (jwtRequestUri.IsPresent()) { // 512 is from the spec if (jwtRequestUri.Length > 512) { LogError("request_uri is too long", request); return Invalid(request, description: "request_uri is too long"); } var jwt = await _jwtRequestUriHttpClient.GetJwtAsync(jwtRequestUri, request.Client); if (jwt.IsMissing()) { LogError("no value returned from request_uri", request); return Invalid(request, description: "no value returned from request_uri"); } jwtRequest = jwt; } } // check length restrictions if (jwtRequest.IsPresent()) { if (jwtRequest.Length >= _options.InputLengthRestrictions.Jwt) { LogError("request value is too long", request); return Invalid(request, description: "Invalid request value"); } } request.RequestObject = jwtRequest; return Valid(request); } private async Task<AuthorizeRequestValidationResult> LoadClientAsync(ValidatedAuthorizeRequest request) { ////////////////////////////////////////////////////////// // client_id must be present (either on the query string or the request object) ///////////////////////////////////////////////////////// var clientId = request.Raw.Get(OidcConstants.AuthorizeRequest.ClientId); if (clientId.IsMissing() && request.RequestObject.IsPresent()) { clientId = await _jwtRequestValidator.LoadClientId(request.RequestObject); } if (clientId.IsMissingOrTooLong(_options.InputLengthRestrictions.ClientId)) { LogError("client_id is missing or too long", request); return Invalid(request, description: "Invalid client_id"); } request.ClientId = clientId; ////////////////////////////////////////////////////////// // check for valid client ////////////////////////////////////////////////////////// var client = await _clients.FindEnabledClientByIdAsync(request.ClientId); if (client == null) { LogError("Unknown client or not enabled", request.ClientId, request); return Invalid(request, OidcConstants.AuthorizeErrors.UnauthorizedClient, "Unknown client or client not enabled"); } request.SetClient(client); return Valid(request); } private async Task<AuthorizeRequestValidationResult> ValidateRequestObjectAsync(ValidatedAuthorizeRequest request) { ////////////////////////////////////////////////////////// // validate request object ///////////////////////////////////////////////////////// if (request.RequestObject.IsPresent()) { // validate the request JWT for this client var jwtRequestValidationResult = await _jwtRequestValidator.ValidateAsync(request.Client, request.RequestObject); if (jwtRequestValidationResult.IsError) { LogError("request JWT validation failure", request); return Invalid(request, description: "Invalid JWT request"); } // validate response_type match var responseType = request.Raw.Get(OidcConstants.AuthorizeRequest.ResponseType); if (responseType != null) { if (jwtRequestValidationResult.Payload.TryGetValue(OidcConstants.AuthorizeRequest.ResponseType, out var payloadResponseType)) { if (payloadResponseType != responseType) { LogError("response_type in JWT payload does not match response_type in request", request); return Invalid(request, description: "Invalid JWT request"); } } } if (jwtRequestValidationResult.Payload.TryGetValue(OidcConstants.AuthorizeRequest.ClientId, out var payloadClientId)) { var queryClientId = request.Raw.Get(OidcConstants.AuthorizeRequest.ClientId); if (queryClientId.IsPresent() && !string.Equals(queryClientId, payloadClientId, StringComparison.Ordinal)) { LogError("client_id in JWT payload does not match client_id in request", request); return Invalid(request, description: "Invalid JWT request"); } } else { LogError("client_id is missing in JWT payload", request); return Invalid(request, description: "Invalid JWT request"); } // merge jwt payload values into original request parameters foreach (var key in jwtRequestValidationResult.Payload.Keys) { var value = jwtRequestValidationResult.Payload[key]; // todo: overwrite or error? // var qsValue = request.Raw.Get(key); // if (qsValue != null) // { // if (!string.Equals(value, qsValue, StringComparison.Ordinal)) // { // LogError("parameter mismatch between request object and query string parameter.", request); // return Invalid(request, description: "Invalid JWT request"); // } // } request.Raw.Set(key, value); } request.RequestObjectValues = jwtRequestValidationResult.Payload; } return Valid(request); } private async Task<AuthorizeRequestValidationResult> ValidateClientAsync(ValidatedAuthorizeRequest request) { ////////////////////////////////////////////////////////// // check request object requirement ////////////////////////////////////////////////////////// if (request.Client.RequireRequestObject) { if (!request.RequestObjectValues.Any()) { return Invalid(request, description: "Client must use request object, but no request or request_uri parameter present"); } } ////////////////////////////////////////////////////////// // redirect_uri must be present, and a valid uri ////////////////////////////////////////////////////////// var redirectUri = request.Raw.Get(OidcConstants.AuthorizeRequest.RedirectUri); if (redirectUri.IsMissingOrTooLong(_options.InputLengthRestrictions.RedirectUri)) { LogError("redirect_uri is missing or too long", request); return Invalid(request, description:"Invalid redirect_uri"); } if (!Uri.TryCreate(redirectUri, UriKind.Absolute, out var _)) { LogError("malformed redirect_uri", redirectUri, request); return Invalid(request, description: "Invalid redirect_uri"); } ////////////////////////////////////////////////////////// // check if client protocol type is oidc ////////////////////////////////////////////////////////// if (request.Client.ProtocolType != IdentityServerConstants.ProtocolTypes.OpenIdConnect) { LogError("Invalid protocol type for OIDC authorize endpoint", request.Client.ProtocolType, request); return Invalid(request, OidcConstants.AuthorizeErrors.UnauthorizedClient, description: "Invalid protocol"); } ////////////////////////////////////////////////////////// // check if redirect_uri is valid ////////////////////////////////////////////////////////// if (await _uriValidator.IsRedirectUriValidAsync(redirectUri, request.Client) == false) { LogError("Invalid redirect_uri", redirectUri, request); return Invalid(request, OidcConstants.AuthorizeErrors.UnauthorizedClient, "Invalid redirect_uri"); } request.RedirectUri = redirectUri; return Valid(request); } private AuthorizeRequestValidationResult ValidateCoreParameters(ValidatedAuthorizeRequest request) { ////////////////////////////////////////////////////////// // check state ////////////////////////////////////////////////////////// var state = request.Raw.Get(OidcConstants.AuthorizeRequest.State); if (state.IsPresent()) { request.State = state; } ////////////////////////////////////////////////////////// // response_type must be present and supported ////////////////////////////////////////////////////////// var responseType = request.Raw.Get(OidcConstants.AuthorizeRequest.ResponseType); if (responseType.IsMissing()) { LogError("Missing response_type", request); return Invalid(request, OidcConstants.AuthorizeErrors.UnsupportedResponseType, "Missing response_type"); } // The responseType may come in in an unconventional order. // Use an IEqualityComparer that doesn't care about the order of multiple values. // Per https://tools.ietf.org/html/rfc6749#section-3.1.1 - // 'Extension response types MAY contain a space-delimited (%x20) list of // values, where the order of values does not matter (e.g., response // type "a b" is the same as "b a").' // http://openid.net/specs/oauth-v2-multiple-response-types-1_0-03.html#terminology - // 'If a response type contains one of more space characters (%20), it is compared // as a space-delimited list of values in which the order of values does not matter.' if (!Constants.SupportedResponseTypes.Contains(responseType, _responseTypeEqualityComparer)) { LogError("Response type not supported", responseType, request); return Invalid(request, OidcConstants.AuthorizeErrors.UnsupportedResponseType, "Response type not supported"); } // Even though the responseType may have come in in an unconventional order, // we still need the request's ResponseType property to be set to the // conventional, supported response type. request.ResponseType = Constants.SupportedResponseTypes.First( supportedResponseType => _responseTypeEqualityComparer.Equals(supportedResponseType, responseType)); ////////////////////////////////////////////////////////// // match response_type to grant type ////////////////////////////////////////////////////////// request.GrantType = Constants.ResponseTypeToGrantTypeMapping[request.ResponseType]; // set default response mode for flow; this is needed for any client error processing below request.ResponseMode = Constants.AllowedResponseModesForGrantType[request.GrantType].First(); ////////////////////////////////////////////////////////// // check if flow is allowed at authorize endpoint ////////////////////////////////////////////////////////// if (!Constants.AllowedGrantTypesForAuthorizeEndpoint.Contains(request.GrantType)) { LogError("Invalid grant type", request.GrantType, request); return Invalid(request, description: "Invalid response_type"); } ////////////////////////////////////////////////////////// // check if PKCE is required and validate parameters ////////////////////////////////////////////////////////// if (request.GrantType == GrantType.AuthorizationCode || request.GrantType == GrantType.Hybrid) { _logger.LogDebug("Checking for PKCE parameters"); ///////////////////////////////////////////////////////////////////////////// // validate code_challenge and code_challenge_method ///////////////////////////////////////////////////////////////////////////// var proofKeyResult = ValidatePkceParameters(request); if (proofKeyResult.IsError) { return proofKeyResult; } } ////////////////////////////////////////////////////////// // check response_mode parameter and set response_mode ////////////////////////////////////////////////////////// // check if response_mode parameter is present and valid var responseMode = request.Raw.Get(OidcConstants.AuthorizeRequest.ResponseMode); if (responseMode.IsPresent()) { if (Constants.SupportedResponseModes.Contains(responseMode)) { if (Constants.AllowedResponseModesForGrantType[request.GrantType].Contains(responseMode)) { request.ResponseMode = responseMode; } else { LogError("Invalid response_mode for flow", responseMode, request); return Invalid(request, OidcConstants.AuthorizeErrors.UnsupportedResponseType, description: "Invalid response_mode"); } } else { LogError("Unsupported response_mode", responseMode, request); return Invalid(request, OidcConstants.AuthorizeErrors.UnsupportedResponseType, description: "Invalid response_mode"); } } ////////////////////////////////////////////////////////// // check if grant type is allowed for client ////////////////////////////////////////////////////////// if (!request.Client.AllowedGrantTypes.Contains(request.GrantType)) { LogError("Invalid grant type for client", request.GrantType, request); return Invalid(request, OidcConstants.AuthorizeErrors.UnauthorizedClient, "Invalid grant type for client"); } ////////////////////////////////////////////////////////// // check if response type contains an access token, // and if client is allowed to request access token via browser ////////////////////////////////////////////////////////// var responseTypes = responseType.FromSpaceSeparatedString(); if (responseTypes.Contains(OidcConstants.ResponseTypes.Token)) { if (!request.Client.AllowAccessTokensViaBrowser) { LogError("Client requested access token - but client is not configured to receive access tokens via browser", request); return Invalid(request, description: "Client not configured to receive access tokens via browser"); } } return Valid(request); } private AuthorizeRequestValidationResult ValidatePkceParameters(ValidatedAuthorizeRequest request) { var fail = Invalid(request); var codeChallenge = request.Raw.Get(OidcConstants.AuthorizeRequest.CodeChallenge); if (codeChallenge.IsMissing()) { if (request.Client.RequirePkce) { LogError("code_challenge is missing", request); fail.ErrorDescription = "code challenge required"; } else { _logger.LogDebug("No PKCE used."); return Valid(request); } return fail; } if (codeChallenge.Length < _options.InputLengthRestrictions.CodeChallengeMinLength || codeChallenge.Length > _options.InputLengthRestrictions.CodeChallengeMaxLength) { LogError("code_challenge is either too short or too long", request); fail.ErrorDescription = "Invalid code_challenge"; return fail; } request.CodeChallenge = codeChallenge; var codeChallengeMethod = request.Raw.Get(OidcConstants.AuthorizeRequest.CodeChallengeMethod); if (codeChallengeMethod.IsMissing()) { _logger.LogDebug("Missing code_challenge_method, defaulting to plain"); codeChallengeMethod = OidcConstants.CodeChallengeMethods.Plain; } if (!Constants.SupportedCodeChallengeMethods.Contains(codeChallengeMethod)) { LogError("Unsupported code_challenge_method", codeChallengeMethod, request); fail.ErrorDescription = "Transform algorithm not supported"; return fail; } // check if plain method is allowed if (codeChallengeMethod == OidcConstants.CodeChallengeMethods.Plain) { if (!request.Client.AllowPlainTextPkce) { LogError("code_challenge_method of plain is not allowed", request); fail.ErrorDescription = "Transform algorithm not supported"; return fail; } } request.CodeChallengeMethod = codeChallengeMethod; return Valid(request); } private async Task<AuthorizeRequestValidationResult> ValidateScopeAsync(ValidatedAuthorizeRequest request) { ////////////////////////////////////////////////////////// // scope must be present ////////////////////////////////////////////////////////// var scope = request.Raw.Get(OidcConstants.AuthorizeRequest.Scope); if (scope.IsMissing()) { LogError("scope is missing", request); return Invalid(request, description: "Invalid scope"); } if (scope.Length > _options.InputLengthRestrictions.Scope) { LogError("scopes too long.", request); return Invalid(request, description: "Invalid scope"); } request.RequestedScopes = scope.FromSpaceSeparatedString().Distinct().ToList(); if (request.RequestedScopes.Contains(IdentityServerConstants.StandardScopes.OpenId)) { request.IsOpenIdRequest = true; } ////////////////////////////////////////////////////////// // check scope vs response_type plausability ////////////////////////////////////////////////////////// var requirement = Constants.ResponseTypeToScopeRequirement[request.ResponseType]; if (requirement == Constants.ScopeRequirement.Identity || requirement == Constants.ScopeRequirement.IdentityOnly) { if (request.IsOpenIdRequest == false) { LogError("response_type requires the openid scope", request); return Invalid(request, description: "Missing openid scope"); } } ////////////////////////////////////////////////////////// // check if scopes are valid/supported and check for resource scopes ////////////////////////////////////////////////////////// if (await _scopeValidator.AreScopesValidAsync(request.RequestedScopes) == false) { return Invalid(request, OidcConstants.AuthorizeErrors.InvalidScope, "Invalid scope"); } if (_scopeValidator.ContainsOpenIdScopes && !request.IsOpenIdRequest) { LogError("Identity related scope requests, but no openid scope", request); return Invalid(request, OidcConstants.AuthorizeErrors.InvalidScope, "Identity scopes requested, but openid scope is missing"); } if (_scopeValidator.ContainsApiResourceScopes) { request.IsApiResourceRequest = true; } ////////////////////////////////////////////////////////// // check scopes and scope restrictions ////////////////////////////////////////////////////////// if (await _scopeValidator.AreScopesAllowedAsync(request.Client, request.RequestedScopes) == false) { return Invalid(request, OidcConstants.AuthorizeErrors.UnauthorizedClient, description: "Invalid scope for client"); } request.ValidatedScopes = _scopeValidator; ////////////////////////////////////////////////////////// // check id vs resource scopes and response types plausability ////////////////////////////////////////////////////////// if (!_scopeValidator.IsResponseTypeValid(request.ResponseType)) { return Invalid(request, OidcConstants.AuthorizeErrors.InvalidScope, "Invalid scope for response type"); } return Valid(request); } private async Task<AuthorizeRequestValidationResult> ValidateOptionalParametersAsync(ValidatedAuthorizeRequest request) { ////////////////////////////////////////////////////////// // check nonce ////////////////////////////////////////////////////////// var nonce = request.Raw.Get(OidcConstants.AuthorizeRequest.Nonce); if (nonce.IsPresent()) { if (nonce.Length > _options.InputLengthRestrictions.Nonce) { LogError("Nonce too long", request); return Invalid(request, description: "Invalid nonce"); } request.Nonce = nonce; } else { if (request.GrantType == GrantType.Implicit || request.GrantType == GrantType.Hybrid) { // only openid requests require nonce if (request.IsOpenIdRequest) { LogError("Nonce required for implicit and hybrid flow with openid scope", request); return Invalid(request, description: "Invalid nonce"); } } } ////////////////////////////////////////////////////////// // check prompt ////////////////////////////////////////////////////////// var prompt = request.Raw.Get(OidcConstants.AuthorizeRequest.Prompt); if (prompt.IsPresent()) { if (Constants.SupportedPromptModes.Contains(prompt)) { request.PromptMode = prompt; } else { _logger.LogDebug("Unsupported prompt mode - ignored: " + prompt); } } ////////////////////////////////////////////////////////// // check ui locales ////////////////////////////////////////////////////////// var uilocales = request.Raw.Get(OidcConstants.AuthorizeRequest.UiLocales); if (uilocales.IsPresent()) { if (uilocales.Length > _options.InputLengthRestrictions.UiLocale) { LogError("UI locale too long", request); return Invalid(request, description: "Invalid ui_locales"); } request.UiLocales = uilocales; } ////////////////////////////////////////////////////////// // check display ////////////////////////////////////////////////////////// var display = request.Raw.Get(OidcConstants.AuthorizeRequest.Display); if (display.IsPresent()) { if (Constants.SupportedDisplayModes.Contains(display)) { request.DisplayMode = display; } _logger.LogDebug("Unsupported display mode - ignored: " + display); } ////////////////////////////////////////////////////////// // check max_age ////////////////////////////////////////////////////////// var maxAge = request.Raw.Get(OidcConstants.AuthorizeRequest.MaxAge); if (maxAge.IsPresent()) { if (int.TryParse(maxAge, out var seconds)) { if (seconds >= 0) { request.MaxAge = seconds; } else { LogError("Invalid max_age.", request); return Invalid(request, description: "Invalid max_age"); } } else { LogError("Invalid max_age.", request); return Invalid(request, description: "Invalid max_age"); } } ////////////////////////////////////////////////////////// // check login_hint ////////////////////////////////////////////////////////// var loginHint = request.Raw.Get(OidcConstants.AuthorizeRequest.LoginHint); if (loginHint.IsPresent()) { if (loginHint.Length > _options.InputLengthRestrictions.LoginHint) { LogError("Login hint too long", request); return Invalid(request, description:"Invalid login_hint"); } request.LoginHint = loginHint; } ////////////////////////////////////////////////////////// // check acr_values ////////////////////////////////////////////////////////// var acrValues = request.Raw.Get(OidcConstants.AuthorizeRequest.AcrValues); if (acrValues.IsPresent()) { if (acrValues.Length > _options.InputLengthRestrictions.AcrValues) { LogError("Acr values too long", request); return Invalid(request, description: "Invalid acr_values"); } request.AuthenticationContextReferenceClasses = acrValues.FromSpaceSeparatedString().Distinct().ToList(); } ////////////////////////////////////////////////////////// // check custom acr_values: idp ////////////////////////////////////////////////////////// var idp = request.GetIdP(); if (idp.IsPresent()) { // if idp is present but client does not allow it, strip it from the request message if (request.Client.IdentityProviderRestrictions != null && request.Client.IdentityProviderRestrictions.Any()) { if (!request.Client.IdentityProviderRestrictions.Contains(idp)) { _logger.LogWarning("idp requested ({idp}) is not in client restriction list.", idp); request.RemoveIdP(); } } } ////////////////////////////////////////////////////////// // check session cookie ////////////////////////////////////////////////////////// if (_options.Endpoints.EnableCheckSessionEndpoint) { if (request.Subject.IsAuthenticated()) { var sessionId = await _userSession.GetSessionIdAsync(); if (sessionId.IsPresent()) { request.SessionId = sessionId; } else { LogError("Check session endpoint enabled, but SessionId is missing", request); } } else { request.SessionId = ""; // empty string for anonymous users } } return Valid(request); } private AuthorizeRequestValidationResult Invalid(ValidatedAuthorizeRequest request, string error = OidcConstants.AuthorizeErrors.InvalidRequest, string description = null) { return new AuthorizeRequestValidationResult(request, error, description); } private AuthorizeRequestValidationResult Valid(ValidatedAuthorizeRequest request) { return new AuthorizeRequestValidationResult(request); } private void LogError(string message, ValidatedAuthorizeRequest request) { var requestDetails = new AuthorizeRequestValidationLog(request); _logger.LogError(message + "\n{@requestDetails}", requestDetails); } private void LogError(string message, string detail, ValidatedAuthorizeRequest request) { var requestDetails = new AuthorizeRequestValidationLog(request); _logger.LogError(message + ": {detail}\n{@requestDetails}", detail, requestDetails); } } }
44.780788
179
0.506628
[ "Apache-2.0" ]
Akinnagbe/IdentityServer4
src/IdentityServer4/src/Validation/Default/AuthorizeRequestValidator.cs
36,362
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.Network.V20200601 { public static class GetLoadBalancer { public static Task<GetLoadBalancerResult> InvokeAsync(GetLoadBalancerArgs args, InvokeOptions? options = null) => Pulumi.Deployment.Instance.InvokeAsync<GetLoadBalancerResult>("azure-nextgen:network/v20200601:getLoadBalancer", args ?? new GetLoadBalancerArgs(), options.WithVersion()); } public sealed class GetLoadBalancerArgs : Pulumi.InvokeArgs { /// <summary> /// Expands referenced resources. /// </summary> [Input("expand")] public string? Expand { get; set; } /// <summary> /// The name of the load balancer. /// </summary> [Input("loadBalancerName", required: true)] public string LoadBalancerName { get; set; } = null!; /// <summary> /// The name of the resource group. /// </summary> [Input("resourceGroupName", required: true)] public string ResourceGroupName { get; set; } = null!; public GetLoadBalancerArgs() { } } [OutputType] public sealed class GetLoadBalancerResult { /// <summary> /// Collection of backend address pools used by a load balancer. /// </summary> public readonly ImmutableArray<Outputs.BackendAddressPoolResponse> BackendAddressPools; /// <summary> /// A unique read-only string that changes whenever the resource is updated. /// </summary> public readonly string Etag; /// <summary> /// Object representing the frontend IPs to be used for the load balancer. /// </summary> public readonly ImmutableArray<Outputs.FrontendIPConfigurationResponse> FrontendIPConfigurations; /// <summary> /// Defines an external port range for inbound NAT to a single backend port on NICs associated with a load balancer. Inbound NAT rules are created automatically for each NIC associated with the Load Balancer using an external port from this range. Defining an Inbound NAT pool on your Load Balancer is mutually exclusive with defining inbound Nat rules. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an inbound NAT pool. They have to reference individual inbound NAT rules. /// </summary> public readonly ImmutableArray<Outputs.InboundNatPoolResponse> InboundNatPools; /// <summary> /// Collection of inbound NAT Rules used by a load balancer. Defining inbound NAT rules on your load balancer is mutually exclusive with defining an inbound NAT pool. Inbound NAT pools are referenced from virtual machine scale sets. NICs that are associated with individual virtual machines cannot reference an Inbound NAT pool. They have to reference individual inbound NAT rules. /// </summary> public readonly ImmutableArray<Outputs.InboundNatRuleResponse> InboundNatRules; /// <summary> /// Object collection representing the load balancing rules Gets the provisioning. /// </summary> public readonly ImmutableArray<Outputs.LoadBalancingRuleResponse> LoadBalancingRules; /// <summary> /// Resource location. /// </summary> public readonly string? Location; /// <summary> /// Resource name. /// </summary> public readonly string Name; /// <summary> /// The outbound rules. /// </summary> public readonly ImmutableArray<Outputs.OutboundRuleResponse> OutboundRules; /// <summary> /// Collection of probe objects used in the load balancer. /// </summary> public readonly ImmutableArray<Outputs.ProbeResponse> Probes; /// <summary> /// The provisioning state of the load balancer resource. /// </summary> public readonly string ProvisioningState; /// <summary> /// The resource GUID property of the load balancer resource. /// </summary> public readonly string ResourceGuid; /// <summary> /// The load balancer SKU. /// </summary> public readonly Outputs.LoadBalancerSkuResponse? Sku; /// <summary> /// Resource tags. /// </summary> public readonly ImmutableDictionary<string, string>? Tags; /// <summary> /// Resource type. /// </summary> public readonly string Type; [OutputConstructor] private GetLoadBalancerResult( ImmutableArray<Outputs.BackendAddressPoolResponse> backendAddressPools, string etag, ImmutableArray<Outputs.FrontendIPConfigurationResponse> frontendIPConfigurations, ImmutableArray<Outputs.InboundNatPoolResponse> inboundNatPools, ImmutableArray<Outputs.InboundNatRuleResponse> inboundNatRules, ImmutableArray<Outputs.LoadBalancingRuleResponse> loadBalancingRules, string? location, string name, ImmutableArray<Outputs.OutboundRuleResponse> outboundRules, ImmutableArray<Outputs.ProbeResponse> probes, string provisioningState, string resourceGuid, Outputs.LoadBalancerSkuResponse? sku, ImmutableDictionary<string, string>? tags, string type) { BackendAddressPools = backendAddressPools; Etag = etag; FrontendIPConfigurations = frontendIPConfigurations; InboundNatPools = inboundNatPools; InboundNatRules = inboundNatRules; LoadBalancingRules = loadBalancingRules; Location = location; Name = name; OutboundRules = outboundRules; Probes = probes; ProvisioningState = provisioningState; ResourceGuid = resourceGuid; Sku = sku; Tags = tags; Type = type; } } }
39.993711
576
0.650574
[ "Apache-2.0" ]
test-wiz-sec/pulumi-azure-nextgen
sdk/dotnet/Network/V20200601/GetLoadBalancer.cs
6,359
C#
#region license // Copyright (c) 2005 - 2007 Ayende Rahien (ayende@ayende.com) // All rights reserved. // // Redistribution and use in source and binary forms, with or without modification, // are permitted provided that the following conditions are met: // // * Redistributions of source code must retain the above copyright notice, // this list of conditions and the following disclaimer. // * Redistributions in binary form must reproduce the above copyright notice, // this list of conditions and the following disclaimer in the documentation // and/or other materials provided with the distribution. // * Neither the name of Ayende Rahien nor the names of its // contributors may be used to endorse or promote products derived from this // software without specific prior written permission. // // THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND // ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED // WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE // DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE // FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL // DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR // SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER // CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, // OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF // THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. #endregion namespace Rhino.Commons.Test.Components { using System.Collections.Generic; public class Fubar { object foo; private static readonly Fubar instance = new Fubar("Instance"); public object Foo { get { return foo; } } public Fubar(object foo) { this.foo = foo; } public static Fubar Instance { get { return instance; } } } public class MyComponent { private readonly IDictionary<string, string> someMapping; public MyComponent(IDictionary<string, string> someMapping) { this.someMapping = someMapping; } public IDictionary<string, string> SomeMapping { get { return someMapping; } } } }
33.557143
83
0.719455
[ "BSD-3-Clause" ]
cneuwirt/rhino-commons
Rhino.Commons.Test/Binsor/Fubar.cs
2,351
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Collections; using System.ComponentModel; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using PropertyChanged; namespace AutoLotDAL2.Models { [AddINotifyPropertyChangedInterface] public abstract class EntityBase : IDataErrorInfo,INotifyDataErrorInfo { [Timestamp] public byte[] TimeStamp { get; set; } [NotMapped] public bool IsChanged { get; set; } private readonly Dictionary<string, List<string>> _errors = new Dictionary<string, List<string>>(); public bool HasErrors => _errors.Count != 0; public event EventHandler<DataErrorsChangedEventArgs> ErrorsChanged; public IEnumerable GetErrors(string propertyName) { if (string.IsNullOrEmpty(propertyName)) { return _errors.Values; } return _errors.ContainsKey(propertyName) ? _errors[propertyName] : null; } public string Error { get; } public abstract string this[string columnName] { get; } protected void ClearErrors(string propertyName = "") { _errors.Remove(propertyName); OnErrorsChanged(propertyName); } protected void AddError(string propertyName, string error) { AddErrors(propertyName, new List<string> { error }); } protected void AddErrors(string propertyName, IList<string> errors) { var changed = false; if (!_errors.ContainsKey(propertyName)) { _errors.Add(propertyName, new List<string>()); changed = true; } errors.ToList().ForEach(x => { if (_errors[propertyName].Contains(x)) return; _errors[propertyName].Add(x); changed = true; }); if (changed) { OnErrorsChanged(propertyName); } } protected void OnErrorsChanged(string propertyName) { ErrorsChanged?.Invoke(this, new DataErrorsChangedEventArgs(propertyName)); } protected string[] GetErrorsFromAnnotations<T>(string propertyName, T value) { var results = new List<ValidationResult>(); var vc = new ValidationContext(this, null, null) { MemberName = propertyName }; var isValid = Validator.TryValidateProperty(value, vc, results); return (isValid) ? null : Array.ConvertAll(results.ToArray(), o => o.ErrorMessage); } } }
33.802469
107
0.608108
[ "MIT" ]
NuCode1497/WPFTutorials
MVVM/AutoLotDAL2/Models/EntityBase.cs
2,740
C#
namespace OpenSsl.Crypto.Utility { /// <summary> /// ras签名算法,其中MD2、MD5、SHA1密钥长度1024,其他密钥长度2048 /// </summary> public enum RsaSignerAlgorithm { MD2withRSA = 1, MD5withRSA = 2, SHA1withRSA = 3, //以下密钥长度均为2048 SHA224withRSA = 4, SHA256withRSA = 5, SHA384withRSA = 6, SHA512withRSA = 7, RIPEMD128withRSA = 8, RIPEMD160withRSA = 9 } }
21.75
49
0.56092
[ "MIT" ]
swpudp/OpenSsl.Crypto.Utility
src/OpenSsl.Crypto.Utility/RsaSignerAlgorithm.cs
493
C#
using System.Collections.Generic; using UnityEngine; namespace TextEffect { public class TextBlendScale : TextEffectBase { [SerializeField, Range(0f, 1f)] private float _blend; [SerializeField] private float _interval; [SerializeField] private Vector2 _fromScale = Vector2.zero; [SerializeField] private Vector2 _toScale = Vector2.zero; [SerializeField] private AlignmentType _alignment = AlignmentType.MiddleCenter; [SerializeField] private AnimationCurve _animationCurve; private float _cacheBlend; private float _cacheInterval; private Vector2 _cacheToScale; private Vector2 _cacheFromScale; /// <summary> /// ブレンド割合 /// </summary> public float Blend { get { return _blend; } set { _blend = value; SetVerticesDirty(); } } /// <summary> /// インターバル /// </summary> public float Interval { get { return _interval; } set { _interval = value; SetVerticesDirty(); } } /// <summary> /// 開始 /// </summary> public Vector2 FromScale { get { return _fromScale; } set { _fromScale = value; SetVerticesDirty(); } } /// <summary> /// 終了 /// </summary> public Vector2 ToScale { get { return _toScale; } set { _toScale = value; SetVerticesDirty(); } } #if UNITY_EDITOR protected override void OnValidate() { base.OnValidate(); FromScale = _fromScale; ToScale = _toScale; Blend = _blend; Interval = _interval; } #endif protected override void Modify(ref List<UIVertex> stream) { var count = 0; var streamCount = stream.Count; var startPoint = (streamCount / 6f + Interval - 1) * EffectBlend - Interval; for (int i = 0; i < streamCount; i += 6) { var scale = count < startPoint ? ToScale : count > startPoint + Interval ? FromScale : FromScale + (ToScale - FromScale) * (startPoint + Interval - count) / Interval; var anchor = GetAnchor(stream.ToArray(), i, _alignment); for (var r = 0; r < 6; r++) { var element = stream[i + r]; var pos = element.position - (Vector3) anchor; Vector2 newPos = new Vector2(pos.x * scale.x, pos.y * scale.y); element.position = newPos + anchor; stream[i + r] = element; } count++; } } private float EffectBlend { get { return _animationCurve == null ? _blend : _animationCurve.Evaluate(_blend); } } private void Update() { if (_cacheToScale != ToScale) { _cacheToScale = ToScale; ToScale = _cacheToScale; } if (_cacheFromScale != FromScale) { _cacheFromScale = FromScale; FromScale = _cacheFromScale; } if (_cacheBlend != Blend) { _cacheBlend = Blend; Blend = _cacheBlend; } if (_cacheInterval != Interval) { _cacheInterval = Interval; Interval = _cacheInterval; } } } }
27.666667
105
0.46142
[ "MIT" ]
ToshikiImagawa/TextEffect
Assets/TextEffect/TextBlendScale.cs
3,935
C#
using Newtonsoft.Json; using Miki.Rest; using System.Linq; using System.Threading.Tasks; namespace Miki.API.UrbanDictionary { internal class UrbanDictionaryApi { private string key = ""; public UrbanDictionaryApi(string key) { this.key = key; } public async Task<UrbanDictionaryEntry> GetEntryAsync(string term, int index = 0) { RestClient client = new RestClient("https://mashape-community-urban-dictionary.p.mashape.com/define?term=" + term); client.AddHeader("X-Mashape-Key", key); client.AddHeader("Accept", "application/json"); RestResponse<UrbanDictionaryResponse> post = await client.GetAsync<UrbanDictionaryResponse>(""); if (post.Data.Entries.Count == 0) { return null; } return post.Data.Entries.FirstOrDefault(); } } }
26.794118
127
0.6191
[ "Apache-2.0" ]
SnipeFrost/Miki
Miki/API/Urban Dictionary/UrbanDictionaryApi.cs
913
C#
using Core.DataAccess.EntityFramework; using DataAccess.Abstract; using Entities.Concrete; namespace DataAccess.Concrete.EntityFramework { public class EfColorDal : EfEntityRepositoryBase<Color, ReCapProjectContext>, IColorDal { } }
22.454545
91
0.793522
[ "Apache-2.0" ]
ismailkaygisiz/ReCapProject
DataAccess/Concrete/EntityFramework/EfColorDal.cs
249
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Collections.Generic; using System.Reflection; using Microsoft.AspNetCore.Mvc.ActionConstraints; using Microsoft.AspNetCore.Mvc.Filters; using Microsoft.AspNetCore.Mvc.Infrastructure; using Microsoft.AspNetCore.Mvc.Internal; using Microsoft.AspNetCore.Mvc.Routing; using Xunit; namespace Microsoft.AspNetCore.Mvc.ApplicationModels { public class ControllerModelTest { [Fact] public void CopyConstructor_DoesDeepCopyOfOtherModels() { // Arrange var controller = new ControllerModel(typeof(TestController).GetTypeInfo(), new List<object>()); var action = new ActionModel(typeof(TestController).GetMethod("Edit"), new List<object>()); controller.Actions.Add(action); action.Controller = controller; var route = new AttributeRouteModel(new HttpGetAttribute("api/Products")); controller.Selectors.Add(new SelectorModel() { AttributeRouteModel = route }); var apiExplorer = controller.ApiExplorer; controller.ApiExplorer.GroupName = "group"; controller.ApiExplorer.IsVisible = true; // Act var controller2 = new ControllerModel(controller); // Assert Assert.NotSame(action, controller2.Actions[0]); Assert.NotNull(controller2.Selectors); Assert.Single(controller2.Selectors); Assert.NotSame(route, controller2.Selectors[0].AttributeRouteModel); Assert.NotSame(apiExplorer, controller2.ApiExplorer); Assert.NotSame(controller.Selectors[0].ActionConstraints, controller2.Selectors[0].ActionConstraints); Assert.NotSame(controller.Actions, controller2.Actions); Assert.NotSame(controller.Attributes, controller2.Attributes); Assert.NotSame(controller.Filters, controller2.Filters); Assert.NotSame(controller.RouteConstraints, controller2.RouteConstraints); } [Fact] public void CopyConstructor_CopiesAllProperties() { // Arrange var controller = new ControllerModel( typeof(TestController).GetTypeInfo(), new List<object>() { new HttpGetAttribute(), new MyFilterAttribute(), }); var selectorModel = new SelectorModel(); selectorModel.ActionConstraints.Add(new HttpMethodActionConstraint(new string[] { "GET" })); controller.Selectors.Add(selectorModel); controller.Application = new ApplicationModel(); controller.ControllerName = "cool"; controller.Filters.Add(new MyFilterAttribute()); controller.RouteConstraints.Add(new MyRouteConstraintAttribute()); controller.Properties.Add(new KeyValuePair<object, object>("test key", "test value")); controller.ControllerProperties.Add( new PropertyModel(typeof(TestController).GetProperty("TestProperty"), new List<object>())); // Act var controller2 = new ControllerModel(controller); // Assert foreach (var property in typeof(ControllerModel).GetProperties()) { if (property.Name.Equals("Actions") || property.Name.Equals("Selectors") || property.Name.Equals("ApiExplorer") || property.Name.Equals("ControllerProperties")) { // This test excludes other ApplicationModel objects on purpose because we deep copy them. continue; } var value1 = property.GetValue(controller); var value2 = property.GetValue(controller2); if (typeof(IEnumerable<object>).IsAssignableFrom(property.PropertyType)) { Assert.Equal<object>((IEnumerable<object>)value1, (IEnumerable<object>)value2); // Ensure non-default value Assert.NotEmpty((IEnumerable<object>)value1); } else if (typeof(IDictionary<object, object>).IsAssignableFrom(property.PropertyType)) { Assert.Equal(value1, value2); // Ensure non-default value Assert.NotEmpty((IDictionary<object, object>)value1); } else if (property.PropertyType.GetTypeInfo().IsValueType || Nullable.GetUnderlyingType(property.PropertyType) != null) { Assert.Equal(value1, value2); // Ensure non-default value Assert.NotEqual(value1, Activator.CreateInstance(property.PropertyType)); } else { Assert.Same(value1, value2); // Ensure non-default value Assert.NotNull(value1); } } } private class TestController { public string TestProperty { get; set; } public void Edit() { } } private class MyFilterAttribute : Attribute, IFilterMetadata { } private class MyRouteConstraintAttribute : Attribute, IRouteConstraintProvider { public bool BlockNonAttributedActions { get { return true; } } public string RouteKey { get; set; } public RouteKeyHandling RouteKeyHandling { get { return RouteKeyHandling.RequireKey; } } public string RouteValue { get; set; } } } }
39.701987
114
0.586656
[ "Apache-2.0" ]
Mani4007/ASPNET
test/Microsoft.AspNetCore.Mvc.Core.Test/ApplicationModel/ControllerModelTest.cs
5,995
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Text; namespace Cosmos.Assembler.x86 { [Cosmos.Assembler.OpCode("ret")] public class Return: Instruction { public Return() { DestinationValue = 0; } public uint DestinationValue { get; set; } public override void WriteText(Assembler aAssembler, TextWriter aOutput) { if (DestinationValue == 0) { aOutput.WriteLine("Ret"); } else { aOutput.WriteLine("Ret 0x" + DestinationValue.ToString("X")); } } } }
22.545455
81
0.502688
[ "BSD-3-Clause" ]
ERamaM/Cosmos
source/Cosmos.Assembler/x86/Return.cs
746
C#
using System; using System.Linq; using System.Reflection; using System.Runtime.Serialization; using UnityEngine; using Benchmark.NestedModel; using UnityEngine.Profiling; public class Factory : MonoBehaviour { private const int Iterations = 10000; private B _b; private C _c; private D _d; private E _e; private ConstructorInfo _aConstructorInfo; private void Start() { _e = new E(); _d = new D(_e); _c = new C(_d); _b = new B(_c); _aConstructorInfo = typeof(A).GetConstructors().OrderByDescending(c => c.GetParameters().Length).First(); } private void Update() { BenchmarkInstantiateNew(); BenchmarkInstantiateActivator(); BenchmarkInstantiateUninitializedObject(); } private void BenchmarkInstantiateNew() { Profiler.BeginSample(nameof(BenchmarkInstantiateNew)); for (int i = 0; i < Iterations; i++) { var instance = new A(_b); } Profiler.EndSample(); } private void BenchmarkInstantiateActivator() { Profiler.BeginSample(nameof(BenchmarkInstantiateActivator)); for (int i = 0; i < Iterations; i++) { var instance = Activator.CreateInstance(typeof(A), _b); } Profiler.EndSample(); } private void BenchmarkInstantiateUninitializedObject() { Profiler.BeginSample(nameof(BenchmarkInstantiateUninitializedObject)); for (int i = 0; i < Iterations; i++) { var instance = FormatterServices.GetUninitializedObject(typeof(A)); _aConstructorInfo.Invoke(instance, new object[] {_b}); } Profiler.EndSample(); } }
21.637681
107
0.723376
[ "MIT" ]
gustavopsantos/Reflex
Reflex.Benchmark/Assets/Benchmark/Factory.cs
1,495
C#
using System.Collections; using System.Collections.Generic; using UnityEngine; using UnityEngine.UI; public class SkinSelector : MonoBehaviour { private INIParser m_parser; private int m_currentIndex = 0; public List<SkinData> skins; private SkinData currentSkin; public SkinData CurrentSkin { get => currentSkin; set => currentSkin = value; } public Image skinPreviewImage; public Text skinPreviewName; public Image skinPreviewSelectButtonCheck; private void Awake() { m_parser = new INIParser(); m_parser.Open(Application.persistentDataPath + "/settings.ini"); m_currentIndex = m_parser.ReadValue("Player", "SkinSelected", 0); m_parser.Close(); if (m_currentIndex < 0 || m_currentIndex >= skins.Count) { m_currentIndex = 0; } CurrentSkin = skins[m_currentIndex]; UpdateSkinPreview(m_currentIndex); } public void PreviousSkin() { int newIndex = m_currentIndex - 1; UpdateSkinPreview(newIndex); } public void NextSkin() { int newIndex = m_currentIndex + 1; UpdateSkinPreview(newIndex); } public void SelectCurrentSkin() { CurrentSkin = skins[m_currentIndex]; skinPreviewSelectButtonCheck.enabled = true; m_parser.Open(Application.persistentDataPath + "/settings.ini"); m_parser.WriteValue("Player", "SkinSelected", m_currentIndex); m_parser.Close(); } private void UpdateSkinPreview(int index) { if (index < 0) { index = skins.Count - 1; } else if(index >= skins.Count) { index = 0; } m_currentIndex = index; skinPreviewImage.sprite = skins[m_currentIndex].Preview; skinPreviewName.text = skins[m_currentIndex].SkinName; if(CurrentSkin == skins[index]) { skinPreviewSelectButtonCheck.enabled = true; } else { skinPreviewSelectButtonCheck.enabled = false; } } }
25.243902
83
0.625604
[ "MIT" ]
MonsieurTweek/unity-proto-joey
Assets/Sources/Scripts/Store/SkinSelector.cs
2,072
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. using System.Web.Http.OData.TestCommon.Models; namespace System.Web.Http.OData { public static class TypeInitializer { public static object GetInstance(SupportedTypes type, int index = 0, int maxReferenceDepth = 7) { if (index > DataSource.MaxIndex) { throw new ArgumentException(String.Format("The max supported index is : {0}", DataSource.MaxIndex)); } return InternalGetInstance(type, index, new ReferenceDepthContext(maxReferenceDepth)); } internal static object InternalGetInstance(SupportedTypes type, int index, ReferenceDepthContext context) { if (!context.IncreamentCounter()) { return null; } if (type == SupportedTypes.Person) { return new Person(index, context); } else if (type == SupportedTypes.Employee) { return new Employee(index, context); } else if (type == SupportedTypes.Address) { return new Address(index, context); } else if (type == SupportedTypes.WorkItem) { return new WorkItem() { EmployeeID = index, IsCompleted = false, NumberOfHours = 100, ID = 25 }; } context.DecrementCounter(); throw new ArgumentException(String.Format("Cannot initialize an instance for {0} type.", type.ToString())); } } }
33.52
133
0.576372
[ "Apache-2.0" ]
Darth-Fx/AspNetMvcStack
OData/test/System.Web.Http.OData.Test/TestCommon/TypeInitializer.cs
1,678
C#
/* * Copyright(c) 2020 Samsung Electronics Co., Ltd. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ using System; using System.ComponentModel; using Tizen.NUI.BaseComponents; namespace Tizen.NUI.Accessibility { /// <summary> /// AccessibilityManager manages registration of views in an accessibility focus chain and changing the focused view within that chain. /// This class provides the functionality of registering the focus order and description of views and maintaining the focus chain. /// It provides functionality of setting the focus and moving the focus forward and backward. /// It also draws a highlight for the focused view and emits a signal when the focus is changed. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public partial class AccessibilityManager : BaseHandle { private static readonly AccessibilityManager instance = AccessibilityManager.Get(); internal AccessibilityManager(global::System.IntPtr cPtr, bool cMemoryOwn) : base(Interop.AccessibilityManager.AccessibilityManager_SWIGUpcast(cPtr), cMemoryOwn) { } internal static global::System.Runtime.InteropServices.HandleRef getCPtr(AccessibilityManager obj) { return (obj == null) ? new global::System.Runtime.InteropServices.HandleRef(null, global::System.IntPtr.Zero) : obj.swigCPtr; } /// This will not be public opened. [EditorBrowsable(EditorBrowsableState.Never)] protected override void ReleaseSwigCPtr(System.Runtime.InteropServices.HandleRef swigCPtr) { Interop.AccessibilityManager.delete_AccessibilityManager(swigCPtr); } // Callback for AccessibilityManager StatusChangedSignal private bool OnStatusChanged(IntPtr data) { if (_accessibilityManagerStatusChangedEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerStatusChangedEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionNextSignal private bool OnActionNext(IntPtr data) { if (_accessibilityManagerActionNextEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionNextEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionPreviousSignal private bool OnActionPrevious(IntPtr data) { if (_accessibilityManagerActionPreviousEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionPreviousEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionActivateSignal private bool OnActionActivate(IntPtr data) { if (_accessibilityManagerActionActivateEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionActivateEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionReadSignal private bool OnActionRead(IntPtr data) { if (_accessibilityManagerActionReadEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionReadEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionOverSignal private bool OnActionOver(IntPtr data) { if (_accessibilityManagerActionOverEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionOverEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionReadNextSignal private bool OnActionReadNext(IntPtr data) { if (_accessibilityManagerActionReadNextEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionReadNextEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionReadPreviousSignal private bool OnActionReadPrevious(IntPtr data) { if (_accessibilityManagerActionReadPreviousEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionReadPreviousEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionUpSignal private bool OnActionUp(IntPtr data) { if (_accessibilityManagerActionUpEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionUpEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionDownSignal private bool OnActionDown(IntPtr data) { if (_accessibilityManagerActionDownEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionDownEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionClearFocusSignal private bool OnActionClearFocus(IntPtr data) { if (_accessibilityManagerActionClearFocusEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionClearFocusEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionBackSignal private bool OnActionBack(IntPtr data) { if (_accessibilityManagerActionBackEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionBackEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionScrollUpSignal private bool OnActionScrollUp(IntPtr data) { if (_accessibilityManagerActionScrollUpEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionScrollUpEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionScrollDownSignal private bool OnActionScrollDown(IntPtr data) { if (_accessibilityManagerActionScrollDownEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionScrollDownEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionPageLeftSignal private bool OnActionPageLeft(IntPtr data) { if (_accessibilityManagerActionPageLeftEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionPageLeftEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionPageRightSignal private bool OnActionPageRight(IntPtr data) { if (_accessibilityManagerActionPageRightEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionPageRightEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionPageUpSignal private bool OnActionPageUp(IntPtr data) { if (_accessibilityManagerActionPageUpEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionPageUpEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionPageDownSignal private bool OnActionPageDown(IntPtr data) { if (_accessibilityManagerActionPageDownEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionPageDownEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionMoveToFirstSignal private bool OnActionMoveToFirst(IntPtr data) { if (_accessibilityManagerActionMoveToFirstEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionMoveToFirstEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionMoveToLastSignal private bool OnActionMoveToLast(IntPtr data) { if (_accessibilityManagerActionMoveToLastEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionMoveToLastEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionReadFromTopSignal private bool OnActionReadFromTop(IntPtr data) { if (_accessibilityManagerActionReadFromTopEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionReadFromTopEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionReadFromNextSignal private bool OnActionReadFromNext(IntPtr data) { if (_accessibilityManagerActionReadFromNextEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionReadFromNextEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionZoomSignal private bool OnActionZoom(IntPtr data) { if (_accessibilityManagerActionZoomEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionZoomEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionReadPauseResumeSignal private bool OnActionReadPauseResume(IntPtr data) { if (_accessibilityManagerActionReadPauseResumeEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionReadPauseResumeEventHandler(instance, null); } return false; } // Callback for AccessibilityManager ActionStartStopSignal private bool OnActionStartStop(IntPtr data) { if (_accessibilityManagerActionStartStopEventHandler != null) { //here we send all data to user event handlers return _accessibilityManagerActionStartStopEventHandler(instance, null); } return false; } // Callback for AccessibilityManager FocusChangedSignal private void OnFocusChanged(IntPtr view1, IntPtr view2) { FocusChangedEventArgs e = new FocusChangedEventArgs(); // Populate all members of "e" (FocusChangedEventArgs) with real data e.ViewCurrent = Registry.GetManagedBaseHandleFromNativePtr(view1) as View; e.ViewNext = Registry.GetManagedBaseHandleFromNativePtr(view2) as View; if (_accessibilityManagerFocusChangedEventHandler != null) { //here we send all data to user event handlers _accessibilityManagerFocusChangedEventHandler(this, e); } } // Callback for AccessibilityManager FocusedViewActivatedSignal private void OnFocusedViewActivated(IntPtr view) { FocusedViewActivatedEventArgs e = new FocusedViewActivatedEventArgs(); // Populate all members of "e" (FocusedViewActivatedEventArgs) with real data e.View = Registry.GetManagedBaseHandleFromNativePtr(view) as View; if (_accessibilityManagerFocusedViewActivatedEventHandler != null) { //here we send all data to user event handlers _accessibilityManagerFocusedViewActivatedEventHandler(this, e); } } // Callback for AccessibilityManager FocusOvershotSignal private void OnFocusOvershot(IntPtr currentFocusedView, AccessibilityManager.FocusOvershotDirection direction) { FocusOvershotEventArgs e = new FocusOvershotEventArgs(); // Populate all members of "e" (FocusOvershotEventArgs) with real data e.CurrentFocusedView = Registry.GetManagedBaseHandleFromNativePtr(currentFocusedView) as View; e.FocusOvershotDirection = direction; if (_accessibilityManagerFocusOvershotEventHandler != null) { //here we send all data to user event handlers _accessibilityManagerFocusOvershotEventHandler(this, e); } } /// <summary> /// Enumeration for accessibility that needs four information which will be read by screen-reader. /// /// Reading order : Label -> Trait -> Optional (Value and Hint) /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public enum AccessibilityAttribute { /// <summary> /// Simple text which contained in components, such as Ok or Cancel in case of a button /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] Label = 0, /// <summary> /// Description of components trait, such as Button in case of a button /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] Trait, /// <summary> /// Current value of components (Optional) /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] Value, /// <summary> /// Hint for action (Optional) /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] Hint, /// <summary> /// The number of attributes /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] AttributeNumber } /// <summary> /// Enumeration for overshoot direction. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public enum FocusOvershotDirection { /// <summary> /// Try to move previous of the first view /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] Previous = -1, /// <summary> /// Try to move next of the last view /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] Next = 1 } /// <summary> /// Creates an AccessibilityManager handle. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public AccessibilityManager() : this(Interop.AccessibilityManager.new_AccessibilityManager(), true) { if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the singleton of AccessibilityManager object. /// </summary> /// <returns> A handle to the AccessibilityManager </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public static AccessibilityManager Instance { get { return instance; } } /// <summary> /// Sets the information of the specified view's accessibility attribute. /// </summary> /// <param name="view"> The view to be set with</param> /// <param name="type"> The attribute type the text to be set with</param> /// <param name="text"> The text for the view's accessibility information</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetAccessibilityAttribute(View view, AccessibilityManager.AccessibilityAttribute type, string text) { Interop.AccessibilityManager.AccessibilityManager_SetAccessibilityAttribute(swigCPtr, View.getCPtr(view), (int)type, text); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the text of the specified view's accessibility attribute. /// </summary> /// <param name="view"> The view to be queried</param> /// <param name="type"> The attribute type to be queried</param> /// <returns> The text of the view's accessibility information </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public string GetAccessibilityAttribute(View view, AccessibilityManager.AccessibilityAttribute type) { string ret = Interop.AccessibilityManager.AccessibilityManager_GetAccessibilityAttribute(swigCPtr, View.getCPtr(view), (int)type); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets the focus order of the view. /// The focus order of each view in the focus chain is unique. /// If there is another view assigned with the same focus order already, the new view will be inserted to the focus chain with that focus order, /// and the focus order of the original view and all the views followed in the focus chain will be increased accordingly. /// If the focus order assigned to the view is 0, it means that view's focus order is undefined /// (e.g. the view has a description but with no focus order being set yet) and therefore that view is not focusable. /// </summary> /// <param name="view"> the view to be set with</param> /// <param name="order"> the focus order to be set with</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetFocusOrder(View view, uint order) { Interop.AccessibilityManager.AccessibilityManager_SetFocusOrder(swigCPtr, View.getCPtr(view), order); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the focus order of the view. /// When the focus order is 0, it means the focus order of the view is undefined. /// </summary> /// <param name="view"> the view to be set with</param> /// <returns> The focus order of the view </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public uint GetFocusOrder(View view) { uint ret = Interop.AccessibilityManager.AccessibilityManager_GetFocusOrder(swigCPtr, View.getCPtr(view)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Generates a new focus order number which can be used to assign to views /// which need to be appended to the end of the current focus order chain. /// The new number will be an increment over the very last focus order number in the focus chain. /// If the focus chain is empty then the function returns 1, /// else the number returned will be FOLast + 1 where FOLast is the focus order of the very last control in the focus chain. /// </summary> /// <returns> The focus order of the view </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public uint GenerateNewFocusOrder() { uint ret = Interop.AccessibilityManager.AccessibilityManager_GenerateNewFocusOrder(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Gets the view that has the specified focus order. /// It will return an empty handle if no view in the window has the specified focus order. /// </summary> /// <param name="order"> The focus order of the view</param> /// <returns> The view that has the specified focus order or an empty handle if no view in the stage has the specified focus order </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View GetViewByFocusOrder(uint order) { View ret = new View(Interop.AccessibilityManager.AccessibilityManager_GetActorByFocusOrder(swigCPtr, order), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Moves the focus to the specified view. /// Only one view can be focused at the same time. The view must have a defined focus order /// and must be focusable, visible and in the window. /// </summary> /// <param name="view"> the view to be set with</param> /// <returns> Whether the focus is successful or not </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool SetCurrentFocusView(View view) { bool ret = Interop.AccessibilityManager.AccessibilityManager_SetCurrentFocusActor(swigCPtr, View.getCPtr(view)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Gets the current focused view. /// </summary> /// <returns> A handle to the current focused view or an empty handle if no view is focused </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View GetCurrentFocusView() { View ret = new View(Interop.AccessibilityManager.AccessibilityManager_GetCurrentFocusActor(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Gets the focus group of current focused view. /// </summary> /// <returns> A handle to the immediate parent of the current focused view which is also a focus group, or an empty handle if no view is focused </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View GetCurrentFocusGroup() { View ret = new View(Interop.AccessibilityManager.AccessibilityManager_GetCurrentFocusGroup(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Gets the focus order of currently focused view. /// </summary> /// <returns> The focus order of the currently focused view or 0 if no view is in focus </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public uint GetCurrentFocusOrder() { uint ret = Interop.AccessibilityManager.AccessibilityManager_GetCurrentFocusOrder(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Moves the focus to the next focusable view in the focus chain (according to the focus traversal order). /// When the focus movement is wrapped around, the focus will be moved to the first focusable view when it reaches the end of the focus chain. /// </summary> /// <returns> True if the moving was successful </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool MoveFocusForward() { bool ret = Interop.AccessibilityManager.AccessibilityManager_MoveFocusForward(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Moves the focus to the previous focusable view in the focus chain (according to the focus traversal order). /// When the focus movement is wrapped around, the focus will be moved to the last focusable view /// when it reaches the beginning of the focus chain. /// </summary> /// <returns> True if the moving was successful </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool MoveFocusBackward() { bool ret = Interop.AccessibilityManager.AccessibilityManager_MoveFocusBackward(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Clears the focus from the current focused view if any, so that no view is focused in the focus chain. /// It will emit focus changed signal without current focused view. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void ClearFocus() { Interop.AccessibilityManager.AccessibilityManager_ClearFocus(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Clears every registered focusable view from focus-manager. /// </summary> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public new void Reset() { Interop.AccessibilityManager.AccessibilityManager_Reset(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Sets whether an view is a focus group that can limit the scope of focus movement to its child views in the focus chain. /// </summary> /// <param name="view"> the view to be set as a focus group</param> /// <param name="isFocusGroup"> Whether to set the view to be a focus group or not</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetFocusGroup(View view, bool isFocusGroup) { Interop.AccessibilityManager.AccessibilityManager_SetFocusGroup(swigCPtr, View.getCPtr(view), isFocusGroup); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Checks whether the view is set as a focus group or not. /// </summary> /// <param name="view"> the view to be checked</param> /// <returns> Whether the view is set as a focus group </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool IsFocusGroup(View view) { bool ret = Interop.AccessibilityManager.AccessibilityManager_IsFocusGroup(swigCPtr, View.getCPtr(view)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets whether the group mode is enabled or not. /// When the group mode is enabled, the focus movement will be limited to the child views of the current focus group including the current focus group itself. /// The current focus group is the closest ancestor of the current focused view that is set as a focus group. /// </summary> /// <param name="enabled"> Whether the group mode is enabled or not</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetGroupMode(bool enabled) { Interop.AccessibilityManager.AccessibilityManager_SetGroupMode(swigCPtr, enabled); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets whether the group mode is enabled or not. /// </summary> /// <since_tizen> 6 </since_tizen> /// <returns> Whether the group mode is enabled or not. </returns> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool GetGroupMode() { bool ret = Interop.AccessibilityManager.AccessibilityManager_GetGroupMode(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets whether focus will be moved to the beginning of the focus chain when it reaches the end or vice versa. /// When both the wrap mode and the group mode are enabled, focus will be wrapped within the current focus group. /// Focus will not be wrapped in default. /// </summary> /// <param name="wrapped"> Whether the focus movement is wrapped around or not</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetWrapMode(bool wrapped) { Interop.AccessibilityManager.AccessibilityManager_SetWrapMode(swigCPtr, wrapped); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets whether the wrap mode is enabled or not. /// </summary> /// <returns> Whether the wrap mode is enabled or not. </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public bool GetWrapMode() { bool ret = Interop.AccessibilityManager.AccessibilityManager_GetWrapMode(swigCPtr); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Sets the focus indicator view. /// This will replace the default focus indicator view in AccessibilityManager and /// will be added to the focused view as a highlight. /// </summary> /// <param name="indicator"> The indicator view to be added</param> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public void SetFocusIndicatorView(View indicator) { Interop.AccessibilityManager.AccessibilityManager_SetFocusIndicatorActor(swigCPtr, View.getCPtr(indicator)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); } /// <summary> /// Gets the focus indicator view. /// </summary> /// <returns> A handle to the focus indicator view </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View GetFocusIndicatorView() { View ret = new View(Interop.AccessibilityManager.AccessibilityManager_GetFocusIndicatorActor(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Returns the closest ancestor of the given view that is a focus group. /// </summary> /// <param name="view"> The view to be checked for its focus group</param> /// <returns> The focus group the given view belongs to or an empty handle if the given view doesn't belong to any focus group </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public View GetFocusGroup(View view) { View ret = new View(Interop.AccessibilityManager.AccessibilityManager_GetFocusGroup(swigCPtr, View.getCPtr(view)), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } /// <summary> /// Returns the current position of the read action. /// </summary> /// <returns> The current event position </returns> /// <since_tizen> 6 </since_tizen> /// This will be public opened in tizen_6.0 after ACR done. Before ACR, need to be hidden as inhouse API. [EditorBrowsable(EditorBrowsableState.Never)] public Vector2 GetReadPosition() { Vector2 ret = new Vector2(Interop.AccessibilityManager.AccessibilityManager_GetReadPosition(swigCPtr), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal static AccessibilityManager Get() { AccessibilityManager ret = new AccessibilityManager(Interop.AccessibilityManager.AccessibilityManager_Get(), true); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } // Signals - AccessibilityManagerEvent.cs internal FocusChangedSignal FocusChangedSignal() { FocusChangedSignal ret = new FocusChangedSignal(Interop.AccessibilityManager.AccessibilityManager_FocusChangedSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityFocusOvershotSignal FocusOvershotSignal() { AccessibilityFocusOvershotSignal ret = new AccessibilityFocusOvershotSignal(Interop.AccessibilityManager.AccessibilityManager_FocusOvershotSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal ViewSignal FocusedViewActivatedSignal() { ViewSignal ret = new ViewSignal(Interop.AccessibilityManager.AccessibilityManager_FocusedActorActivatedSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal StatusChangedSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_StatusChangedSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionNextSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionNextSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionPreviousSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionPreviousSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionActivateSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionActivateSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionReadSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionReadSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionOverSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionOverSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionReadNextSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionReadNextSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionReadPreviousSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionReadPreviousSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionUpSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionUpSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionDownSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionDownSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionClearFocusSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionClearFocusSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionBackSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionBackSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionScrollUpSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionScrollUpSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionScrollDownSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionScrollDownSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionPageLeftSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionPageLeftSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionPageRightSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionPageRightSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionPageUpSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionPageUpSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionPageDownSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionPageDownSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionMoveToFirstSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionMoveToFirstSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionMoveToLastSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionMoveToLastSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionReadFromTopSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionReadFromTopSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionReadFromNextSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionReadFromNextSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionZoomSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionZoomSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionReadPauseResumeSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionReadPauseResumeSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal AccessibilityActionSignal ActionStartStopSignal() { AccessibilityActionSignal ret = new AccessibilityActionSignal(Interop.AccessibilityManager.AccessibilityManager_ActionStartStopSignal(swigCPtr), false); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } internal SWIGTYPE_p_Dali__SignalT_bool_fDali__Toolkit__AccessibilityManager_R_Dali__TouchEvent_const_RF_t ActionScrollSignal() { SWIGTYPE_p_Dali__SignalT_bool_fDali__Toolkit__AccessibilityManager_R_Dali__TouchEvent_const_RF_t ret = new SWIGTYPE_p_Dali__SignalT_bool_fDali__Toolkit__AccessibilityManager_R_Dali__TouchEvent_const_RF_t(Interop.AccessibilityManager.AccessibilityManager_ActionScrollSignal(swigCPtr)); if (NDalicPINVOKE.SWIGPendingException.Pending) throw NDalicPINVOKE.SWIGPendingException.Retrieve(); return ret; } } }
49.283668
296
0.664767
[ "Apache-2.0", "MIT" ]
MoonheeChoi/TizenFX
src/Tizen.NUI/src/public/Accessibility/AccessibilityManager.cs
51,600
C#
#pragma checksum "C:\Users\suley\Desktop\NetCore_3.1\.NetCore_3.1\E_Ticaret.WebUI\Views\Account\Register.cshtml" "{ff1816ec-aa5e-4d10-87f7-6f4963833460}" "4ab2b1218382f5f9b481c0e07d1339f21a0808ea" // <auto-generated/> #pragma warning disable 1591 [assembly: global::Microsoft.AspNetCore.Razor.Hosting.RazorCompiledItemAttribute(typeof(AspNetCore.Views_Account_Register), @"mvc.1.0.view", @"/Views/Account/Register.cshtml")] namespace AspNetCore { #line hidden using System; using System.Collections.Generic; using System.Linq; using Microsoft.AspNetCore.Mvc; using Microsoft.AspNetCore.Mvc.Rendering; using Microsoft.AspNetCore.Mvc.ViewFeatures; #nullable restore #line 1 "C:\Users\suley\Desktop\NetCore_3.1\.NetCore_3.1\E_Ticaret.WebUI\Views\_ViewImports.cshtml" using E_Ticaret.WebUI; #line default #line hidden #nullable disable #nullable restore #line 2 "C:\Users\suley\Desktop\NetCore_3.1\.NetCore_3.1\E_Ticaret.WebUI\Views\_ViewImports.cshtml" using E_Ticaret.WebUI.Models; #line default #line hidden #nullable disable #nullable restore #line 1 "C:\Users\suley\Desktop\NetCore_3.1\.NetCore_3.1\E_Ticaret.WebUI\Views\Account\Register.cshtml" using System.Threading.Tasks; #line default #line hidden #nullable disable [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"4ab2b1218382f5f9b481c0e07d1339f21a0808ea", @"/Views/Account/Register.cshtml")] [global::Microsoft.AspNetCore.Razor.Hosting.RazorSourceChecksumAttribute(@"SHA1", @"b65e5ee7e44607bcae71e3dde4696d773136408d", @"/Views/_ViewImports.cshtml")] public class Views_Account_Register : global::Microsoft.AspNetCore.Mvc.Razor.RazorPage<E_Ticaret.WebUI.Models.RegisterViewModel> { private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_0 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/css/Register/fonts/material-icon/css/material-design-iconic-font.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_1 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("rel", new global::Microsoft.AspNetCore.Html.HtmlString("stylesheet"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_2 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/css/Register/css/style.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_3 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/jquery/dist/jquery.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_4 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/bootstrap/dist/js/bootstrap.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_5 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("href", new global::Microsoft.AspNetCore.Html.HtmlString("~/lib/bootstrap/dist/css/bootstrap.css"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_6 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "text", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_7 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("form-input"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_8 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("name"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_9 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("placeholder", new global::Microsoft.AspNetCore.Html.HtmlString("Ad"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_10 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "email", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_11 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("email"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_12 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("placeholder", new global::Microsoft.AspNetCore.Html.HtmlString("E-Mail"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_13 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("password"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_14 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("placeholder", new global::Microsoft.AspNetCore.Html.HtmlString("Şifre"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_15 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("type", "password", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_16 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("re_password"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_17 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("placeholder", new global::Microsoft.AspNetCore.Html.HtmlString("Şifre Tekrar"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_18 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-controller", "Account", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_19 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Register", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_20 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("method", "post", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_21 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("id", new global::Microsoft.AspNetCore.Html.HtmlString("signup-form"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_22 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("signup-form"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_23 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("asp-action", "Login", global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_24 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("class", new global::Microsoft.AspNetCore.Html.HtmlString("loginhere-link"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); private static readonly global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute __tagHelperAttribute_25 = new global::Microsoft.AspNetCore.Razor.TagHelpers.TagHelperAttribute("src", new global::Microsoft.AspNetCore.Html.HtmlString("~/css/Register/js/main.js"), global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); #line hidden #pragma warning disable 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperExecutionContext __tagHelperExecutionContext; #pragma warning restore 0649 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner __tagHelperRunner = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperRunner(); #pragma warning disable 0169 private string __tagHelperStringValueBuffer; #pragma warning restore 0169 private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __backed__tagHelperScopeManager = null; private global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager __tagHelperScopeManager { get { if (__backed__tagHelperScopeManager == null) { __backed__tagHelperScopeManager = new global::Microsoft.AspNetCore.Razor.Runtime.TagHelpers.TagHelperScopeManager(StartTagHelperWritingScope, EndTagHelperWritingScope); } return __backed__tagHelperScopeManager; } } private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper; private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper; private global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper; private global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper; #pragma warning disable 1998 public async override global::System.Threading.Tasks.Task ExecuteAsync() { WriteLiteral("\n"); #nullable restore #line 4 "C:\Users\suley\Desktop\NetCore_3.1\.NetCore_3.1\E_Ticaret.WebUI\Views\Account\Register.cshtml" ViewData["Title"] = "Register"; Layout = null; #line default #line hidden #nullable disable WriteLiteral("\n\n\n\n<!DOCTYPE html>\n<html lang=\"en\">\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("head", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4ab2b1218382f5f9b481c0e07d1339f21a0808ea13383", async() => { WriteLiteral("\n <meta charset=\"UTF-8\">\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1.0\">\n <meta http-equiv=\"X-UA-Compatible\" content=\"ie=edge\">\n <title>Sign Up Form by Colorlib</title>\n\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "4ab2b1218382f5f9b481c0e07d1339f21a0808ea13864", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_0); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "4ab2b1218382f5f9b481c0e07d1339f21a0808ea15041", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_2); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4ab2b1218382f5f9b481c0e07d1339f21a0808ea16220", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_3); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4ab2b1218382f5f9b481c0e07d1339f21a0808ea17318", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_4); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("link", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "4ab2b1218382f5f9b481c0e07d1339f21a0808ea18416", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_5); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_1); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n"); } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.HeadTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_HeadTagHelper); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n"); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("body", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4ab2b1218382f5f9b481c0e07d1339f21a0808ea20295", async() => { WriteLiteral("\n\n <div class=\"main\">\n\n <section class=\"signup\">\n <!-- <img src=\"images/signup-bg.jpg\" alt=\"\"> -->\n <div class=\"container\">\n <div class=\"signup-content\">\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("form", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4ab2b1218382f5f9b481c0e07d1339f21a0808ea20791", async() => { WriteLiteral("\n <h2 class=\"form-title\">Kayıt Ol</h2>\n <div class=\"form-group\">\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "4ab2b1218382f5f9b481c0e07d1339f21a0808ea21200", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 36 "C:\Users\suley\Desktop\NetCore_3.1\.NetCore_3.1\E_Ticaret.WebUI\Views\Account\Register.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.UserName); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.InputTypeName = (string)__tagHelperAttribute_6.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_8); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_9); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n </div>\n <div class=\"form-group\">\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "4ab2b1218382f5f9b481c0e07d1339f21a0808ea23365", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 39 "C:\Users\suley\Desktop\NetCore_3.1\.NetCore_3.1\E_Ticaret.WebUI\Views\Account\Register.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Email); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.InputTypeName = (string)__tagHelperAttribute_10.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_10); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_11); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_12); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n </div>\n <div class=\"form-group\">\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "4ab2b1218382f5f9b481c0e07d1339f21a0808ea25531", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 42 "C:\Users\suley\Desktop\NetCore_3.1\.NetCore_3.1\E_Ticaret.WebUI\Views\Account\Register.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.Password); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.InputTypeName = (string)__tagHelperAttribute_6.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_6); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_13); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_14); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n <span toggle=\"#password\" class=\"zmdi zmdi-eye field-icon toggle-password\"></span>\n </div>\n <div class=\"form-group\">\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("input", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.SelfClosing, "4ab2b1218382f5f9b481c0e07d1339f21a0808ea27813", async() => { } ); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.InputTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper); #nullable restore #line 46 "C:\Users\suley\Desktop\NetCore_3.1\.NetCore_3.1\E_Ticaret.WebUI\Views\Account\Register.cshtml" __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For = ModelExpressionProvider.CreateModelExpression(ViewData, __model => __model.ComfirmPassword); #line default #line hidden #nullable disable __tagHelperExecutionContext.AddTagHelperAttribute("asp-for", __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.For, global::Microsoft.AspNetCore.Razor.TagHelpers.HtmlAttributeValueStyle.DoubleQuotes); __Microsoft_AspNetCore_Mvc_TagHelpers_InputTagHelper.InputTypeName = (string)__tagHelperAttribute_15.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_15); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_7); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_16); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_17); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral(@" </div> <div class=""form-group""> <input type=""submit"" name=""submit"" id=""submit"" class=""form-submit"" value=""Kayıt Ol"" /> </div> "); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.FormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.RenderAtEndOfFormTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_RenderAtEndOfFormTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Controller = (string)__tagHelperAttribute_18.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_18); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Action = (string)__tagHelperAttribute_19.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_19); __Microsoft_AspNetCore_Mvc_TagHelpers_FormTagHelper.Method = (string)__tagHelperAttribute_20.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_20); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_21); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_22); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n <p class=\"loginhere\">\n Zaten Kayıtlımısınız? "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("a", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4ab2b1218382f5f9b481c0e07d1339f21a0808ea32087", async() => { WriteLiteral("Giriş Yap"); } ); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.TagHelpers.AnchorTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Controller = (string)__tagHelperAttribute_18.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_18); __Microsoft_AspNetCore_Mvc_TagHelpers_AnchorTagHelper.Action = (string)__tagHelperAttribute_23.Value; __tagHelperExecutionContext.AddTagHelperAttribute(__tagHelperAttribute_23); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_24); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n </p>\n </div>\n </div>\n </section>\n\n </div>\n\n "); __tagHelperExecutionContext = __tagHelperScopeManager.Begin("script", global::Microsoft.AspNetCore.Razor.TagHelpers.TagMode.StartTagAndEndTag, "4ab2b1218382f5f9b481c0e07d1339f21a0808ea33724", async() => { } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.UrlResolutionTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_UrlResolutionTagHelper); __tagHelperExecutionContext.AddHtmlAttribute(__tagHelperAttribute_25); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n"); } ); __Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper = CreateTagHelper<global::Microsoft.AspNetCore.Mvc.Razor.TagHelpers.BodyTagHelper>(); __tagHelperExecutionContext.Add(__Microsoft_AspNetCore_Mvc_Razor_TagHelpers_BodyTagHelper); await __tagHelperRunner.RunAsync(__tagHelperExecutionContext); if (!__tagHelperExecutionContext.Output.IsContentModified) { await __tagHelperExecutionContext.SetOutputContentAsync(); } Write(__tagHelperExecutionContext.Output); __tagHelperExecutionContext = __tagHelperScopeManager.End(); WriteLiteral("\n</html>\n\n"); } #pragma warning restore 1998 [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.ViewFeatures.IModelExpressionProvider ModelExpressionProvider { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IUrlHelper Url { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.IViewComponentHelper Component { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IJsonHelper Json { get; private set; } [global::Microsoft.AspNetCore.Mvc.Razor.Internal.RazorInjectAttribute] public global::Microsoft.AspNetCore.Mvc.Rendering.IHtmlHelper<E_Ticaret.WebUI.Models.RegisterViewModel> Html { get; private set; } } } #pragma warning restore 1591
93.123711
407
0.733477
[ "MIT" ]
suleymanaylar/.NetCore_3.1
E_Ticaret.WebUI/obj/Debug/netcoreapp3.1/Razor/Views/Account/Register.cshtml.g.cs
36,142
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. // See the LICENSE file in the project root for more information. #nullable enable using System.Diagnostics.CodeAnalysis; using System.Runtime.CompilerServices; using Microsoft.CodeAnalysis.Host.Mef; namespace Microsoft.CodeAnalysis.Host { internal sealed partial class CodeStyleHostLanguageServices : HostLanguageServices { private static readonly ConditionalWeakTable<HostLanguageServices, CodeStyleHostLanguageServices> s_mappedLanguageServices = new ConditionalWeakTable<HostLanguageServices, CodeStyleHostLanguageServices>(); private static readonly ConditionalWeakTable<string, MefHostExportProvider> s_exportProvidersByLanguageCache = new ConditionalWeakTable<string, MefHostExportProvider>(); private readonly HostLanguageServices _hostLanguageServices; private readonly HostLanguageServices _codeStyleLanguageServices; [SuppressMessage("ApiDesign", "RS0030:Do not used banned APIs", Justification = "This is the replacement API")] private CodeStyleHostLanguageServices(HostLanguageServices hostLanguageServices) { _hostLanguageServices = hostLanguageServices; var exportProvider = s_exportProvidersByLanguageCache.GetValue(hostLanguageServices.Language, MefHostExportProvider.Create); _codeStyleLanguageServices = new MefWorkspaceServices(exportProvider, hostLanguageServices.WorkspaceServices.Workspace) .GetLanguageServices(hostLanguageServices.Language); } public static CodeStyleHostLanguageServices? GetMappedCodeStyleLanguageServices(HostLanguageServices? hostLanguageServices) => hostLanguageServices != null ? s_mappedLanguageServices.GetValue(hostLanguageServices, Create) : null; public static CodeStyleHostLanguageServices GetRequiredMappedCodeStyleLanguageServices(HostLanguageServices hostLanguageServices) => s_mappedLanguageServices.GetValue(hostLanguageServices, Create); private static CodeStyleHostLanguageServices Create(HostLanguageServices hostLanguageServices) => new CodeStyleHostLanguageServices(hostLanguageServices); public override HostWorkspaceServices WorkspaceServices => _hostLanguageServices.WorkspaceServices; public override string Language => _hostLanguageServices.Language; public override TLanguageService? GetService<TLanguageService>() where TLanguageService : default => _codeStyleLanguageServices.GetService<TLanguageService>() ?? _hostLanguageServices.GetService<TLanguageService>(); } }
53.901961
137
0.783921
[ "MIT" ]
06needhamt/roslyn
src/CodeStyle/Core/CodeFixes/Host/Mef/CodeStyleHostLanguageServices.MefHostExportProvider.cs
2,751
C#
using System; using uSync8.BackOffice.Configuration; namespace uSync8.BackOffice.SyncHandlers { [Obsolete("Extended Handler Config gives better results")] public class HandlerConfigPair { public ISyncHandler Handler { get; set; } public HandlerSettings Settings { get; set; } } }
22.5
62
0.707937
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
JoseMarcenaro/uSync8
uSync8.BackOffice/SyncHandlers/Models/HandlerConfigPair.cs
317
C#
// *** WARNING: this file was generated by the Pulumi Terraform Bridge (tfgen) Tool. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.Cloudflare { /// <summary> /// Define Firewall rules using filter expressions for more control over how traffic is matched to the rule. /// A filter expression permits selecting traffic by multiple criteria allowing greater freedom in rule creation. /// /// Filter expressions needs to be created first before using Firewall Rule. See Filter. /// /// ## Example Usage /// /// ```csharp /// using Pulumi; /// using Cloudflare = Pulumi.Cloudflare; /// /// class MyStack : Stack /// { /// public MyStack() /// { /// var wordpressFilter = new Cloudflare.Filter("wordpressFilter", new Cloudflare.FilterArgs /// { /// ZoneId = "d41d8cd98f00b204e9800998ecf8427e", /// Description = "Wordpress break-in attempts that are outside of the office", /// Expression = "(http.request.uri.path ~ \".*wp-login.php\" or http.request.uri.path ~ \".*xmlrpc.php\") and ip.src ne 192.0.2.1", /// }); /// var wordpressFirewallRule = new Cloudflare.FirewallRule("wordpressFirewallRule", new Cloudflare.FirewallRuleArgs /// { /// ZoneId = "d41d8cd98f00b204e9800998ecf8427e", /// Description = "Block wordpress break-in attempts", /// FilterId = wordpressFilter.Id, /// Action = "block", /// }); /// } /// /// } /// ``` /// /// ## Import /// /// Firewall Rule can be imported using a composite ID formed of zone ID and rule ID, e.g. /// /// ```sh /// $ pulumi import cloudflare:index/firewallRule:FirewallRule default d41d8cd98f00b204e9800998ecf8427e/9e107d9d372bb6826bd81d3542a419d6 /// ``` /// /// where* `d41d8cd98f00b204e9800998ecf8427e` - zone ID * `9e107d9d372bb6826bd81d3542a419d6` - rule ID as returned by [API](https://api.cloudflare.com/#zone-firewall-filter-rules) /// </summary> [CloudflareResourceType("cloudflare:index/firewallRule:FirewallRule")] public partial class FirewallRule : Pulumi.CustomResource { /// <summary> /// The action to apply to a matched request. Allowed values: "block", "challenge", "allow", "js_challenge", "bypass". Enterprise plan also allows "log". /// </summary> [Output("action")] public Output<string> Action { get; private set; } = null!; /// <summary> /// A description of the rule to help identify it. /// </summary> [Output("description")] public Output<string?> Description { get; private set; } = null!; [Output("filterId")] public Output<string> FilterId { get; private set; } = null!; /// <summary> /// Whether this filter based firewall rule is currently paused. Boolean value. /// </summary> [Output("paused")] public Output<bool?> Paused { get; private set; } = null!; /// <summary> /// The priority of the rule to allow control of processing order. A lower number indicates high priority. If not provided, any rules with a priority will be sequenced before those without. /// </summary> [Output("priority")] public Output<int?> Priority { get; private set; } = null!; /// <summary> /// List of products to bypass for a request when the bypass action is used. Allowed values: "zoneLockdown", "uaBlock", "bic", "hot", "securityLevel", "rateLimit", "waf". /// </summary> [Output("products")] public Output<ImmutableArray<string>> Products { get; private set; } = null!; /// <summary> /// The DNS zone to which the Filter should be added. /// </summary> [Output("zoneId")] public Output<string> ZoneId { get; private set; } = null!; /// <summary> /// Create a FirewallRule 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 FirewallRule(string name, FirewallRuleArgs args, CustomResourceOptions? options = null) : base("cloudflare:index/firewallRule:FirewallRule", name, args ?? new FirewallRuleArgs(), MakeResourceOptions(options, "")) { } private FirewallRule(string name, Input<string> id, FirewallRuleState? state = null, CustomResourceOptions? options = null) : base("cloudflare:index/firewallRule:FirewallRule", 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 FirewallRule 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 FirewallRule Get(string name, Input<string> id, FirewallRuleState? state = null, CustomResourceOptions? options = null) { return new FirewallRule(name, id, state, options); } } public sealed class FirewallRuleArgs : Pulumi.ResourceArgs { /// <summary> /// The action to apply to a matched request. Allowed values: "block", "challenge", "allow", "js_challenge", "bypass". Enterprise plan also allows "log". /// </summary> [Input("action", required: true)] public Input<string> Action { get; set; } = null!; /// <summary> /// A description of the rule to help identify it. /// </summary> [Input("description")] public Input<string>? Description { get; set; } [Input("filterId", required: true)] public Input<string> FilterId { get; set; } = null!; /// <summary> /// Whether this filter based firewall rule is currently paused. Boolean value. /// </summary> [Input("paused")] public Input<bool>? Paused { get; set; } /// <summary> /// The priority of the rule to allow control of processing order. A lower number indicates high priority. If not provided, any rules with a priority will be sequenced before those without. /// </summary> [Input("priority")] public Input<int>? Priority { get; set; } [Input("products")] private InputList<string>? _products; /// <summary> /// List of products to bypass for a request when the bypass action is used. Allowed values: "zoneLockdown", "uaBlock", "bic", "hot", "securityLevel", "rateLimit", "waf". /// </summary> public InputList<string> Products { get => _products ?? (_products = new InputList<string>()); set => _products = value; } /// <summary> /// The DNS zone to which the Filter should be added. /// </summary> [Input("zoneId", required: true)] public Input<string> ZoneId { get; set; } = null!; public FirewallRuleArgs() { } } public sealed class FirewallRuleState : Pulumi.ResourceArgs { /// <summary> /// The action to apply to a matched request. Allowed values: "block", "challenge", "allow", "js_challenge", "bypass". Enterprise plan also allows "log". /// </summary> [Input("action")] public Input<string>? Action { get; set; } /// <summary> /// A description of the rule to help identify it. /// </summary> [Input("description")] public Input<string>? Description { get; set; } [Input("filterId")] public Input<string>? FilterId { get; set; } /// <summary> /// Whether this filter based firewall rule is currently paused. Boolean value. /// </summary> [Input("paused")] public Input<bool>? Paused { get; set; } /// <summary> /// The priority of the rule to allow control of processing order. A lower number indicates high priority. If not provided, any rules with a priority will be sequenced before those without. /// </summary> [Input("priority")] public Input<int>? Priority { get; set; } [Input("products")] private InputList<string>? _products; /// <summary> /// List of products to bypass for a request when the bypass action is used. Allowed values: "zoneLockdown", "uaBlock", "bic", "hot", "securityLevel", "rateLimit", "waf". /// </summary> public InputList<string> Products { get => _products ?? (_products = new InputList<string>()); set => _products = value; } /// <summary> /// The DNS zone to which the Filter should be added. /// </summary> [Input("zoneId")] public Input<string>? ZoneId { get; set; } public FirewallRuleState() { } } }
41.747967
197
0.596981
[ "ECL-2.0", "Apache-2.0" ]
pulumi/pulumi-cloudflare
sdk/dotnet/FirewallRule.cs
10,270
C#
#region license // Copyright (c) 2007-2010 Mauricio Scheffer // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. #endregion using System; using System.Collections; using System.Collections.Generic; using System.Linq; using System.Reflection; using System.Xml.Linq; using System.Xml.XPath; using Xunit; using SolrNet.Attributes; using SolrNet.Impl; using SolrNet.Impl.DocumentPropertyVisitors; using SolrNet.Impl.FieldParsers; using SolrNet.Impl.ResponseParsers; using SolrNet.Mapping; using SolrNet.Tests.Utils; using Castle.Facilities.SolrNetIntegration; namespace SolrNet.Tests { public partial class SolrQueryResultsParserTests { private static SolrDocumentResponseParser<T> GetDocumentParser<T>() { var mapper = new AttributesMappingManager(); return GetDocumentParser<T>(mapper); } private static SolrDocumentResponseParser<T> GetDocumentParser<T>(IReadOnlyMappingManager mapper) { return new SolrDocumentResponseParser<T>(mapper, new DefaultDocumentVisitor(mapper, new DefaultFieldParser()), new SolrDocumentActivator<T>()); } [Fact] public void ParseDocument() { var parser = GetDocumentParser<TestDocument>(); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.response.xml"); var docNode = xml.XPathSelectElement("response/result/doc"); var doc = parser.ParseDocument(docNode); Assert.NotNull(doc); Assert.Equal(123456, doc.Id); } [Fact] public void ParseDocumentWithMappingManager() { var mapper = new MappingManager(); mapper.Add(typeof(TestDocumentWithoutAttributes).GetProperty("Id"), "id"); var parser = GetDocumentParser<TestDocumentWithoutAttributes>(mapper); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.response.xml"); var docNode = xml.XPathSelectElement("response/result/doc"); var doc = parser.ParseDocument(docNode); Assert.NotNull(doc); Assert.Equal(123456, doc.Id); } private static SolrQueryResults<T> ParseFromResource<T>(string xmlResource) { var docParser = GetDocumentParser<T>(); var parser = new ResultsResponseParser<T>(docParser); var r = new SolrQueryResults<T>(); var xml = EmbeddedResource.GetEmbeddedXml(typeof(SolrQueryResultsParserTests), xmlResource); parser.Parse(xml, r); return r; } [Fact] public void NumFound() { var r = ParseFromResource<TestDocument>("Resources.response.xml"); Assert.Equal(1, r.NumFound); } [Fact] public void CanParseNextCursormark() { var r = ParseFromResource<TestDocument>("Resources.response.xml"); Assert.Equal(new StartOrCursor.Cursor("AoEoZTQ3YmY0NDM="), r.NextCursorMark); } [Fact] public void Parse() { var results = ParseFromResource<TestDocument>("Resources.response.xml"); Assert.Single(results); var doc = results[0]; Assert.Equal(123456, doc.Id); } [Fact] public void SetPropertyWithArrayOfStrings() { var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithArrays.xml"); var fieldNode = xml.XPathSelectElement("response/result/doc/arr[@name='cat']"); var mapper = new AttributesMappingManager(); var visitor = new DefaultDocumentVisitor(mapper, new DefaultFieldParser()); var doc = new TestDocumentWithArrays(); visitor.Visit(doc, "cat", fieldNode); Assert.Equal(2, doc.Cat.Count); var cats = new List<string>(doc.Cat); Assert.Equal("electronics", cats[0]); Assert.Equal("hard drive", cats[1]); } [Fact] public void SetPropertyDouble() { var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithArrays.xml"); var fieldNode = xml.XPathSelectElement("response/result/doc/float[@name='price']"); var mapper = new AttributesMappingManager(); var visitor = new DefaultDocumentVisitor(mapper, new DefaultFieldParser()); var doc = new TestDocumentWithArrays(); visitor.Visit(doc, "price", fieldNode); Assert.Equal(92d, doc.Price); } [Fact] public void SetPropertyNullableDouble() { var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithArrays.xml"); var fieldNode = xml.XPathSelectElement("response/result/doc/float[@name='price']"); var mapper = new AttributesMappingManager(); var visitor = new DefaultDocumentVisitor(mapper, new DefaultFieldParser()); var doc = new TestDocumentWithNullableDouble(); visitor.Visit(doc, "price", fieldNode); Assert.Equal(92d, doc.Price); } [Fact] public void SetPropertyWithIntCollection() { var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithArrays.xml"); var fieldNode = xml.XPathSelectElement("response/result/doc/arr[@name='numbers']"); var mapper = new AttributesMappingManager(); var visitor = new DefaultDocumentVisitor(mapper, new DefaultFieldParser()); var doc = new TestDocumentWithArrays(); visitor.Visit(doc, "numbers", fieldNode); Assert.Equal(2, doc.Numbers.Count); var numbers = new List<int>(doc.Numbers); Assert.Equal(1, numbers[0]); Assert.Equal(2, numbers[1]); } [Fact] public void SetPropertyWithNonGenericCollection() { var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithArrays.xml"); var fieldNode = xml.XPathSelectElement("response/result/doc/arr[@name='numbers']"); var mapper = new AttributesMappingManager(); var visitor = new DefaultDocumentVisitor(mapper, new DefaultFieldParser()); var doc = new TestDocumentWithArrays3(); visitor.Visit(doc, "numbers", fieldNode); Assert.Equal(2, doc.Numbers.Count); var numbers = new ArrayList(doc.Numbers); Assert.Equal(1, numbers[0]); Assert.Equal(2, numbers[1]); } [Fact] public void SetPropertyWithArrayOfIntsToIntArray() { var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithArrays.xml"); var fieldNode = xml.XPathSelectElement("response/result/doc/arr[@name='numbers']"); var mapper = new AttributesMappingManager(); var visitor = new DefaultDocumentVisitor(mapper, new DefaultFieldParser()); var doc = new TestDocumentWithArrays2(); visitor.Visit(doc, "numbers", fieldNode); Assert.Equal(2, doc.Numbers.Length); var numbers = new List<int>(doc.Numbers); Assert.Equal(1, numbers[0]); Assert.Equal(2, numbers[1]); } [Fact] public void ParseResultsWithArrays() { var results = ParseFromResource<TestDocumentWithArrays>("Resources.responseWithArrays.xml"); Assert.Single(results); var doc = results[0]; Assert.Equal("SP2514N", doc.Id); } [Fact] public void SupportsDateTime() { var results = ParseFromResource<TestDocumentWithDate>("Resources.responseWithDate.xml"); Assert.Single(results); var doc = results[0]; Assert.Equal(new DateTime(2001, 1, 2, 3, 4, 5), doc.Fecha); } [Fact] public void ParseDate_without_milliseconds() { var dt = DateTimeFieldParser.ParseDate("2001-01-02T03:04:05Z"); Assert.Equal(new DateTime(2001, 1, 2, 3, 4, 5), dt); } [Fact] public void ParseDate_with_milliseconds() { var dt = DateTimeFieldParser.ParseDate("2001-01-02T03:04:05.245Z"); Assert.Equal(new DateTime(2001, 1, 2, 3, 4, 5, 245), dt); } [Fact] public void SupportsNullableDateTime() { var results = ParseFromResource<TestDocumentWithNullableDate>("Resources.responseWithDate.xml"); Assert.Single(results); var doc = results[0]; Assert.Equal(new DateTime(2001, 1, 2, 3, 4, 5), doc.Fecha); } [Fact] public void SupportsIEnumerable() { var results = ParseFromResource<TestDocumentWithArrays4>("Resources.responseWithArraysSimple.xml"); Assert.Single(results); var doc = results[0]; Assert.Equal(2, new List<string>(doc.Features).Count); } [Fact] public void SupportsGuid() { var results = ParseFromResource<TestDocWithGuid>("Resources.responseWithGuid.xml"); Assert.Single(results); var doc = results[0]; //Console.WriteLine(doc.Key); } [Fact] public void SupportsEnumAsInteger() { var results = ParseFromResource<TestDocWithEnum>("Resources.responseWithEnumAsInt.xml"); Assert.Single(results); var doc = results[0]; //Console.WriteLine(doc.En); } [Fact] public void SupportsEnumAsString() { var results = ParseFromResource<TestDocWithEnum>("Resources.responseWithEnumAsString.xml"); Assert.Single(results); var doc = results[0]; //Console.WriteLine(doc.En); } [Fact] public void EmptyEnumThrows() { var mapper = new MappingManager(); mapper.Add(typeof(TestDocWithEnum).GetProperty("En"), "basicview"); var docParser = GetDocumentParser<TestDocWithEnum>(mapper); var parser = new ResultsResponseParser<TestDocWithEnum>(docParser); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.response.xml"); var results = new SolrQueryResults<TestDocWithEnum>(); Assert.Throws<Exception>(() => parser.Parse(xml, results)); } [Fact] public void SupportsNullableGuidWithEmptyField() { var results = ParseFromResource<TestDocWithNullableEnum>("Resources.response.xml"); Assert.Single(results); Assert.False(results[0].BasicView.HasValue); } [Fact] public void GenericDictionary_string_string() { var results = ParseFromResource<TestDocWithGenDict>("Resources.responseWithDict.xml"); Assert.Single(results); var doc = results[0]; Assert.NotNull(doc.Dict); Assert.Equal(2, doc.Dict.Count); Assert.Equal("1", doc.Dict["One"]); Assert.Equal("2", doc.Dict["Two"]); } [Fact] public void GenericDictionary_string_int() { var results = ParseFromResource<TestDocWithGenDict2>("Resources.responseWithDict.xml"); Assert.Single(results); var doc = results[0]; Assert.NotNull(doc.Dict); Assert.Equal(2, doc.Dict.Count); Assert.Equal(1, doc.Dict["One"]); Assert.Equal(2, doc.Dict["Two"]); } [Fact] public void GenericDictionary_string_float() { var results = ParseFromResource<TestDocWithGenDict3>("Resources.responseWithDictFloat.xml"); Assert.Single(results); var doc = results[0]; Assert.NotNull(doc.Dict); Assert.Equal(2, doc.Dict.Count); Assert.Equal(1.45f, doc.Dict["One"]); Assert.Equal(2.234f, doc.Dict["Two"]); } [Fact] public void GenericDictionary_string_decimal() { var results = ParseFromResource<TestDocWithGenDict4>("Resources.responseWithDictFloat.xml"); Assert.Single(results); var doc = results[0]; Assert.NotNull(doc.Dict); Assert.Equal(2, doc.Dict.Count); Assert.Equal(1.45m, doc.Dict["One"]); Assert.Equal(2.234m, doc.Dict["Two"]); } [Fact] public void GenericDictionary_rest_of_fields() { var results = ParseFromResource<TestDocWithGenDict5>("Resources.responseWithDictFloat.xml"); Assert.Equal("1.45", results[0].DictOne); Assert.NotNull(results[0].Dict); Assert.Equal(4, results[0].Dict.Count); Assert.Equal("2.234", results[0].Dict["DictTwo"]); Assert.Equal(new DateTime(1, 1, 1), results[0].Dict["timestamp"]); Assert.Equal(92.0f, results[0].Dict["price"]); Assert.IsAssignableFrom<ICollection>(results[0].Dict["features"]); } [Fact] public void WrongFieldDoesntThrow() { var results = ParseFromResource<TestDocumentWithDate>("Resources.responseWithArraysSimple.xml"); Assert.Single(results); var doc = results[0]; } [Fact] public void ReadsMaxScoreAttribute() { var results = ParseFromResource<TestDocumentWithArrays4>("Resources.responseWithArraysSimple.xml"); Assert.Equal(1.6578954, results.MaxScore); } [Fact] public void ReadMaxScore_doesnt_crash_if_not_present() { var results = ParseFromResource<TestDocument>("Resources.response.xml"); Assert.Null(results.MaxScore); } public void ProfileTest(ProfilingContainer container) { var parser = container.Resolve<ISolrAbstractResponseParser<TestDocumentWithArrays>>(); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithArraysSimple.xml"); var results = new SolrQueryResults<TestDocumentWithArrays>(); for (var i = 0; i < 1000; i++) { parser.Parse(xml, results); } var profile = Flatten(container.GetProfile()); var q = from n in profile group n.Value by n.Key into x let kv = new { method = x.Key, count = x.Count(), total = x.Sum(t => t.TotalMilliseconds) } orderby kv.total descending select kv; //foreach (var i in q) // Console.WriteLine("{0} {1}: {2} executions, {3}ms", i.method.DeclaringType, i.method, i.count, i.total); } public IEnumerable<KeyValuePair<MethodInfo, TimeSpan>> Flatten(Node<KeyValuePair<MethodInfo, TimeSpan>> n) { if (n.Value.Key != null) yield return n.Value; foreach (var i in n.Children.SelectMany(Flatten)) yield return i; } [Fact(Skip = "Performance test, potentially slow")] public void Performance() { var container = new ProfilingContainer(); container.AddFacility("solr", new SolrNetFacility("http://localhost")); ProfileTest(container); } [Fact] public void ParseFacetResults() { var parser = new FacetsResponseParser<TestDocumentWithArrays>(); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithFacet.xml"); var r = new SolrQueryResults<TestDocumentWithArrays>(); parser.Parse(xml, r); Assert.NotNull(r.FacetFields); //Console.WriteLine(r.FacetFields.Count); Assert.True(r.FacetFields.ContainsKey("cat")); Assert.True(r.FacetFields.ContainsKey("inStock")); Assert.Equal(2, r.FacetFields["cat"].First(q => q.Key == "connector").Value); Assert.Equal(2, r.FacetFields["cat"].First(q => q.Key == "").Value); // facet.missing as empty string //Facet Ranges Assert.NotNull(r.FacetRanges); Assert.Equal(2, r.FacetRanges.Count); Assert.Equal("date-timestamp", r.FacetRanges.First().Key ); Assert.Equal("2017-07-30T00:00:00Z", r.FacetRanges.First().Value.Start); Assert.Equal("2017-08-30T00:00:00Z", r.FacetRanges.First().Value.End); Assert.Equal("+1DAY", r.FacetRanges.First().Value.Gap); Assert.Equal(41622120, r.FacetRanges.First().Value.OtherResults[FacetRangeOther.Before]); Assert.Equal(47336, r.FacetRanges.First().Value.OtherResults[FacetRangeOther.After]); Assert.Equal(75812, r.FacetRanges.First().Value.OtherResults[FacetRangeOther.Between]); Assert.Equal(31, r.FacetRanges.First().Value.RangeResults.Count); Assert.Equal("2017-07-30T00:00:00Z", r.FacetRanges.First().Value.RangeResults.First().Key); Assert.Equal(222, r.FacetRanges.First().Value.RangeResults.First().Value); Assert.Equal("2017-08-29T00:00:00Z", r.FacetRanges.First().Value.RangeResults.Last().Key); Assert.Equal(20, r.FacetRanges.First().Value.RangeResults.Last().Value); Assert.Equal("version", r.FacetRanges.Last().Key); Assert.Equal("1000", r.FacetRanges.Last().Value.Gap); Assert.Equal("1531035549990449850", r.FacetRanges.Last().Value.RangeResults.First().Key); Assert.Equal(20, r.FacetRanges.Last().Value.RangeResults.First().Value); Assert.Equal("1531035549990659850", r.FacetRanges.Last().Value.RangeResults.Last().Key); Assert.Equal(0, r.FacetRanges.Last().Value.RangeResults.Last().Value); //Facet Intervals Assert.NotNull(r.FacetIntervals); Assert.Equal(2, r.FacetIntervals.Count); Assert.Equal("letters", r.FacetIntervals.First().Key); Assert.Equal(3, r.FacetIntervals.First().Value.Count); Assert.Equal("[*,b]", r.FacetIntervals.First().Value.First().Key ); Assert.Equal(5, r.FacetIntervals.First().Value.First().Value ); Assert.Equal("bar", r.FacetIntervals.First().Value.Last().Key); Assert.Equal(4544341, r.FacetIntervals.First().Value.Last().Value); Assert.Equal("number", r.FacetIntervals.Last().Key); Assert.Equal(2, r.FacetIntervals.Last().Value.Count); Assert.Equal("[0,500]", r.FacetIntervals.Last().Value.First().Key); Assert.Equal(9, r.FacetIntervals.Last().Value.First().Value); Assert.Equal("[500,1000]", r.FacetIntervals.Last().Value.Last().Key); Assert.Equal(123, r.FacetIntervals.Last().Value.Last().Value); //Facet Queries Assert.NotNull(r.FacetQueries); //Console.WriteLine(r.FacetQueries.Count); Assert.Equal(1, r.FacetQueries.Count); } [Fact] public void ParseResponseHeader() { var parser = new HeaderResponseParser<TestDocument>(); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.response.xml"); var docNode = xml.XPathSelectElement("response/lst[@name='responseHeader']"); var header = parser.ParseHeader(docNode); Assert.Equal(1, header.Status); Assert.Equal(15, header.QTime); Assert.Equal(2, header.Params.Count); Assert.Equal("id:123456", header.Params["q"]); Assert.Equal("2.2", header.Params["version"]); } [Fact] public void ExtractResponse() { var parser = new ExtractResponseParser(new HeaderResponseParser<TestDocument>()); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithExtractContent.xml"); var extractResponse = parser.Parse(xml); Assert.Equal("Hello world!", extractResponse.Content); } private static IDictionary<string, HighlightedSnippets> ParseHighlightingResults(string rawXml) { var xml = XDocument.Parse(rawXml); var docNode = xml.XPathSelectElement("response/lst[@name='highlighting']"); var item = new Product { Id = "SP2514N" }; return HighlightingResponseParser<Product>.ParseHighlighting(new SolrQueryResults<Product> { item }, docNode); } [Fact] public void ParseHighlighting() { var highlights = ParseHighlightingResults(EmbeddedResource.GetEmbeddedString(GetType(), "Resources.responseWithHighlighting.xml")); Assert.Equal(1, highlights.Count); var kv = highlights.First().Value; Assert.Single(kv); Assert.Equal("features", kv.First().Key); Assert.Equal(1, kv.First().Value.Count); //Console.WriteLine(kv.First().Value.First()); Assert.StartsWith("<em>Noise</em>", kv.First().Value.First(), StringComparison.OrdinalIgnoreCase); } [Fact] public void ParseHighlightingWrappedWithClass() { var highlights = ParseHighlightingResults(EmbeddedResource.GetEmbeddedString(GetType(), "Resources.responseWithHighlighting.xml")); Assert.Equal(1, highlights.Count); var first = highlights.First(); Assert.Equal("SP2514N", first.Key); var fieldsWithSnippets = highlights["SP2514N"].Snippets; Assert.Equal(1, fieldsWithSnippets.Count); Assert.Equal("features", fieldsWithSnippets.First().Key); var snippets = highlights["SP2514N"].Snippets["features"]; Assert.Equal(1, snippets.Count); Assert.StartsWith("<em>Noise</em>", snippets.First(),StringComparison.OrdinalIgnoreCase); } [Fact] public void ParseHighlighting2() { var highlights = ParseHighlightingResults(EmbeddedResource.GetEmbeddedString(GetType(), "Resources.responseWithHighlighting2.xml")); var first = highlights.First(); //first.Value.Keys.ToList().ForEach(Console.WriteLine); //first.Value["source_en"].ToList().ForEach(Console.WriteLine); Assert.Equal(3, first.Value["source_en"].Count); } [Fact] public void ParseHighlighting2WrappedWithClass() { var highlights = ParseHighlightingResults(EmbeddedResource.GetEmbeddedString(GetType(), "Resources.responseWithHighlighting2.xml")); var first = highlights.First(); //foreach (var i in first.Value.Snippets.Keys) // Console.WriteLine(i); //foreach (var i in first.Value.Snippets["source_en"]) // Console.WriteLine(i); Assert.Equal(3, first.Value.Snippets["source_en"].Count); } [Fact] public void ParseHighlighting3() { var highlights = ParseHighlightingResults(EmbeddedResource.GetEmbeddedString(GetType(), "Resources.responseWithHighlighting3.xml")); Assert.Empty(highlights["e4420cc2"]); Assert.Single(highlights["e442c4cd"]); Assert.Equal(1, highlights["e442c4cd"]["bodytext"].Count); Assert.Contains("Garia lancerer", highlights["e442c4cd"]["bodytext"].First()); } [Fact] public void ParseSpellChecking() { var parser = new SpellCheckResponseParser<Product>(); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithSpellChecking.xml"); var docNode = xml.XPathSelectElement("response/lst[@name='spellcheck']"); var spellChecking = parser.ParseSpellChecking(docNode); Assert.NotNull(spellChecking); Assert.Equal("dell ultrasharp", spellChecking.Collations.First().CollationQuery); Assert.Equal(2, spellChecking.Count); } [Fact] public void ParseSpellCheckingCollateTrueInSuggestions() { // Multiple collation nodes are included in suggestions in Solr 4.x, included for backward compatibility var parser = new SpellCheckResponseParser<Product>(); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithSpellCheckingCollationInSuggestions.xml"); var docNode = xml.XPathSelectElement("response/lst[@name='spellcheck']"); var spellChecking = parser.ParseSpellChecking(docNode); Assert.NotNull(spellChecking); Assert.Equal("audit", spellChecking.Collations.First().CollationQuery); Assert.Equal("au dt", spellChecking.Collations.Last().CollationQuery); Assert.Equal(2, spellChecking.Count); Assert.Equal(2, spellChecking.Collations.Count); } [Fact] public void ParseSpellCheckingCollateTrueInCollations() { //Collations node now separates from collation nodes from suggestions var parser = new SpellCheckResponseParser<Product>(); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithSpellCheckingCollationInCollations.xml"); var docNode = xml.XPathSelectElement("response/lst[@name='spellcheck']"); var spellChecking = parser.ParseSpellChecking(docNode); Assert.NotNull(spellChecking); Assert.Equal("dell ultrasharp", spellChecking.Collations.First().CollationQuery); Assert.Equal(2, spellChecking.Count); Assert.Equal(1, spellChecking.Collations.Count); } [Theory] [InlineData("4-")] [InlineData("5+")] public void ParseSpellCheckingCollations(string solrVersion) { //Collations node now separates from collation nodes from suggestions var parser = new SpellCheckResponseParser<Product>(); XDocument xml; if (solrVersion.Equals("5+")) { xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithSpellCheckingAndCollationsSolr5+.xml"); } else { xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithSpellCheckingAndCollationsSolr4-.xml"); } var docNode = xml.XPathSelectElement("response/lst[@name='spellcheck']"); var spellChecking = parser.ParseSpellChecking(docNode); Assert.NotNull(spellChecking); Assert.NotNull(spellChecking.Collations); Assert.Equal(2, spellChecking.Collations.Count); //First result Assert.Equal("audit differences", spellChecking.Collations.First().CollationQuery); Assert.Equal(1111, spellChecking.Collations.First().Hits); Assert.Equal(2, spellChecking.Collations.First().MisspellingsAndCorrections.Count); Assert.Equal("audit", spellChecking.Collations.First().MisspellingsAndCorrections.Where(mc => mc.Key == "aodit").First().Value); Assert.Equal("differences", spellChecking.Collations.First().MisspellingsAndCorrections.Where(mc => mc.Key == "differencex").First().Value); //Second result Assert.Equal("(ao dit) differences", spellChecking.Collations.Last().CollationQuery); Assert.Equal(1234, spellChecking.Collations.Last().Hits); Assert.Equal(2, spellChecking.Collations.Last().MisspellingsAndCorrections.Count); Assert.Equal("ao dit", spellChecking.Collations.Last().MisspellingsAndCorrections.Where(mc => mc.Key == "aodit").First().Value); Assert.Equal("differences", spellChecking.Collations.Last().MisspellingsAndCorrections.Where(mc => mc.Key == "differencex").First().Value); } [Theory] [InlineData("4-")] [InlineData("5+")] public void ParseSpellCheckingCollationsNoExtended(string solrVersion) { //Collations node now separates from collation nodes from suggestions var parser = new SpellCheckResponseParser<Product>(); XDocument xml; if (solrVersion.Equals("5+")) { xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithSpellCheckingAndCollationsNoExtendedSolr5+.xml"); } else { xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithSpellCheckingAndCollationsNoExtendedSolr4-.xml"); } var docNode = xml.XPathSelectElement("response/lst[@name='spellcheck']"); var spellChecking = parser.ParseSpellChecking(docNode); Assert.NotNull(spellChecking); Assert.NotNull(spellChecking.Collations); Assert.Equal(2, spellChecking.Collations.Count); //First result Assert.Equal("audit collation", spellChecking.Collations.First().CollationQuery); Assert.Equal(0, spellChecking.Collations.First().MisspellingsAndCorrections.Count); InvalidOperationException ex1 = Assert.Throws<InvalidOperationException>(() => spellChecking.Collations.First().Hits); Assert.Equal("Operation not supported when collateExtendedResults parameter is set to false.", ex1.Message); //Second result Assert.Equal("audit (colla tion)", spellChecking.Collations.Last().CollationQuery); Assert.Equal(0, spellChecking.Collations.Last().MisspellingsAndCorrections.Count); InvalidOperationException ex2 = Assert.Throws<InvalidOperationException>(() => spellChecking.Collations.Last().Hits); Assert.Equal("Operation not supported when collateExtendedResults parameter is set to false.", ex2.Message); } [Theory] [InlineData("4-")] [InlineData("5+")] public void ParseSpellCheckingCollationsDuplicates(string solrVersion) { //Collations node now separates from collation nodes from suggestions var parser = new SpellCheckResponseParser<Product>(); XDocument xml; if (solrVersion.Equals("5+")) { xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithSpellCheckingAndCollationsDuplicatesSolr5+.xml"); } else { xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithSpellCheckingAndCollationsDuplicatesSolr4-.xml"); } var docNode = xml.XPathSelectElement("response/lst[@name='spellcheck']"); var spellChecking = parser.ParseSpellChecking(docNode); Assert.NotNull(spellChecking); Assert.NotNull(spellChecking.Collations); Assert.Equal(1, spellChecking.Collations.Count); //First result Assert.Equal("audit audit", spellChecking.Collations.ElementAt(0).CollationQuery); Assert.Equal(1111, spellChecking.Collations.ElementAt(0).Hits); Assert.Equal(2, spellChecking.Collations.ElementAt(0).MisspellingsAndCorrections.Count); Assert.Equal("audit", spellChecking.Collations.ElementAt(0).MisspellingsAndCorrections.ElementAt(0).Value); Assert.Equal("audit", spellChecking.Collations.ElementAt(0).MisspellingsAndCorrections.ElementAt(1).Value); } [Fact] public void ParseClustering() { var parser = new ClusterResponseParser<Product>(); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithClustering.xml"); var docNode = xml.XPathSelectElement("response/arr[@name='clusters']"); var clustering = parser.ParseClusterNode(docNode); Assert.NotNull(clustering); Assert.Equal(89, clustering.Clusters.Count()); Assert.Equal("International", clustering.Clusters.First().Label); Assert.Equal(33.729704170097, clustering.Clusters.First().Score); Assert.Equal(8, clustering.Clusters.First().Documents.Count()); Assert.Equal("19622040", clustering.Clusters.First().Documents.First()); } [Fact] public void ParseTerms() { var parser = new TermsResponseParser<Product>(); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithTerms.xml"); var docNode = xml.XPathSelectElement("response/lst[@name='terms']"); var terms = parser.ParseTerms(docNode); Assert.NotNull(terms); Assert.Equal(2, terms.Count); Assert.Equal("text", terms.First().Field); Assert.Equal("textgen", terms.ElementAt(1).Field); Assert.Equal("boot", terms.First().Terms.First().Key); Assert.Equal(479, terms.First().Terms.First().Value); Assert.Equal("boots", terms.ElementAt(1).Terms.First().Key); Assert.Equal(463, terms.ElementAt(1).Terms.First().Value); } [Fact] public void ParseTermVector() { var parser = new TermVectorResultsParser<Product>(); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithTermVector.xml"); var docNode = xml.XPathSelectElement("response/lst[@name='termVectors']"); var docs = parser.ParseDocuments(docNode).ToList(); Assert.NotNull(docs); Assert.Equal(2, docs.Count); var cable = docs .First(d => d.UniqueKey == "3007WFP") .TermVector .First(f => f.Field == "includes"); Assert.Equal("cable", cable.Term); Assert.Equal(1, cable.Tf); Assert.Equal(1, cable.Df); Assert.Equal(1.0, cable.Tf_Idf); var positions = cable.Positions.ToList(); Assert.Equal(2, cable.Positions.Count); Assert.Equal(1, positions[0]); Assert.Equal(10, positions[1]); var offsets = cable.Offsets.ToList(); Assert.Equal(1, cable.Offsets.Count); Assert.Equal(4, offsets[0].Start); Assert.Equal(9, offsets[0].End); } [Fact] public void ParseTermVector2() { var parser = new TermVectorResultsParser<Product>(); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithTermVector2.xml"); var docNode = xml.XPathSelectElement("response/lst[@name='termVectors']"); var docs = parser.ParseDocuments(docNode).ToList(); Assert.NotNull(docs); Assert.Single(docs); Assert.Equal("20", docs[0].UniqueKey); var vectors = docs[0].TermVector.ToList(); Assert.Equal(15, vectors.Count); } [Fact] public void ParseMoreLikeThis() { var mapper = new AttributesMappingManager(); var parser = new MoreLikeThisResponseParser<Product>(new SolrDocumentResponseParser<Product>(mapper, new DefaultDocumentVisitor(mapper, new DefaultFieldParser()), new SolrDocumentActivator<Product>())); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithMoreLikeThis.xml"); var docNode = xml.XPathSelectElement("response/lst[@name='moreLikeThis']"); var product1 = new Product { Id = "UTF8TEST" }; var product2 = new Product { Id = "SOLR1000" }; var mlt = parser.ParseMoreLikeThis(new[] { product1, product2, }, docNode); Assert.NotNull(mlt); Assert.Equal(2, mlt.Count); Assert.True(mlt.ContainsKey(product1.Id)); Assert.True(mlt.ContainsKey(product2.Id)); Assert.Equal(1, mlt[product1.Id].Count); Assert.Equal(1, mlt[product2.Id].Count); //Console.WriteLine(mlt[product1.Id][0].Id); } [Fact] public void ParseStatsResults() { var parser = new StatsResponseParser<Product>(); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithStats.xml"); var docNode = xml.XPathSelectElement("response/lst[@name='stats']"); var stats = parser.ParseStats(docNode, "stats_fields"); Assert.Equal(2, stats.Count); Assert.True(stats.ContainsKey("price")); var priceStats = stats["price"]; Assert.Equal(0.0, priceStats.Min); Assert.Equal(2199.0, priceStats.Max); Assert.Equal(5251.2699999999995, priceStats.Sum); Assert.Equal(15, priceStats.Count); Assert.Equal(11, priceStats.Missing); Assert.Equal(6038619.160300001, priceStats.SumOfSquares); Assert.Equal(350.08466666666664, priceStats.Mean); Assert.Equal(547.737557906113, priceStats.StdDev); Assert.Equal(1, priceStats.FacetResults.Count); Assert.True(priceStats.FacetResults.ContainsKey("inStock")); var priceInStockStats = priceStats.FacetResults["inStock"]; Assert.Equal(2, priceInStockStats.Count); Assert.True(priceInStockStats.ContainsKey("true")); Assert.True(priceInStockStats.ContainsKey("false")); var priceInStockFalseStats = priceInStockStats["false"]; Assert.Equal(11.5, priceInStockFalseStats.Min); Assert.Equal(649.99, priceInStockFalseStats.Max); Assert.Equal(1161.39, priceInStockFalseStats.Sum); Assert.Equal(4, priceInStockFalseStats.Count); Assert.Equal(0, priceInStockFalseStats.Missing); Assert.Equal(653369.2551, priceInStockFalseStats.SumOfSquares); Assert.Equal(290.3475, priceInStockFalseStats.Mean); Assert.Equal(324.63444676281654, priceInStockFalseStats.StdDev); var priceInStockTrueStats = priceInStockStats["true"]; Assert.Equal(0.0, priceInStockTrueStats.Min); Assert.Equal(2199.0, priceInStockTrueStats.Max); Assert.Equal(4089.879999999999, priceInStockTrueStats.Sum); Assert.Equal(11, priceInStockTrueStats.Count); Assert.Equal(0, priceInStockTrueStats.Missing); Assert.Equal(5385249.905200001, priceInStockTrueStats.SumOfSquares); Assert.Equal(371.8072727272727, priceInStockTrueStats.Mean); Assert.Equal(621.6592938755265, priceInStockTrueStats.StdDev); var zeroResultsStats = stats["zeroResults"]; Assert.Equal(double.NaN, zeroResultsStats.Min); Assert.Equal(double.NaN, zeroResultsStats.Max); Assert.Equal(0, zeroResultsStats.Count); Assert.Equal(0, zeroResultsStats.Missing); Assert.Equal(0.0, zeroResultsStats.Sum); Assert.Equal(0.0, zeroResultsStats.SumOfSquares); Assert.Equal(double.NaN, zeroResultsStats.Mean); Assert.Equal(0.0, zeroResultsStats.StdDev); } [Fact] public void ParseStatsResults2() { var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.partialResponseWithStats.xml"); var parser = new StatsResponseParser<Product>(); var stats = parser.ParseStats(xml.Root, "stats_fields"); Assert.NotNull(stats); Assert.Contains("instock_prices", stats.Keys); Assert.Contains("all_prices", stats.Keys); var instock = stats["instock_prices"]; Assert.Equal(0, instock.Min); Assert.Equal(2199, instock.Max); Assert.Equal(16, instock.Count); Assert.Equal(16, instock.Missing); Assert.Equal(5251.270030975342, instock.Sum); var all = stats["all_prices"]; Assert.Equal(4089.880027770996, all.Sum); Assert.Equal(2199, all.Max); } [Fact] public void ParseFacetDateResults() { var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.partialResponseWithDateFacet.xml"); var p = new FacetsResponseParser<Product>(); var results = p.ParseFacetDates(xml.Root); Assert.Equal(1, results.Count); var result = results.First(); Assert.Equal("timestamp", result.Key); Assert.Equal("+1DAY", result.Value.Gap); Assert.Equal(new DateTime(2009, 8, 10, 0, 33, 46, 578), result.Value.End); var dateResults = result.Value.DateResults; Assert.Equal(1, dateResults.Count); Assert.Equal(16, dateResults[0].Value); Assert.Equal(new DateTime(2009, 8, 9, 0, 33, 46, 578), dateResults[0].Key); } [Fact] public void ParseFacetDateResultsWithOther() { var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.partialResponseWithDateFacetAndOther.xml"); var p = new FacetsResponseParser<Product>(); var results = p.ParseFacetDates(xml.Root); Assert.Equal(1, results.Count); var result = results.First(); Assert.Equal("timestamp", result.Key); Assert.Equal("+1DAY", result.Value.Gap); Assert.Equal(new DateTime(2009, 8, 10, 0, 46, 29), result.Value.End); Assert.Equal(new DateTime(2009, 8, 9, 22, 46, 29), result.Value.DateResults[0].Key); var other = result.Value.OtherResults; Assert.Equal(1, other[FacetDateOther.Before]); Assert.Equal(0, other[FacetDateOther.After]); Assert.Equal(0, other[FacetDateOther.Between]); } [Fact] public void ParseFacetRangeResults() { var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.partialResponseWithRangeFacet.xml"); var p = new FacetsResponseParser<Product>(); var results = p.ParseFacetRanges(xml.Root); Assert.Equal(1, results.Count); var result = results.First(); Assert.Equal("timestamp", result.Key); Assert.Equal("+1DAY", result.Value.Gap); Assert.Equal("2017-08-29T00:00:00Z", result.Value.Start); Assert.Equal("2017-08-31T00:00:00Z", result.Value.End); var RangeResults = result.Value.RangeResults; Assert.Equal(2, RangeResults.Count); Assert.Equal(27, RangeResults[0].Value); Assert.Equal("2017-08-29T00:00:00Z", RangeResults[0].Key); Assert.Equal(124, RangeResults[1].Value); Assert.Equal("2017-08-30T00:00:00Z", RangeResults[1].Key); } [Fact] public void ParseFacetRangeResultsWithOther() { var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.partialResponseWithRangeFacetAndOther.xml"); var p = new FacetsResponseParser<Product>(); var results = p.ParseFacetRanges(xml.Root); Assert.Equal(1, results.Count); var result = results.First(); Assert.Equal("timestamp", result.Key); Assert.Equal("+1DAY", result.Value.Gap); Assert.Equal("2017-08-29T00:00:00Z", result.Value.Start); Assert.Equal("2017-08-31T00:00:00Z", result.Value.End); var RangeResults = result.Value.RangeResults; Assert.Equal(2, RangeResults.Count); Assert.Equal(27, RangeResults[0].Value); Assert.Equal("2017-08-29T00:00:00Z", RangeResults[0].Key); Assert.Equal(124, RangeResults[1].Value); Assert.Equal("2017-08-30T00:00:00Z", RangeResults[1].Key); var other = result.Value.OtherResults; Assert.Equal(41739753, other[FacetRangeOther.Before]); Assert.Equal(47567, other[FacetRangeOther.After]); Assert.Equal(151, other[FacetRangeOther.Between]); } [Fact] public void ParseResultsWithGroups() { var mapper = new AttributesMappingManager(); var parser = new GroupingResponseParser<Product>(new SolrDocumentResponseParser<Product>(mapper, new DefaultDocumentVisitor(mapper, new DefaultFieldParser()), new SolrDocumentActivator<Product>())); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithGroupingOnInstock.xml"); var results = new SolrQueryResults<Product>(); parser.Parse(xml, results); Assert.Equal(1, results.Grouping.Count); Assert.Equal(2, results.Grouping["inStock"].Groups.Count()); Assert.Equal(13, results.Grouping["inStock"].Groups.First().NumFound); } [Fact] public void ParseResultsWithFacetPivot() { var parser = new FacetsResponseParser<Product>(); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.responseWithFacetPivoting.xml"); var r = new SolrQueryResults<Product>(); parser.Parse(xml, r); Assert.NotNull(r.FacetPivots); //Console.WriteLine(r.FacetPivots.Count); Assert.True(r.FacetPivots.ContainsKey("inStock,manu")); Assert.Equal(2, r.FacetPivots["inStock,manu"].Count); Assert.Equal("inStock", r.FacetPivots["inStock,manu"][0].Field); Assert.Equal(10, r.FacetPivots["inStock,manu"][0].ChildPivots.Count); } [Fact] public void PropertyWithoutSetter() { var parser = GetDocumentParser<TestDocWithoutSetter>(); var xml = EmbeddedResource.GetEmbeddedXml(GetType(), "Resources.response.xml"); var docNode = xml.XPathSelectElement("response/result/doc"); var doc = parser.ParseDocument(docNode); Assert.NotNull(doc); Assert.Equal(0, doc.Id); } [Fact] public void ParseInterestingTermsList() { var innerParser = new InterestingTermsResponseParser<Product>(); var parser = new SolrMoreLikeThisHandlerQueryResultsParser<Product>(new[] { innerParser }); var response = EmbeddedResource.GetEmbeddedString(GetType(), "Resources.responseWithInterestingTermsList.xml"); var results = parser.Parse(response); Assert.NotNull(results); Assert.NotNull(results.InterestingTerms); Assert.Equal(4, results.InterestingTerms.Count); Assert.Equal("three", results.InterestingTerms[2].Key); Assert.True(results.InterestingTerms.All(t => t.Value == 0.0f)); } [Fact] public void ParseInterestingTermsDetails() { var innerParser = new InterestingTermsResponseParser<Product>(); var parser = new SolrMoreLikeThisHandlerQueryResultsParser<Product>(new[] { innerParser }); var response = EmbeddedResource.GetEmbeddedString(GetType(), "Resources.responseWithInterestingTermsDetails.xml"); var results = parser.Parse(response); Assert.NotNull(results); Assert.NotNull(results.InterestingTerms); Assert.Equal(4, results.InterestingTerms.Count); Assert.Equal("content:three", results.InterestingTerms[2].Key); Assert.Equal(3.3f, results.InterestingTerms[2].Value); } [Fact] public void ParseMlthMatch() { var innerParser = new MoreLikeThisHandlerMatchResponseParser<TestDocWithGuid>(GetDocumentParser<TestDocWithGuid>()); var parser = new SolrMoreLikeThisHandlerQueryResultsParser<TestDocWithGuid>(new[] { innerParser }); var response = EmbeddedResource.GetEmbeddedString(GetType(), "Resources.responseWithInterestingTermsDetails.xml"); var results = parser.Parse(response); Assert.NotNull(results); Assert.NotNull(results.Match); Assert.Equal(new Guid("224fbdc1-12df-4520-9fbe-dd91f916eba1"), results.Match.Key); } public enum AEnum { One, Two, Three } public class TestDocWithEnum { [SolrField] public AEnum En { get; set; } } public class TestDocWithNullableEnum { [SolrField("basicview")] public AEnum? BasicView { get; set; } } } }
46.709108
215
0.603693
[ "Apache-2.0" ]
chipshub/SolrNet
SolrNet.Tests/SolrQueryResultsParserTests.cs
50,261
C#
using System; using System.IO; using System.Linq; using System.Media; using System.Text.RegularExpressions; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Media; using eletigo.PoeChatNotify.Controls; using eletigo.PoeChatNotify.Managers; using eletigo.PoeChatNotify.Model; using eletigo.PoeChatNotify.Monitors; using eletigo.PoeChatNotify.Settings; using eletigo.PoeChatNotify.Utility; namespace eletigo.PoeChatNotify { /// <summary> /// Логика взаимодействия для MainWindow.xaml /// </summary> public partial class MainWindow { private const string ExeClientPath = @"logs\Client.txt"; private const int CopyWhisper = 0; private const int CopyInvite = 1; private bool _isForseClose; private bool _isNewMessage; private SettingsWindow _settings; private readonly ClientMonitor _client; private readonly PoeMonitor _poe; private readonly TrayManager _tray; private readonly MediaPlayer _media; public MainWindow() { InitializeComponent(); _tray = new TrayManager(tbiTaskbarIcon) { State = TrayIconState.Disabled }; _poe = new PoeMonitor(); _poe.StateChanged += _poe_StateChanged; _client = new ClientMonitor { ClientPath = Config.Instance.ClientFilePath }; _client.Append += _client_Append; _media = new MediaPlayer(); // Controls _bindingFilterCheckers(); miNitificationChecker.IsChecked = Config.Instance.IsNotificationsEnabled; } private void Window_Loaded(object sender, RoutedEventArgs e) { // Client Scan _runScanning(); if (_client.IsScaning) return; _poe.ProcessChanged += _poe_ProcessChanged; _poe.Scan(); } private void Window_StateChanged(object sender, EventArgs e) { if (WindowState == WindowState.Minimized && Config.Instance.IsMinimizeToTrayWhenMininized) { _hideToTray(); } } private void Window_Closing(object sender, System.ComponentModel.CancelEventArgs e) { if (!_isForseClose && Config.Instance.IsMinimizeToTrayWhenClosing) { _hideToTray(); e.Cancel = true; return; } _poe?.Stop(); _client?.Stop(); // Save Config if (cbxFilterGlobal.IsChecked != null) Config.Instance.Filters[MessageType.Global].IsEnabled = (bool)cbxFilterGlobal.IsChecked; if (cbxFilterParty.IsChecked != null) Config.Instance.Filters[MessageType.Party].IsEnabled = (bool)cbxFilterParty.IsChecked; if (cbxFilterWhisper.IsChecked != null) Config.Instance.Filters[MessageType.Whisper].IsEnabled = (bool)cbxFilterWhisper.IsChecked; if (cbxFilterTrade.IsChecked != null) Config.Instance.Filters[MessageType.Trade].IsEnabled = (bool)cbxFilterTrade.IsChecked; if (cbxFilterGuild.IsChecked != null) Config.Instance.Filters[MessageType.Guild].IsEnabled = (bool)cbxFilterGuild.IsChecked; Config.Instance.Save(); Application.Current.Shutdown(); } private void Window_Activated(object sender, EventArgs e) { _messageReaded(); _media.Stop(); } private void _poe_StateChanged(object sender, StateChangedEventArgs e) { if (!e.IsForeground || !_isNewMessage) return; DispatcherHelper.Access(_messageReaded); _poe.Stop(); } private void _messageReaded() { if (!_isNewMessage) return; _isNewMessage = false; _updateTrayIcon(); } private void _poe_ProcessChanged(object sender, ProcessChangedEventArgs e) { if (e.ChangedType != ProcessChangedType.Opened) return; DispatcherHelper.Access(_runScanning); _poe.ProcessChanged -= _poe_ProcessChanged; } // http://stackoverflow.com/a/16204794 public static bool IsWindowOpen<T>(string name = "") where T : Window { return string.IsNullOrEmpty(name) ? Application.Current.Windows.OfType<T>().Any() : Application.Current.Windows.OfType<T>().Any(w => w.Name.Equals(name)); } private static bool _isMessageValid(MessageItem item) { if (!Config.Instance.Filters.ContainsKey(item.Type)) return false; var filter = Config.Instance.Filters[item.Type]; if (!filter.IsEnabled) return false; return !filter.IsRegexEnabled || Regex.IsMatch(item.Message, filter.RegexPattern); } private void _client_Append(object sender, ClientChangedEventArgs e) { DispatcherHelper.Access(() => { // Filter messages from user if (e.MessageItem.Direction == MessageDirection.To) return; // Filter if (!e.MessageItem.IsDisconnect && !_isMessageValid(e.MessageItem)) return; // Chat List lbxChat.Items.Add(e.MessageItem); lbxChat.ScrollIntoView(lbxChat.Items[lbxChat.Items.Count - 1]); if (!Config.Instance.IsNotifyWhenPoeChatNotifyIsActive && IsActive) return; // Notification if (!Config.Instance.IsNotificationsEnabled) return; if (e.MessageItem.IsDisconnect && !Config.Instance.IsNotifyWhenDisconnect) return; if (Config.Instance.IsNotifyOnlyWhenPoEIsInactive && User32.IsPoeInForeground()) return; // Tray Icon Notify _isNewMessage = true; _updateTrayIcon(); _poe.Scan(); string title; if (!e.MessageItem.IsDisconnect) title = $"{e.MessageItem.Type.GetDescription()}" + $"{(!string.IsNullOrEmpty(e.MessageItem.GuildName) ? e.MessageItem.GuildName + " " : "")}" + $"{e.MessageItem.UserName}"; else title = $"{e.MessageItem.UserName}"; var balloon = new PoeBalloon { Title = title, Message = e.MessageItem.Message, IsDisconnect = e.MessageItem.IsDisconnect }; balloon.Click += (o, args) => { if (Config.Instance.ClickShowProgram == 0) { User32.BringPoeToForeground(); } else if (Config.Instance.ClickShowProgram == 1) { _toggleWindow(); } _copyToClipboard(e.MessageItem, Config.Instance.ClickCopyToClipboard); balloon.Close(); }; int? dur = null; if (Config.Instance.NotificationDuration != 0) dur = Config.Instance.NotificationDuration < 500 ? 500 : Config.Instance.NotificationDuration; tbiTaskbarIcon.ShowCustomBalloon(balloon, PopupAnimation.Slide, dur); // Play Sound if (!e.MessageItem.IsDisconnect) { if (!Config.Instance.IsPlaySoundOnMessage) return; } else { if (!Config.Instance.IsPlaySoundOnDisconnect) return; } if (Config.Instance.IsCustomSound && File.Exists(Config.Instance.CustomSoundPath)) { try { _media.Open(new Uri(Config.Instance.CustomSoundPath)); _media.Volume = Config.Instance.CustomSoundVolume; _media.Play(); } catch (Exception) { /*custom boop*/ } } else { try { if (!e.MessageItem.IsDisconnect) { new SoundPlayer { Stream = Properties.Resources.NotifySound }.Play(); } else { new SoundPlayer { Stream = Properties.Resources.NotifySoundError }.Play(); } } catch (Exception) { /*boop*/ } } }); } private static void _bindElement(DependencyObject dObj, DependencyProperty dProp, object source, string path) { BindingOperations.SetBinding(dObj, dProp, new Binding { Source = source, Path = new PropertyPath(path), Mode = BindingMode.TwoWay, UpdateSourceTrigger = UpdateSourceTrigger.PropertyChanged }); } private void _bindingFilterCheckers() { _bindElement(cbxFilterGlobal, ToggleButton.IsCheckedProperty, Config.Instance.Filters[MessageType.Global], "IsEnabled"); _bindElement(cbxFilterParty, ToggleButton.IsCheckedProperty, Config.Instance.Filters[MessageType.Party], "IsEnabled"); _bindElement(cbxFilterWhisper, ToggleButton.IsCheckedProperty, Config.Instance.Filters[MessageType.Whisper], "IsEnabled"); _bindElement(cbxFilterTrade, ToggleButton.IsCheckedProperty, Config.Instance.Filters[MessageType.Trade], "IsEnabled"); _bindElement(cbxFilterGuild, ToggleButton.IsCheckedProperty, Config.Instance.Filters[MessageType.Guild], "IsEnabled"); } private void _updateTrayIcon() { if (_isNewMessage) { _tray.State = TrayIconState.Message; _tray.ToolTipText = "PoE Chat Notify\nYou have unread message!"; } else if (_client.IsScaning) { if (Config.Instance.IsNotificationsEnabled) { _tray.State = TrayIconState.Normal; _tray.ToolTipText = "PoE Chat Notify\nScan started..."; } else { _tray.State = TrayIconState.NotificationOff; _tray.ToolTipText = "PoE Chat Notify\nScan started...\nNotifications is OFF"; } } else if (!_client.IsScaning) { _tray.State = TrayIconState.Disabled; _tray.ToolTipText = "PoE Chat Notify\nScan stoped!"; } } private string _getClientPath() { User32.GetPoeWindow(); var process = User32.GetPoeProc(); var dir = Path.GetDirectoryName(process?.MainModule.FileName); return dir != null ? Path.Combine(dir, ExeClientPath) : string.Empty; } private void _runScanning() { if (!_client.IsScaning) _toggleScan(); } private void _toggleScan() { if (!_client.IsScaning) { _client.ClientPath = Config.Instance.ClientFilePath; if (!File.Exists(_client.ClientPath)) { if (Config.Instance.IsAutoDetect) { _client.ClientPath = _getClientPath(); if (!File.Exists(_client.ClientPath)) { MessageBox.Show("Please run Path of Exile game for detect Client.txt.", "Cannot running scanning Client.txt", MessageBoxButton.OK, MessageBoxImage.Information); return; } Config.Instance.ClientFilePath = _client.ClientPath; } else { MessageBox.Show($"File {_client.ClientPath} not found. Please set file path or enable auto-detection in settings.", "Cannot running scanning Client.txt", MessageBoxButton.OK, MessageBoxImage.Error); return; } } _client.Scan(); Indicator.Background = Brushes.DarkRed; Indicator.ToolTip = "Scanning Client.txt is running...\nPress to stop."; } else { _media.Stop(); _client.Stop(); Indicator.Background = Brushes.LightSlateGray; Indicator.ToolTip = "Scanning Client.txt is stoped!\nPress to start."; } _updateTrayIcon(); } private void _hideToTray() { Hide(); } private void _toggleWindow() { if (!IsActive) { Show(); Activate(); if (WindowState == WindowState.Minimized) WindowState = WindowState.Normal; } else { Hide(); } } private void tbiTaskbarIcon_TrayLeftMouseDown(object sender, RoutedEventArgs e) { _toggleWindow(); } private void _showSettings() { if (!IsWindowOpen<SettingsWindow>()) { _settings = new SettingsWindow(); _settings.Applied += _settings_Applied; _settings.Closed += _settings_Applied; } _settings.Show(); _settings.Activate(); } private void _settings_Applied(object sender, EventArgs e) { if (!Config.Instance.IsCustomSound || !Config.Instance.IsPlaySoundOnMessage) _media.Stop(); _updateTrayIcon(); _bindingFilterCheckers(); } private void btnSettings_Click(object sender, RoutedEventArgs e) { _showSettings(); } #region Context Menu private void _copyToClipboard(MessageItem mi, int metod) { if (metod == CopyWhisper) Clipboard.SetText($"@{mi.UserName}"); else if (metod == CopyInvite) Clipboard.SetText($"/invite {mi.UserName}"); } private MessageItem _getMessageItem(FrameworkElement mi) { PoeListItem sp = null; var placementTarget = ((ContextMenu)mi?.Parent)?.PlacementTarget; if (placementTarget != null) sp = placementTarget as PoeListItem; return sp?.DataContext as MessageItem; } private void MenuItemSettings_Click(object sender, RoutedEventArgs e) { _showSettings(); } private void MenuItemShowWindow_Click(object sender, RoutedEventArgs e) { _toggleWindow(); } private void MenuItemExit_Click(object sender, RoutedEventArgs e) { _isForseClose = true; Close(); } private void MenuItemClearLict_Click(object sender, RoutedEventArgs e) { lbxChat.Items.Clear(); } private void MenuItemWhisperUser_Click(object sender, RoutedEventArgs e) { var mi = _getMessageItem(sender as MenuItem); if (mi != null) _copyToClipboard(mi, CopyWhisper); } private void MenuItemInviteUser_Click(object sender, RoutedEventArgs e) { var mi = _getMessageItem(sender as MenuItem); if (mi != null) _copyToClipboard(mi, CopyInvite); } private void miNitificationChecker_Click(object sender, RoutedEventArgs e) { Config.Instance.IsNotificationsEnabled = miNitificationChecker.IsChecked; _updateTrayIcon(); } #endregion private void Indicator_MouseLeftButtonDown(object sender, System.Windows.Input.MouseButtonEventArgs e) { _toggleScan(); } private void lbxChat_SelectionChanged(object sender, SelectionChangedEventArgs e) { lbxChat.SelectedIndex = -1; } } }
31.568579
125
0.713642
[ "MIT" ]
eletigo/PoEChatNotify
PoeChatNotify/PoeChatNotify/MainWindow.xaml.cs
12,684
C#
using System.ComponentModel.Composition; using Microsoft.VisualStudio.Text.Classification; using Microsoft.VisualStudio.Utilities; #pragma warning disable 649 namespace Spect.Net.VsPackage.CustomEditors.TestEditor { public class Z80TestEditorClassificationDefinition { [Export(typeof(ClassificationTypeDefinition))] [Name("Z80TestKeyword")] internal static ClassificationTypeDefinition keywordDefinition; [Export(typeof(ClassificationTypeDefinition))] [Name("Z80TestComment")] internal static ClassificationTypeDefinition commentDefinition; [Export(typeof(ClassificationTypeDefinition))] [Name("Z80TestNumber")] internal static ClassificationTypeDefinition numberDefinition; [Export(typeof(ClassificationTypeDefinition))] [Name("Z80TestIdentifier")] internal static ClassificationTypeDefinition identifierDefinition; [Export(typeof(ClassificationTypeDefinition))] [Name("Z80TestKey")] internal static ClassificationTypeDefinition z80KeyDefinition; [Export(typeof(ClassificationTypeDefinition))] [Name("Z80TestBreakpoint")] internal static ClassificationTypeDefinition breakpointDefinition; [Export(typeof(ClassificationTypeDefinition))] [Name("Z80TestCurrentBreakpoint")] internal static ClassificationTypeDefinition currentBreakpointDefinition; } } #pragma warning restore 649
34.952381
81
0.750681
[ "MIT" ]
Dotneteer/spectnetide
VsIntegration/Old-Spect.Net.VsPackage/CustomEditors/TestEditor/Z80TestEditorClassificationDefinition.cs
1,470
C#
using System.ComponentModel.DataAnnotations.Schema; namespace SqlServer.Core.InformationSchema { /// <summary> /// Returns one row for each column in the current database that is used in a view definition. This information schema view returns information about the objects to which the current user has permissions. /// </summary> [Table("VIEW_COLUMN_USAGE", Schema="INFORMATION_SCHEMA")] public class ViewColumnUsage { /// <summary> /// View qualifier. /// </summary> [Column("VIEW_CATALOG")] public string ViewCatalog {get; set; } /// <summary> /// Name of schema that contains the view /// </summary> [Column("VIEW_SCHEMA")] public string ViewSchema {get; set; } /// <summary> /// View name /// </summary> [Column("VIEW_NAME")] public string ViewName {get; set; } /// <summary> /// Table qualifier. /// </summary> [Column("TABLE_CATALOG")] public string TableCatalog {get; set; } /// <summary> /// Name of schema that contains the table. /// </summary> [Column("TABLE_SCHEMA")] public string TableSchema {get; set; } /// <summary> /// Base table. /// </summary> [Column("TABLE_NAME")] public string TableName {get; set; } /// <summary> /// Column name. /// </summary> [Column("COLUMN_NAME")] public string ColumnName {get; set;} } }
26.017857
208
0.596431
[ "MIT" ]
gavindew/SqlServer.Core.InformationSchema
SqlServer.Core.InformationSchema/ViewColumnUsage.cs
1,457
C#
using UnityEngine; using System.Collections; public class coinControl : MonoBehaviour { // Use this for initialization void Start () { } // Update is called once per frame void Update () { } }
13
42
0.682692
[ "MIT" ]
Th3NiKo/Space-Shooter
Assets/Scripts/items/coinControl.cs
210
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. namespace Microsoft.Azure.Devices { public abstract class FeedbackReceiver<T> : Receiver<T> where T: FeedbackBatch { } }
28.6
101
0.737762
[ "MIT" ]
5e8a91/Azure_C_Library_new
csharp/service/Microsoft.Azure.Devices/FeedbackReceiver.cs
288
C#
using UnityEngine; using System.Collections; using UnityEngine.UI; public class PaperManager : MonoBehaviour { public GameObject[] paperArray = null; public GameObject[] playerPaperArray = null; void FixedUpdate () { testpaper (); } //检测方法 void testpaper(){ if (Input.GetKeyDown(KeyCode.Space)) { if (text (paperArray, playerPaperArray)) { nextEvent (); }else{ los(); } } } // Update is called once per frame bool text(GameObject[] paperArray1,GameObject[] paperArray2){ bool isRet = false; for(int i = 0; i <paperArray1.Length; i++) { if ((paperArray1 [i].GetComponent<MeshRenderer> ().material.mainTexture.name) != (paperArray2 [i].GetComponent<MeshRenderer> ().material.mainTexture.name)) { isRet =false; break; } if (i==paperArray1.Length-1) { isRet = true; } } return isRet; }//end text #region difrent event void win(){ Debug.Log ("true"); } void los(){ Debug.Log ("fals"); } void nextEvent(){ Debug.Log ("Next Level"); } #endregion }
18.034483
160
0.641491
[ "MIT" ]
kompyang/UnityGamePlayPocketLab
An&Wei/Assets/Script/PaperManager.cs
1,056
C#
/* * Copyright 2022 MASES s.r.l. * * 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. * * Refer to LICENSE for more information. */ using Java.Lang; using Java.Math; using Java.Util; using MASES.JCOBridge.C2JBridge; using MASES.KNet.Connect.Data; namespace MASES.KNet.Connect.Header { public class Headers : JVMBridgeBase<Headers> { public override bool IsInterface => true; public override string ClassName => "org.apache.kafka.connect.header.Headers"; [System.Obsolete("This is not public in Apache Kafka API")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public Headers() { } [System.Obsolete("This is not public in Apache Kafka API")] [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public Headers(params object[] args) : base(args) { } public static implicit operator Iterable<Header>(Headers headers) { return headers.Cast<Iterable<Header>>(); } public int Size => IExecute<int>("size"); public bool IsEmpty => IExecute<bool>("isEmpty"); public Iterator<Header> AllWithName(string key) => IExecute<Iterator<Header>>("allWithName", key); public Header LastWithName(string key) => IExecute<Header>("lastWithName", key); public Headers Add(Header header) => IExecute<Headers>("add", header); public Headers Add(string key, SchemaAndValue schemaAndValue) => IExecute<Headers>("add", key, schemaAndValue); public Headers Add(string key, object value, Schema schema) => IExecute<Headers>("add", key, value, schema); public Headers AddString(string key, string value) => IExecute<Headers>("addString", key, value); public Headers AddBoolean(string key, bool value) => IExecute<Headers>("addBoolean", key, value); public Headers AddByte(String key, byte value) => IExecute<Headers>("addByte", key, value); public Headers AddShort(String key, short value) => IExecute<Headers>("addShort", key, value); public Headers AddInt(String key, int value) => IExecute<Headers>("addInt", key, value); public Headers AddLong(String key, long value) => IExecute<Headers>("addLong", key, value); public Headers AddFloat(String key, float value) => IExecute<Headers>("addFloat", key, value); public Headers AddDouble(String key, double value) => IExecute<Headers>("addDouble", key, value); public Headers AddBytes(String key, byte[] value) => IExecute<Headers>("addBytes", key, value); public Headers AddList(String key, List value, Schema schema) => IExecute<Headers>("addList", key, value, schema); public Headers AddMap(String key, Map value, Schema schema) => IExecute<Headers>("addMap", key, value, schema); public Headers AddStruct(String key, Struct value) => IExecute<Headers>("addStruct", key, value); public Headers AddDecimal(String key, BigDecimal value) => IExecute<Headers>("addDecimal", key, value); public Headers AddDate(String key, Java.Util.Date value) => IExecute<Headers>("addDate", key, value); public Headers AddTime(String key, Java.Util.Date value) => IExecute<Headers>("addTime", key, value); public Headers AddTimestamp(String key, Java.Util.Date value) => IExecute<Headers>("addTimestamp", key, value); public Headers Remove(String key) => IExecute<Headers>("remove", key); public Headers RetainLatest(String key) => IExecute<Headers>("retainLatest", key); public Headers RetainLatest() => IExecute<Headers>("retainLatest"); public Headers Clear() => IExecute<Headers>("clear"); public Headers Duplicate() => IExecute<Headers>("duplicate"); public Headers Apply(HeaderTransform transform) => IExecute<Headers>("apply", transform); public Headers Apply(string key, HeaderTransform transform) => IExecute<Headers>("apply", key, transform); public class HeaderTransform : JVMBridgeBase<HeaderTransform> { public override bool IsInterface => true; public override string ClassName => "org.apache.kafka.connect.header.Headers$HeaderTransform"; public Header Apply(Header header) => IExecute<Header>("apply", header); } } }
42.452174
122
0.687423
[ "Apache-2.0" ]
masesdevelopers/KafkaBridge
src/net/KNet/ClientSide/BridgedClasses/Connect/Header/Headers.cs
4,884
C#
#region License // /* // * ###### // * ###### // * ############ ####( ###### #####. ###### ############ ############ // * ############# #####( ###### #####. ###### ############# ############# // * ###### #####( ###### #####. ###### ##### ###### ##### ###### // * ###### ###### #####( ###### #####. ###### ##### ##### ##### ###### // * ###### ###### #####( ###### #####. ###### ##### ##### ###### // * ############# ############# ############# ############# ##### ###### // * ############ ############ ############# ############ ##### ###### // * ###### // * ############# // * ############ // * // * Adyen Dotnet API Library // * // * Copyright (c) 2019 Adyen B.V. // * This file is open source and available under the MIT license. // * See the LICENSE file for more info. // */ #endregion using Adyen.Model.Notification; using Adyen.Util; using Microsoft.VisualStudio.TestTools.UnitTesting; using System.Collections.Generic; namespace Adyen.Test { [TestClass] public class UtilTest : BaseTest { [TestMethod] public void TestDataSign() { var postParameters = new Dictionary<string, string> { {Constants.HPPConstants.Fields.MerchantAccount, "ACC"}, {Constants.HPPConstants.Fields.CurrencyCode, "EUR"} }; var hmacValidator = new HmacValidator(); var buildSigningString = hmacValidator.BuildSigningString(postParameters); Assert.IsTrue(string.Equals("currencyCode:merchantAccount:EUR:ACC", buildSigningString)); postParameters = new Dictionary<string, string> { {Constants.HPPConstants.Fields.CurrencyCode, "EUR"}, {Constants.HPPConstants.Fields.MerchantAccount, "ACC:\\"} }; buildSigningString = hmacValidator.BuildSigningString(postParameters); Assert.IsTrue(string.Equals("currencyCode:merchantAccount:EUR:ACC\\:\\\\", buildSigningString)); } [TestMethod] public void TestHmac() { var data = "countryCode:currencyCode:merchantAccount:merchantReference:paymentAmount:sessionValidity:skinCode:NL:EUR:MagentoMerchantTest2:TEST-PAYMENT-2017-02-01-14\\:02\\:05:199:2017-02-02T14\\:02\\:05+01\\:00:PKz2KML1"; var key = "DFB1EB5485895CFA84146406857104ABB4CBCABDC8AAF103A624C8F6A3EAAB00"; var hmacValidator = new HmacValidator(); var ecnrypted = hmacValidator.CalculateHmac(data, key); Assert.IsTrue(string.Equals(ecnrypted, "34oR8T1whkQWTv9P+SzKyp8zhusf9n0dpqrm9nsqSJs=")); } [TestMethod] public void TestSerializationShopperInteractionDefault() { var paymentRequest = MockPaymentData.CreateFullPaymentRequestWithShopperInteraction(default(Model.Enum.ShopperInteraction)); var serializedPaymentRequest = JsonOperation.SerializeRequest(paymentRequest); Assert.IsFalse(serializedPaymentRequest.Contains("shopperInteraction")); } [TestMethod] public void TestNotificationRequestItemHmac() { string key = "DFB1EB5485895CFA84146406857104ABB4CBCABDC8AAF103A624C8F6A3EAAB00"; var expectedSign = "ipnxGCaUZ4l8TUW75a71/ghd2Fe5ffvX0pV4TLTntIc="; var additionalData = new Dictionary<string, string> { { Constants.AdditionalData.HmacSignature, expectedSign } }; var notificationRequestItem = new NotificationRequestItem { PspReference = "pspReference", OriginalReference = "originalReference", MerchantAccountCode = "merchantAccount", MerchantReference = "reference", Amount = new Model.Amount("EUR", 1000), EventCode = "EVENT", Success = true, AdditionalData = additionalData }; var hmacValidator = new HmacValidator(); var data = hmacValidator.GetDataToSign(notificationRequestItem); Assert.AreEqual("pspReference:originalReference:merchantAccount:reference:1000:EUR:EVENT:true", data); var encrypted = hmacValidator.CalculateHmac(notificationRequestItem, key); Assert.AreEqual(expectedSign, encrypted); notificationRequestItem.AdditionalData[Constants.AdditionalData.HmacSignature] = expectedSign; Assert.IsTrue(hmacValidator.IsValidHmac(notificationRequestItem, key)); notificationRequestItem.AdditionalData[Constants.AdditionalData.HmacSignature] = "notValidSign"; Assert.IsFalse(hmacValidator.IsValidHmac(notificationRequestItem, key)); } [TestMethod] public void TestSerializationShopperInteractionMoto() { var paymentRequest = MockPaymentData.CreateFullPaymentRequestWithShopperInteraction(Model.Enum.ShopperInteraction.Moto); var serializedPaymentRequest = JsonOperation.SerializeRequest(paymentRequest); StringAssert.Contains(serializedPaymentRequest, nameof(Model.Enum.ShopperInteraction.Moto)); } } }
48.114035
234
0.556791
[ "MIT" ]
AlexandrosMor/adyen-dotnet-api-library
Adyen.Test/UtilTest.cs
5,487
C#
using System; using Cosmos.IdUtils.GuidImplements.Core; /* * Reference to: * Nito.Guids * Author: Stephen Cleary * URL: https://github.com/StephenCleary/Guids * MIT */ namespace Cosmos.IdUtils.GuidImplements.Internals { internal static class GuidExtensions { /// <summary> /// Returns a 16-element byte array that contains the value of the GUID, in big-endian format. /// </summary> /// <param name="guid">The GUID.</param> public static byte[] ToBigEndianByteArray(this in Guid guid) { var result = guid.ToByteArray(); GuidUtility.EndianSwap(result); return result; } /// <summary> /// Decodes a GUID into its fields. /// </summary> /// <param name="guid">The GUID to decode.</param> public static DecodedGuid Decode(this in Guid guid) => new DecodedGuid(guid); } }
28.484848
102
0.594681
[ "MIT" ]
alexinea/Cosmos.Standard
src/Cosmos.Extensions.PowerCucumber/Cosmos/IdUtils/GuidImplements/Internals/GuidExtensions.cs
942
C#
// // linq.cs: support for query expressions // // Authors: Marek Safar (marek.safar@gmail.com) // // Dual licensed under the terms of the MIT X11 or GNU GPL // // Copyright 2007-2008 Novell, Inc // using System; using System.Reflection; using System.Collections.Generic; namespace Mono.CSharp.Linq { // NOTES: // Expression should be IExpression to save some memory and make a few things // easier to read // // public class QueryExpression : AQueryClause { public QueryExpression (Block block, AQueryClause query) : base (null, null, query.Location) { this.next = query; } public override Expression BuildQueryClause (ResolveContext ec, Expression lSide) { return next.BuildQueryClause (ec, lSide); } protected override Expression DoResolve (ResolveContext ec) { int counter = QueryBlock.TransparentParameter.Counter; Expression e = BuildQueryClause (ec, null); if (e != null) e = e.Resolve (ec); // // Reset counter in probing mode to ensure that all transparent // identifier anonymous types are created only once // if (ec.IsInProbingMode) QueryBlock.TransparentParameter.Counter = counter; return e; } protected override string MethodName { get { throw new NotSupportedException (); } } } public abstract class AQueryClause : ShimExpression { class QueryExpressionAccess : MemberAccess { public QueryExpressionAccess (Expression expr, string methodName, Location loc) : base (expr, methodName, loc) { } public QueryExpressionAccess (Expression expr, string methodName, TypeArguments typeArguments, Location loc) : base (expr, methodName, typeArguments, loc) { } protected override Expression Error_MemberLookupFailed (ResolveContext ec, TypeSpec container_type, TypeSpec qualifier_type, TypeSpec queried_type, string name, int arity, string class_name, MemberKind mt, BindingRestriction bf) { ec.Report.Error (1935, loc, "An implementation of `{0}' query expression pattern could not be found. " + "Are you missing `System.Linq' using directive or `System.Core.dll' assembly reference?", name); return null; } } class QueryExpressionInvocation : Invocation, MethodGroupExpr.IErrorHandler { public QueryExpressionInvocation (QueryExpressionAccess expr, Arguments arguments) : base (expr, arguments) { } protected override MethodGroupExpr DoResolveOverload (ResolveContext ec) { mg.CustomErrorHandler = this; MethodGroupExpr rmg = mg.OverloadResolve (ec, ref arguments, false, loc); return rmg; } public bool AmbiguousCall (ResolveContext ec, MethodSpec ambiguous) { ec.Report.SymbolRelatedToPreviousError (mg.BestCandidate); ec.Report.SymbolRelatedToPreviousError (ambiguous); ec.Report.Error (1940, loc, "Ambiguous implementation of the query pattern `{0}' for source type `{1}'", mg.Name, mg.InstanceExpression.GetSignatureForError ()); return true; } public bool NoExactMatch (ResolveContext ec, MethodSpec method) { var pd = method.Parameters; TypeSpec source_type = pd.ExtensionMethodType; if (source_type != null) { Argument a = arguments [0]; if (TypeManager.IsGenericType (source_type) && TypeManager.ContainsGenericParameters (source_type)) { TypeInferenceContext tic = new TypeInferenceContext (source_type.TypeArguments); tic.OutputTypeInference (ec, a.Expr, source_type); if (tic.FixAllTypes (ec)) { source_type = source_type.GetDefinition ().MakeGenericType (tic.InferredTypeArguments); } } if (!Convert.ImplicitConversionExists (ec, a.Expr, source_type)) { ec.Report.Error (1936, loc, "An implementation of `{0}' query expression pattern for source type `{1}' could not be found", mg.Name, TypeManager.CSharpName (a.Type)); return true; } } if (!method.IsGeneric) return false; if (mg.Name == "SelectMany") { ec.Report.Error (1943, loc, "An expression type is incorrect in a subsequent `from' clause in a query expression with source type `{0}'", arguments [0].GetSignatureForError ()); } else { ec.Report.Error (1942, loc, "An expression type in `{0}' clause is incorrect. Type inference failed in the call to `{1}'", mg.Name.ToLower (), mg.Name); } return true; } } // TODO: protected public AQueryClause next; protected ToplevelBlock block; protected AQueryClause (ToplevelBlock block, Expression expr, Location loc) : base (expr) { this.block = block; this.loc = loc; } protected override void CloneTo (CloneContext clonectx, Expression target) { base.CloneTo (clonectx, target); AQueryClause t = (AQueryClause) target; if (block != null) t.block = (ToplevelBlock) block.Clone (clonectx); if (next != null) t.next = (AQueryClause) next.Clone (clonectx); } protected override Expression DoResolve (ResolveContext ec) { return expr.Resolve (ec); } public virtual Expression BuildQueryClause (ResolveContext ec, Expression lSide) { Arguments args; CreateArguments (ec, out args); lSide = CreateQueryExpression (lSide, args); if (next != null) { Select s = next as Select; if (s == null || s.IsRequired) return next.BuildQueryClause (ec, lSide); // Skip transparent select clause if any clause follows if (next.next != null) return next.next.BuildQueryClause (ec, lSide); } return lSide; } protected virtual void CreateArguments (ResolveContext ec, out Arguments args) { args = new Arguments (2); LambdaExpression selector = new LambdaExpression (loc); selector.Block = block; selector.Block.AddStatement (new ContextualReturn (expr)); args.Add (new Argument (selector)); } protected Invocation CreateQueryExpression (Expression lSide, Arguments arguments) { return new QueryExpressionInvocation ( new QueryExpressionAccess (lSide, MethodName, loc), arguments); } protected Invocation CreateQueryExpression (Expression lSide, TypeArguments typeArguments, Arguments arguments) { return new QueryExpressionInvocation ( new QueryExpressionAccess (lSide, MethodName, typeArguments, loc), arguments); } protected abstract string MethodName { get; } public virtual AQueryClause Next { set { next = value; } } public AQueryClause Tail { get { return next == null ? this : next.Tail; } } } // // A query clause with an identifier (range variable) // public abstract class ARangeVariableQueryClause : AQueryClause { sealed class RangeAnonymousTypeParameter : AnonymousTypeParameter { public RangeAnonymousTypeParameter (Expression initializer, SimpleMemberName parameter) : base (initializer, parameter.Value, parameter.Location) { } protected override void Error_InvalidInitializer (ResolveContext ec, string initializer) { ec.Report.Error (1932, loc, "A range variable `{0}' cannot be initialized with `{1}'", Name, initializer); } } protected ARangeVariableQueryClause (ToplevelBlock block, Expression expr) : base (block, expr, expr.Location) { } protected static Expression CreateRangeVariableType (ToplevelBlock block, TypeContainer container, SimpleMemberName name, Expression init) { var args = new List<AnonymousTypeParameter> (2); args.Add (new AnonymousTypeParameter (block.Parameters [0])); args.Add (new RangeAnonymousTypeParameter (init, name)); return new NewAnonymousType (args, container, name.Location); } } class QueryStartClause : AQueryClause { public QueryStartClause (Expression expr) : base (null, expr, expr.Location) { } public override Expression BuildQueryClause (ResolveContext ec, Expression lSide) { expr = expr.Resolve (ec); if (expr == null) return null; if (expr.Type == InternalType.Dynamic || expr.Type == TypeManager.void_type) { ec.Report.Error (1979, expr.Location, "Query expression with a source or join sequence of type `{0}' is not allowed", TypeManager.CSharpName (expr.Type)); return null; } return next.BuildQueryClause (ec, expr); } protected override Expression DoResolve (ResolveContext ec) { Expression e = BuildQueryClause (ec, null); return e.Resolve (ec); } protected override string MethodName { get { throw new NotSupportedException (); } } } class Cast : QueryStartClause { // We don't have to clone cast type readonly FullNamedExpression type_expr; public Cast (FullNamedExpression type, Expression expr) : base (expr) { this.type_expr = type; } public override Expression BuildQueryClause (ResolveContext ec, Expression lSide) { lSide = CreateQueryExpression (expr, new TypeArguments (type_expr), null); if (next != null) return next.BuildQueryClause (ec, lSide); return lSide; } protected override string MethodName { get { return "Cast"; } } } public class GroupBy : AQueryClause { Expression element_selector; ToplevelBlock element_block; public GroupBy (ToplevelBlock block, Expression elementSelector, ToplevelBlock elementBlock, Expression keySelector, Location loc) : base (block, keySelector, loc) { // // Optimizes clauses like `group A by A' // if (!elementSelector.Equals (keySelector)) { this.element_selector = elementSelector; this.element_block = elementBlock; } } protected override void CreateArguments (ResolveContext ec, out Arguments args) { base.CreateArguments (ec, out args); if (element_selector != null) { LambdaExpression lambda = new LambdaExpression (element_selector.Location); lambda.Block = element_block; lambda.Block.AddStatement (new ContextualReturn (element_selector)); args.Add (new Argument (lambda)); } } protected override void CloneTo (CloneContext clonectx, Expression target) { GroupBy t = (GroupBy) target; if (element_selector != null) { t.element_selector = element_selector.Clone (clonectx); t.element_block = (ToplevelBlock) element_block.Clone (clonectx); } base.CloneTo (clonectx, t); } protected override string MethodName { get { return "GroupBy"; } } } public class Join : ARangeVariableQueryClause { readonly SimpleMemberName lt; ToplevelBlock inner_selector, outer_selector; public Join (ToplevelBlock block, SimpleMemberName lt, Expression inner, ToplevelBlock outerSelector, ToplevelBlock innerSelector, Location loc) : base (block, inner) { this.lt = lt; this.outer_selector = outerSelector; this.inner_selector = innerSelector; } protected override void CreateArguments (ResolveContext ec, out Arguments args) { args = new Arguments (4); args.Add (new Argument (expr)); LambdaExpression lambda = new LambdaExpression (outer_selector.StartLocation); lambda.Block = outer_selector; args.Add (new Argument (lambda)); lambda = new LambdaExpression (inner_selector.StartLocation); lambda.Block = inner_selector; args.Add (new Argument (lambda)); Expression result_selector_expr; SimpleMemberName into_variable = GetIntoVariable (); // // When select follows use is as result selector // if (next is Select) { result_selector_expr = next.Expr; next = next.next; } else { result_selector_expr = CreateRangeVariableType (block, ec.MemberContext.CurrentMemberDefinition.Parent, into_variable, new SimpleName (into_variable.Value, into_variable.Location)); } LambdaExpression result_selector = new LambdaExpression (lt.Location); result_selector.Block = new QueryBlock (ec.Compiler, block.Parent, block.Parameters, into_variable, block.StartLocation); result_selector.Block.AddStatement (new ContextualReturn (result_selector_expr)); args.Add (new Argument (result_selector)); } protected virtual SimpleMemberName GetIntoVariable () { return lt; } protected override void CloneTo (CloneContext clonectx, Expression target) { Join t = (Join) target; t.inner_selector = (ToplevelBlock) inner_selector.Clone (clonectx); t.outer_selector = (ToplevelBlock) outer_selector.Clone (clonectx); base.CloneTo (clonectx, t); } protected override string MethodName { get { return "Join"; } } } public class GroupJoin : Join { readonly SimpleMemberName into; public GroupJoin (ToplevelBlock block, SimpleMemberName lt, Expression inner, ToplevelBlock outerSelector, ToplevelBlock innerSelector, SimpleMemberName into, Location loc) : base (block, lt, inner, outerSelector, innerSelector, loc) { this.into = into; } protected override SimpleMemberName GetIntoVariable () { return into; } protected override string MethodName { get { return "GroupJoin"; } } } public class Let : ARangeVariableQueryClause { public Let (ToplevelBlock block, TypeContainer container, SimpleMemberName identifier, Expression expr) : base (block, CreateRangeVariableType (block, container, identifier, expr)) { } protected override string MethodName { get { return "Select"; } } } public class Select : AQueryClause { public Select (ToplevelBlock block, Expression expr, Location loc) : base (block, expr, loc) { } // // For queries like `from a orderby a select a' // the projection is transparent and select clause can be safely removed // public bool IsRequired { get { SimpleName sn = expr as SimpleName; if (sn == null) return true; return sn.Name != block.Parameters.FixedParameters [0].Name; } } protected override string MethodName { get { return "Select"; } } } public class SelectMany : ARangeVariableQueryClause { SimpleMemberName lt; public SelectMany (ToplevelBlock block, SimpleMemberName lt, Expression expr) : base (block, expr) { this.lt = lt; } protected override void CreateArguments (ResolveContext ec, out Arguments args) { base.CreateArguments (ec, out args); Expression result_selector_expr; // // When select follow use is as result selector // if (next is Select) { result_selector_expr = next.Expr; next = next.next; } else { result_selector_expr = CreateRangeVariableType (block, ec.MemberContext.CurrentMemberDefinition.Parent, lt, new SimpleName (lt.Value, lt.Location)); } LambdaExpression result_selector = new LambdaExpression (lt.Location); result_selector.Block = new QueryBlock (ec.Compiler, block.Parent, block.Parameters, lt, block.StartLocation); result_selector.Block.AddStatement (new ContextualReturn (result_selector_expr)); args.Add (new Argument (result_selector)); } protected override string MethodName { get { return "SelectMany"; } } } public class Where : AQueryClause { public Where (ToplevelBlock block, BooleanExpression expr, Location loc) : base (block, expr, loc) { } protected override string MethodName { get { return "Where"; } } } public class OrderByAscending : AQueryClause { public OrderByAscending (ToplevelBlock block,Expression expr) : base (block, expr, expr.Location) { } protected override string MethodName { get { return "OrderBy"; } } } public class OrderByDescending : AQueryClause { public OrderByDescending (ToplevelBlock block, Expression expr) : base (block, expr, expr.Location) { } protected override string MethodName { get { return "OrderByDescending"; } } } public class ThenByAscending : OrderByAscending { public ThenByAscending (ToplevelBlock block, Expression expr) : base (block, expr) { } protected override string MethodName { get { return "ThenBy"; } } } public class ThenByDescending : OrderByDescending { public ThenByDescending (ToplevelBlock block, Expression expr) : base (block, expr) { } protected override string MethodName { get { return "ThenByDescending"; } } } // // Implicit query block // class QueryBlock : ToplevelBlock { // // Transparent parameters are used to package up the intermediate results // and pass them onto next clause // public sealed class TransparentParameter : ImplicitLambdaParameter { public static int Counter; const string ParameterNamePrefix = "<>__TranspIdent"; public readonly ParametersCompiled Parent; public readonly string Identifier; public TransparentParameter (ParametersCompiled parent, SimpleMemberName identifier) : base (ParameterNamePrefix + Counter++, identifier.Location) { Parent = parent; Identifier = identifier.Value; } public new static void Reset () { Counter = 0; } } public sealed class ImplicitQueryParameter : ImplicitLambdaParameter { public ImplicitQueryParameter (string name, Location loc) : base (name, loc) { } } public QueryBlock (CompilerContext ctx, Block parent, SimpleMemberName lt, Location start) : base (ctx, parent, new ParametersCompiled (ctx, new ImplicitQueryParameter (lt.Value, lt.Location)), start) { if (parent != null) base.CheckParentConflictName (parent.Toplevel, lt.Value, lt.Location); } public QueryBlock (CompilerContext ctx, Block parent, ParametersCompiled parameters, SimpleMemberName lt, Location start) : base (ctx, parent, new ParametersCompiled (ctx, parameters [0].Clone (), new ImplicitQueryParameter (lt.Value, lt.Location)), start) { } public QueryBlock (CompilerContext ctx, Block parent, Location start) : base (ctx, parent, parent.Toplevel.Parameters.Clone (), start) { } public void AddTransparentParameter (CompilerContext ctx, SimpleMemberName name) { base.CheckParentConflictName (this, name.Value, name.Location); parameters = new ParametersCompiled (ctx, new TransparentParameter (parameters, name)); } protected override bool CheckParentConflictName (ToplevelBlock block, string name, Location l) { return true; } // // Query parameter reference can include transparent parameters // protected override Expression GetParameterReferenceExpression (string name, Location loc) { Expression expr = base.GetParameterReferenceExpression (name, loc); if (expr != null) return expr; TransparentParameter tp = parameters [0] as TransparentParameter; while (tp != null) { if (tp.Identifier == name) break; TransparentParameter tp_next = tp.Parent [0] as TransparentParameter; if (tp_next == null) { if (tp.Parent.GetParameterIndexByName (name) >= 0) break; } tp = tp_next; } if (tp != null) { expr = new SimpleName (parameters[0].Name, loc); TransparentParameter tp_cursor = (TransparentParameter) parameters[0]; while (tp_cursor != tp) { tp_cursor = (TransparentParameter) tp_cursor.Parent[0]; expr = new MemberAccess (expr, tp_cursor.Name); } return new MemberAccess (expr, name); } return null; } protected override void Error_AlreadyDeclared (Location loc, string var, string reason) { Report.Error (1931, loc, "A range variable `{0}' conflicts with a previous declaration of `{0}'", var); } protected override void Error_AlreadyDeclared (Location loc, string var) { Report.Error (1930, loc, "A range variable `{0}' has already been declared in this scope", var); } public override void Error_AlreadyDeclaredTypeParameter (Report r, Location loc, string name, string conflict) { r.Error (1948, loc, "A range variable `{0}' conflicts with a method type parameter", name); } } }
28.642757
153
0.684851
[ "MIT" ]
speier/shake
src/Shake/Core/Mono.CSharp/mcs/linq.cs
20,365
C#
// Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. using System; using System.Runtime.Caching.Hosting; using System.Runtime.Caching.Resources; using System.Collections; using System.IO; using System.Security; using System.Runtime.Versioning; namespace System.Runtime.Caching { #if NET5_0_OR_GREATER [UnsupportedOSPlatform("browser")] #endif internal sealed class FileChangeNotificationSystem : IFileChangeNotificationSystem { private readonly Hashtable _dirMonitors; private readonly object _lock; internal sealed class DirectoryMonitor { internal FileSystemWatcher Fsw; } internal sealed class FileChangeEventTarget { private readonly string _fileName; private readonly OnChangedCallback _onChangedCallback; private readonly FileSystemEventHandler _changedHandler; private readonly ErrorEventHandler _errorHandler; private readonly RenamedEventHandler _renamedHandler; private static bool EqualsIgnoreCase(string s1, string s2) { if (string.IsNullOrEmpty(s1) && string.IsNullOrEmpty(s2)) { return true; } if (string.IsNullOrEmpty(s1) || string.IsNullOrEmpty(s2)) { return false; } if (s2.Length != s1.Length) { return false; } return 0 == string.Compare(s1, 0, s2, 0, s2.Length, StringComparison.OrdinalIgnoreCase); } private void OnChanged(object sender, FileSystemEventArgs e) { if (EqualsIgnoreCase(_fileName, e.Name)) { _onChangedCallback(null); } } private void OnError(object sender, ErrorEventArgs e) { _onChangedCallback(null); } private void OnRenamed(object sender, RenamedEventArgs e) { if (EqualsIgnoreCase(_fileName, e.Name) || EqualsIgnoreCase(_fileName, e.OldName)) { _onChangedCallback(null); } } internal FileSystemEventHandler ChangedHandler { get { return _changedHandler; } } internal ErrorEventHandler ErrorHandler { get { return _errorHandler; } } internal RenamedEventHandler RenamedHandler { get { return _renamedHandler; } } internal FileChangeEventTarget(string fileName, OnChangedCallback onChangedCallback) { _fileName = fileName; _onChangedCallback = onChangedCallback; _changedHandler = new FileSystemEventHandler(this.OnChanged); _errorHandler = new ErrorEventHandler(this.OnError); _renamedHandler = new RenamedEventHandler(this.OnRenamed); } } internal FileChangeNotificationSystem() { _dirMonitors = Hashtable.Synchronized(new Hashtable(StringComparer.OrdinalIgnoreCase)); _lock = new object(); } void IFileChangeNotificationSystem.StartMonitoring(string filePath, OnChangedCallback onChangedCallback, out object state, out DateTimeOffset lastWriteTime, out long fileSize) { if (filePath == null) { throw new ArgumentNullException(nameof(filePath)); } if (onChangedCallback == null) { throw new ArgumentNullException(nameof(onChangedCallback)); } FileInfo fileInfo = new FileInfo(filePath); string dir = Path.GetDirectoryName(filePath); DirectoryMonitor dirMon = _dirMonitors[dir] as DirectoryMonitor; if (dirMon == null) { lock (_lock) { dirMon = _dirMonitors[dir] as DirectoryMonitor; if (dirMon == null) { dirMon = new DirectoryMonitor(); dirMon.Fsw = new FileSystemWatcher(dir); dirMon.Fsw.NotifyFilter = NotifyFilters.FileName | NotifyFilters.DirectoryName | NotifyFilters.CreationTime | NotifyFilters.Size | NotifyFilters.LastWrite | NotifyFilters.Security; dirMon.Fsw.EnableRaisingEvents = true; } _dirMonitors[dir] = dirMon; } } FileChangeEventTarget target = new FileChangeEventTarget(fileInfo.Name, onChangedCallback); lock (dirMon) { dirMon.Fsw.Changed += target.ChangedHandler; dirMon.Fsw.Created += target.ChangedHandler; dirMon.Fsw.Deleted += target.ChangedHandler; dirMon.Fsw.Error += target.ErrorHandler; dirMon.Fsw.Renamed += target.RenamedHandler; } state = target; lastWriteTime = File.GetLastWriteTime(filePath); fileSize = (fileInfo.Exists) ? fileInfo.Length : -1; } void IFileChangeNotificationSystem.StopMonitoring(string filePath, object state) { if (filePath == null) { throw new ArgumentNullException(nameof(filePath)); } if (state == null) { throw new ArgumentNullException(nameof(state)); } FileChangeEventTarget target = state as FileChangeEventTarget; if (target == null) { throw new ArgumentException(SR.Invalid_state, nameof(state)); } string dir = Path.GetDirectoryName(filePath); DirectoryMonitor dirMon = _dirMonitors[dir] as DirectoryMonitor; if (dirMon != null) { lock (dirMon) { dirMon.Fsw.Changed -= target.ChangedHandler; dirMon.Fsw.Created -= target.ChangedHandler; dirMon.Fsw.Deleted -= target.ChangedHandler; dirMon.Fsw.Error -= target.ErrorHandler; dirMon.Fsw.Renamed -= target.RenamedHandler; } } } } }
38.568966
183
0.545522
[ "MIT" ]
AerisG222/runtime
src/libraries/System.Runtime.Caching/src/System/Runtime/Caching/FileChangeNotificationSystem.cs
6,711
C#
/* * Copyright Amazon.com, Inc. or its affiliates. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"). * You may not use this file except in compliance with the License. * A copy of the License is located at * * http://aws.amazon.com/apache2.0 * * or in the "license" file accompanying this file. This file is distributed * on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either * express or implied. See the License for the specific language governing * permissions and limitations under the License. */ /* * Do not modify this file. This file is generated from the ecs-2014-11-13.normal.json service model. */ using System; using System.Collections.Generic; using System.Globalization; using System.IO; using System.Text; using System.Xml.Serialization; using Amazon.ECS.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.ECS.Model.Internal.MarshallTransformations { /// <summary> /// DescribeTaskDefinition Request Marshaller /// </summary> public class DescribeTaskDefinitionRequestMarshaller : IMarshaller<IRequest, DescribeTaskDefinitionRequest> , IMarshaller<IRequest,AmazonWebServiceRequest> { /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="input"></param> /// <returns></returns> public IRequest Marshall(AmazonWebServiceRequest input) { return this.Marshall((DescribeTaskDefinitionRequest)input); } /// <summary> /// Marshaller the request object to the HTTP request. /// </summary> /// <param name="publicRequest"></param> /// <returns></returns> public IRequest Marshall(DescribeTaskDefinitionRequest publicRequest) { IRequest request = new DefaultRequest(publicRequest, "Amazon.ECS"); string target = "AmazonEC2ContainerServiceV20141113.DescribeTaskDefinition"; request.Headers["X-Amz-Target"] = target; request.Headers["Content-Type"] = "application/x-amz-json-1.1"; request.Headers[Amazon.Util.HeaderKeys.XAmzApiVersion] = "2014-11-13"; request.HttpMethod = "POST"; request.ResourcePath = "/"; request.MarshallerVersion = 2; using (StringWriter stringWriter = new StringWriter(CultureInfo.InvariantCulture)) { JsonWriter writer = new JsonWriter(stringWriter); writer.WriteObjectStart(); var context = new JsonMarshallerContext(request, writer); if(publicRequest.IsSetInclude()) { context.Writer.WritePropertyName("include"); context.Writer.WriteArrayStart(); foreach(var publicRequestIncludeListValue in publicRequest.Include) { context.Writer.Write(publicRequestIncludeListValue); } context.Writer.WriteArrayEnd(); } if(publicRequest.IsSetTaskDefinition()) { context.Writer.WritePropertyName("taskDefinition"); context.Writer.Write(publicRequest.TaskDefinition); } writer.WriteObjectEnd(); string snippet = stringWriter.ToString(); request.Content = System.Text.Encoding.UTF8.GetBytes(snippet); } return request; } private static DescribeTaskDefinitionRequestMarshaller _instance = new DescribeTaskDefinitionRequestMarshaller(); internal static DescribeTaskDefinitionRequestMarshaller GetInstance() { return _instance; } /// <summary> /// Gets the singleton. /// </summary> public static DescribeTaskDefinitionRequestMarshaller Instance { get { return _instance; } } } }
37.5
160
0.603678
[ "Apache-2.0" ]
philasmar/aws-sdk-net
sdk/src/Services/ECS/Generated/Model/Internal/MarshallTransformations/DescribeTaskDefinitionRequestMarshaller.cs
4,350
C#
namespace Astar { public class Node { public Node(int x, int y, int z, bool iswalkable) { this.x = x;this.z = z;this.y =y; this.isWalkable = iswalkable; } public Node(int x, int y, int z) : this(x, y, z, true) { } public Node() : this(0, 0, 0) { } private int lockCount = 0; //Node's position in the grid public int x; public int y; public int z; //Node's costs for pathfinding purposes public float hCost; public float gCost; public float fCost { get //the fCost is the gCost+hCost so we can get it directly this way { return gCost + hCost; } } public Node parentNode; public bool isWalkable = true; public bool showActived = false; public bool IsWalkable { get { if (lockCount > 0) return false; return isWalkable; }} //Types of nodes we can have, we will use this later on a case by case examples public NodeType nodeType; public enum NodeType { ground, air } public override bool Equals(object obj) { if (obj == null) return false; if (!(obj is Node)) return false; var n = obj as Node; return n.x == x && n.y == y && n.z == z; } public override int GetHashCode() { return string.Format("({0},{1},{2})", x, y, z).GetHashCode(); } public void Lock() { lockCount++; } public void Unlock() { lockCount--; } } }
22.818182
93
0.474104
[ "Apache-2.0" ]
DavidSheh/version
Server/GServer/Astar/Node.cs
1,759
C#
using XUCore.Template.Razor.Applaction.User; using XUCore.Template.Razor.DbService.Notice; namespace XUCore.Template.Razor.Web.Pages.Admin.Sys.Admin.Notices { [Authorize] public class DetailModel : PageModel { private readonly INoticeAppService noticeAppService; public DetailModel(INoticeAppService noticeAppService) { this.noticeAppService = noticeAppService; } public NoticeDto NoticeDto { get; set; } public async Task OnGetAsync(long id, CancellationToken cancellationToken) { NoticeDto = await noticeAppService.GetByIdAsync(id, cancellationToken); } } }
30.318182
83
0.694153
[ "MIT" ]
xuyiazl/XUCore.Template
XUCore.Template.Razor/Content/XUCore.Template.Razor/XUCore.Template.Razor.Web/Pages/Admin/Sys/Admin/Notices/Detail.cshtml.cs
669
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // Общие сведения об этой сборке предоставляются следующим набором // набора атрибутов. Измените значения этих атрибутов для изменения сведений, // связанные со сборкой. [assembly: AssemblyTitle("Core")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("*")] [assembly: AssemblyProduct("Core")] [assembly: AssemblyCopyright("Copyright © * 2020")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Установка значения False для параметра ComVisible делает типы в этой сборке невидимыми // для компонентов COM. Если необходимо обратиться к типу в этой сборке через // COM, задайте атрибуту ComVisible значение TRUE для этого типа. [assembly: ComVisible(false)] // Следующий GUID служит для идентификации библиотеки типов, если этот проект будет видимым для COM [assembly: Guid("ab4f6099-92b7-4c56-aa83-924756bf8c64")] // Сведения о версии сборки состоят из указанных ниже четырех значений: // // Основной номер версии // Дополнительный номер версии // Номер сборки // Редакция // // Можно задать все значения или принять номера сборки и редакции по умолчанию // используя "*", как показано ниже: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.216216
99
0.75884
[ "MIT" ]
EvgenL/TheHardwareMonitor
Core/Properties/AssemblyInfo.cs
1,993
C#
// Copyright 2016 Google Inc. All Rights Reserved. // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. using Google.Api.Gax; using Google.Apis.Auth.OAuth2; using Google.Apis.Iam.v1; using Google.Apis.Iam.v1.Data; using Google.Apis.Services; using Google.Cloud.ClientTesting; using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Net.Http.Headers; using System.Threading; using System.Threading.Tasks; using Xunit; namespace Google.Cloud.Storage.V1.Snippets { [SnippetOutputCollector] [Collection(nameof(StorageSnippetFixture))] public class UrlSignerSnippets { private readonly StorageSnippetFixture _fixture; public UrlSignerSnippets(StorageSnippetFixture fixture) { _fixture = fixture; } [Fact] public async Task SignedURLGet() { var bucketName = _fixture.BucketName; var objectName = _fixture.HelloStorageObjectName; var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential; var httpClient = new HttpClient(); // Sample: SignedURLGet // Additional: Sign(string,string,TimeSpan,*,*) // Create a signed URL which can be used to get a specific object for one hour. UrlSigner urlSigner = UrlSigner.FromServiceAccountCredential(credential); string url = urlSigner.Sign(bucketName, objectName, TimeSpan.FromHours(1)); // Get the content at the created URL. HttpResponseMessage response = await httpClient.GetAsync(url); string content = await response.Content.ReadAsStringAsync(); // End sample Assert.Equal(_fixture.HelloWorldContent, content); } // See-also: Sign(string,string,TimeSpan,*,*) // Member: Sign(UrlSigner.RequestTemplate, UrlSigner.Options) // See [Sign](ref) for an example using an alternative overload. // End see-also [Fact] public async Task WithSigningVersion() { var bucketName = _fixture.BucketName; var objectName = _fixture.HelloStorageObjectName; var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential; var httpClient = new HttpClient(); // Sample: WithSigningVersion // Create a signed URL which can be used to get a specific object for one hour, // using the V4 signing process. UrlSigner urlSigner = UrlSigner .FromServiceAccountCredential(credential); string url = urlSigner.Sign(bucketName, objectName, TimeSpan.FromHours(1), signingVersion: SigningVersion.V4); // Get the content at the created URL. HttpResponseMessage response = await httpClient.GetAsync(url); string content = await response.Content.ReadAsStringAsync(); // End sample Assert.Equal(_fixture.HelloWorldContent, content); } [Fact] public async Task SignedURLPut() { var bucketName = _fixture.BucketName; var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential; var httpClient = new HttpClient(); // Sample: SignedURLPut // Create a request template that will be used to create the signed URL. var destination = "places/world.txt"; UrlSigner.RequestTemplate requestTemplate = UrlSigner.RequestTemplate .FromBucket(bucketName) .WithObjectName(destination) .WithHttpMethod(HttpMethod.Put) .WithContentHeaders(new Dictionary<string, IEnumerable<string>> { { "Content-Type", new[] { "text/plain" } } }); // Create options specifying for how long the signer URL will be valid. UrlSigner.Options options = UrlSigner.Options.FromDuration(TimeSpan.FromHours(1)); // Create a signed URL which allows the requester to PUT data with the text/plain content-type. UrlSigner urlSigner = UrlSigner.FromServiceAccountCredential(credential); string url = urlSigner.Sign(requestTemplate, options); // Upload the content into the bucket using the signed URL. string source = "world.txt"; ByteArrayContent content; using (FileStream stream = File.OpenRead(source)) { byte[] data = new byte[stream.Length]; stream.Read(data, 0, data.Length); content = new ByteArrayContent(data) { Headers = { ContentType = new MediaTypeHeaderValue("text/plain") } }; } HttpResponseMessage response = await httpClient.PutAsync(url, content); // End sample Assert.True(response.IsSuccessStatusCode); var client = StorageClient.Create(); var result = new MemoryStream(); await client.DownloadObjectAsync(bucketName, destination, result); using (var stream = File.OpenRead(source)) { var data = new byte[stream.Length]; stream.Read(data, 0, data.Length); Assert.Equal(result.ToArray(), data); } await client.DeleteObjectAsync(bucketName, destination); } // Sample: IamServiceBlobSigner internal sealed class IamServiceBlobSigner : UrlSigner.IBlobSigner { private readonly IamService _iamService; public string Id { get; } internal IamServiceBlobSigner(IamService service, string id) { _iamService = service; Id = id; } public string CreateSignature(byte[] data) => CreateRequest(data).Execute().Signature; public async Task<string> CreateSignatureAsync(byte[] data, CancellationToken cancellationToken) { ProjectsResource.ServiceAccountsResource.SignBlobRequest request = CreateRequest(data); SignBlobResponse response = await request.ExecuteAsync(cancellationToken).ConfigureAwait(false); return response.Signature; } private ProjectsResource.ServiceAccountsResource.SignBlobRequest CreateRequest(byte[] data) { SignBlobRequest body = new SignBlobRequest { BytesToSign = Convert.ToBase64String(data) }; string account = $"projects/-/serviceAccounts/{Id}"; ProjectsResource.ServiceAccountsResource.SignBlobRequest request = _iamService.Projects.ServiceAccounts.SignBlob(body, account); return request; } } // End sample [SkippableFact] public async Task SignedUrlWithIamServiceBlobSigner() { _fixture.SkipIf(Platform.Instance().Type == PlatformType.Unknown); var bucketName = _fixture.BucketName; var objectName = _fixture.HelloStorageObjectName; var credential = (await GoogleCredential.GetApplicationDefaultAsync()).UnderlyingCredential as ServiceAccountCredential; var httpClient = new HttpClient(); // Sample: IamServiceBlobSignerUsage // First obtain the email address of the default service account for this instance from the metadata server. HttpRequestMessage serviceAccountRequest = new HttpRequestMessage { // Note: you could use 169.254.169.254 as the address to avoid a DNS lookup. RequestUri = new Uri("http://metadata.google.internal/computeMetadata/v1/instance/service-accounts/default/email"), Headers = { { "Metadata-Flavor", "Google" } } }; HttpResponseMessage serviceAccountResponse = await httpClient.SendAsync(serviceAccountRequest).ConfigureAwait(false); serviceAccountResponse.EnsureSuccessStatusCode(); string serviceAccountId = await serviceAccountResponse.Content.ReadAsStringAsync(); // Create an IAM service client object using the default application credentials. GoogleCredential iamCredential = await GoogleCredential.GetApplicationDefaultAsync(); iamCredential = iamCredential.CreateScoped(IamService.Scope.CloudPlatform); IamService iamService = new IamService(new BaseClientService.Initializer { HttpClientInitializer = iamCredential }); // Create a request template that will be used to create the signed URL. UrlSigner.RequestTemplate requestTemplate = UrlSigner.RequestTemplate .FromBucket(bucketName) .WithObjectName(objectName) .WithHttpMethod(HttpMethod.Get); // Create options specifying for how long the signer URL will be valid. UrlSigner.Options options = UrlSigner.Options.FromDuration(TimeSpan.FromHours(1)); // Create a URL signer that will use the IAM service for signing. This signer is thread-safe, // and would typically occur as a dependency, e.g. in an ASP.NET Core controller, where the // same instance can be reused for each request. IamServiceBlobSigner blobSigner = new IamServiceBlobSigner(iamService, serviceAccountId); UrlSigner urlSigner = UrlSigner.FromBlobSigner(blobSigner); // Use the URL signer to sign a request for the test object for the next hour. string url = await urlSigner.SignAsync(requestTemplate, options); // Prove we can fetch the content of the test object with a simple unauthenticated GET request. HttpResponseMessage response = await httpClient.GetAsync(url); string content = await response.Content.ReadAsStringAsync(); // End sample Assert.Equal(_fixture.HelloWorldContent, content); } } }
45.348739
132
0.645418
[ "Apache-2.0" ]
tbpg/google-cloud-dotnet
apis/Google.Cloud.Storage.V1/Google.Cloud.Storage.V1.Snippets/UrlSignerSnippets.cs
10,793
C#
// ------------------------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All Rights Reserved. Licensed under the MIT License. See License in the project root for license information. // ------------------------------------------------------------------------------ // **NOTE** This file was generated by a tool and any changes will be overwritten. // Template Source: Templates\CSharp\Requests\EntityRequest.cs.tt namespace Microsoft.Graph { using System; using System.Collections.Generic; using System.IO; using System.Net.Http; using System.Threading; using System.Linq.Expressions; /// <summary> /// The type SharedPCConfigurationRequest. /// </summary> public partial class SharedPCConfigurationRequest : BaseRequest, ISharedPCConfigurationRequest { /// <summary> /// Constructs a new SharedPCConfigurationRequest. /// </summary> /// <param name="requestUrl">The URL for the built request.</param> /// <param name="client">The <see cref="IBaseClient"/> for handling requests.</param> /// <param name="options">Query and header option name value pairs for the request.</param> public SharedPCConfigurationRequest( string requestUrl, IBaseClient client, IEnumerable<Option> options) : base(requestUrl, client, options) { } /// <summary> /// Creates the specified SharedPCConfiguration using POST. /// </summary> /// <param name="sharedPCConfigurationToCreate">The SharedPCConfiguration to create.</param> /// <returns>The created SharedPCConfiguration.</returns> public System.Threading.Tasks.Task<SharedPCConfiguration> CreateAsync(SharedPCConfiguration sharedPCConfigurationToCreate) { return this.CreateAsync(sharedPCConfigurationToCreate, CancellationToken.None); } /// <summary> /// Creates the specified SharedPCConfiguration using POST. /// </summary> /// <param name="sharedPCConfigurationToCreate">The SharedPCConfiguration to create.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The created SharedPCConfiguration.</returns> public async System.Threading.Tasks.Task<SharedPCConfiguration> CreateAsync(SharedPCConfiguration sharedPCConfigurationToCreate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "POST"; var newEntity = await this.SendAsync<SharedPCConfiguration>(sharedPCConfigurationToCreate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(newEntity); return newEntity; } /// <summary> /// Deletes the specified SharedPCConfiguration. /// </summary> /// <returns>The task to await.</returns> public System.Threading.Tasks.Task DeleteAsync() { return this.DeleteAsync(CancellationToken.None); } /// <summary> /// Deletes the specified SharedPCConfiguration. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The task to await.</returns> public async System.Threading.Tasks.Task DeleteAsync(CancellationToken cancellationToken) { this.Method = "DELETE"; await this.SendAsync<SharedPCConfiguration>(null, cancellationToken).ConfigureAwait(false); } /// <summary> /// Gets the specified SharedPCConfiguration. /// </summary> /// <returns>The SharedPCConfiguration.</returns> public System.Threading.Tasks.Task<SharedPCConfiguration> GetAsync() { return this.GetAsync(CancellationToken.None); } /// <summary> /// Gets the specified SharedPCConfiguration. /// </summary> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The SharedPCConfiguration.</returns> public async System.Threading.Tasks.Task<SharedPCConfiguration> GetAsync(CancellationToken cancellationToken) { this.Method = "GET"; var retrievedEntity = await this.SendAsync<SharedPCConfiguration>(null, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(retrievedEntity); return retrievedEntity; } /// <summary> /// Updates the specified SharedPCConfiguration using PATCH. /// </summary> /// <param name="sharedPCConfigurationToUpdate">The SharedPCConfiguration to update.</param> /// <returns>The updated SharedPCConfiguration.</returns> public System.Threading.Tasks.Task<SharedPCConfiguration> UpdateAsync(SharedPCConfiguration sharedPCConfigurationToUpdate) { return this.UpdateAsync(sharedPCConfigurationToUpdate, CancellationToken.None); } /// <summary> /// Updates the specified SharedPCConfiguration using PATCH. /// </summary> /// <param name="sharedPCConfigurationToUpdate">The SharedPCConfiguration to update.</param> /// <param name="cancellationToken">The <see cref="CancellationToken"/> for the request.</param> /// <returns>The updated SharedPCConfiguration.</returns> public async System.Threading.Tasks.Task<SharedPCConfiguration> UpdateAsync(SharedPCConfiguration sharedPCConfigurationToUpdate, CancellationToken cancellationToken) { this.ContentType = "application/json"; this.Method = "PATCH"; var updatedEntity = await this.SendAsync<SharedPCConfiguration>(sharedPCConfigurationToUpdate, cancellationToken).ConfigureAwait(false); this.InitializeCollectionProperties(updatedEntity); return updatedEntity; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="value">The expand value.</param> /// <returns>The request object to send.</returns> public ISharedPCConfigurationRequest Expand(string value) { this.QueryOptions.Add(new QueryOption("$expand", value)); return this; } /// <summary> /// Adds the specified expand value to the request. /// </summary> /// <param name="expandExpression">The expression from which to calculate the expand value.</param> /// <returns>The request object to send.</returns> public ISharedPCConfigurationRequest Expand(Expression<Func<SharedPCConfiguration, object>> expandExpression) { if (expandExpression == null) { throw new ArgumentNullException(nameof(expandExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(expandExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(expandExpression)); } else { this.QueryOptions.Add(new QueryOption("$expand", value)); } return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="value">The select value.</param> /// <returns>The request object to send.</returns> public ISharedPCConfigurationRequest Select(string value) { this.QueryOptions.Add(new QueryOption("$select", value)); return this; } /// <summary> /// Adds the specified select value to the request. /// </summary> /// <param name="selectExpression">The expression from which to calculate the select value.</param> /// <returns>The request object to send.</returns> public ISharedPCConfigurationRequest Select(Expression<Func<SharedPCConfiguration, object>> selectExpression) { if (selectExpression == null) { throw new ArgumentNullException(nameof(selectExpression)); } string error; string value = ExpressionExtractHelper.ExtractMembers(selectExpression, out error); if (value == null) { throw new ArgumentException(error, nameof(selectExpression)); } else { this.QueryOptions.Add(new QueryOption("$select", value)); } return this; } /// <summary> /// Initializes any collection properties after deserialization, like next requests for paging. /// </summary> /// <param name="sharedPCConfigurationToInitialize">The <see cref="SharedPCConfiguration"/> with the collection properties to initialize.</param> private void InitializeCollectionProperties(SharedPCConfiguration sharedPCConfigurationToInitialize) { } } }
44.272727
173
0.628337
[ "MIT" ]
AzureMentor/msgraph-sdk-dotnet
src/Microsoft.Graph/Requests/Generated/SharedPCConfigurationRequest.cs
9,253
C#
using System; namespace ToDo.Web.Features { public class ToDoItemCompletedEvent { public Guid ListId { get; set; } public Guid ItemId { get; set; } public string Title { get; set; } public string Description { get; set; } } }
19.266667
47
0.567474
[ "MIT" ]
joaofbantunes/DaprSample
src/ToDo.Web/Features/ToDoItemCompletedEvent.cs
289
C#
// Copyright (c) .NET Foundation. All rights reserved. // Licensed under the MIT license. See License.txt in the project root for license information. using System.Collections.Generic; using Microsoft.AspNetCore.Razor.Language.Syntax; namespace Microsoft.AspNetCore.Razor.Language.Legacy { internal class SyntaxNodeWalker : SyntaxRewriter { private readonly List<SyntaxNode> _ancestors = new List<SyntaxNode>(); protected IReadOnlyList<SyntaxNode> Ancestors => _ancestors; protected SyntaxNode Parent => _ancestors.Count > 0 ? _ancestors[0] : null; protected override SyntaxNode DefaultVisit(SyntaxNode node) { _ancestors.Insert(0, node); try { for (var i = 0; i < node.SlotCount; i++) { var child = node.GetNodeSlot(i); Visit(child); } } finally { _ancestors.RemoveAt(0); } return node; } } }
27.947368
95
0.57533
[ "MIT" ]
dougbu/razor-tooling
src/Razor/test/Microsoft.AspNetCore.Razor.Test.Common/Language/Legacy/SyntaxNodeWalker.cs
1,064
C#
using System; namespace Open_Lab_04._06 { public class Numbers { public int[] NoOdds(int[] numbers) { for (int i = 0; i <= 100; i++) { if (IsEven(i)) { Console.WriteLine(i); } } public static bool IsEven(int value) { return value % 2 == 0; } } } }
17.608696
50
0.392593
[ "MIT" ]
marekkilv/Open-Lab-04.06
Open-Lab-04.06/Numbers.cs
407
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace Noise.UI.Views { /// <summary> /// Interaction logic for PlaybackRelatedView.xaml /// </summary> public partial class PlaybackRelatedView : UserControl { public PlaybackRelatedView() { InitializeComponent(); } } }
25.230769
60
0.739329
[ "MIT" ]
bswanson58/NoiseMusicSystem
Noise.UI/Views/PlaybackRelatedView.xaml.cs
658
C#
using BlueprintCore.Blueprints; using Kingmaker.UnitLogic.Abilities.Blueprints; using System; using WOTR_PATH_OF_RAGE.Utilities; using Kingmaker.Blueprints; using Kingmaker.UnitLogic.Abilities.Components.Base; using WOTR_PATH_OF_RAGE; using HarmonyLib; using Kingmaker.Blueprints.JsonSystem; using Kingmaker.Blueprints.Classes; using Kingmaker.UnitLogic.FactLogic; using Kingmaker.Localization; using UnityEngine; using static Kingmaker.Visual.Animation.Kingmaker.Actions.UnitAnimationActionCastSpell; using Kingmaker.UnitLogic.Abilities.Components; using Kingmaker.UnitLogic.Mechanics.Components; using Kingmaker.UnitLogic.Mechanics.Actions; using Kingmaker.RuleSystem.Rules.Damage; using Kingmaker.Enums.Damage; using Kingmaker.UnitLogic.Mechanics; using Kingmaker.RuleSystem; using Kingmaker.Enums; using Kingmaker.ElementsSystem; using Kingmaker.Designers.EventConditionActionSystem.Actions; using Kingmaker.UnitLogic.Mechanics.Conditions; using WOTR_PATH_OF_RAGE.New_Rules; using Kingmaker.Blueprints.Classes.Selection; using Kingmaker.Blueprints.Items.Weapons; using Kingmaker.Designers.EventConditionActionSystem.Evaluators; using Kingmaker.Designers.Mechanics.Facts; using Kingmaker.UnitLogic.Abilities.Components.CasterCheckers; using Kingmaker.Blueprints.Classes.Spells; using Kingmaker.UnitLogic.Buffs.Blueprints; using WOTR_PATH_OF_RAGE.MechanicsChanges; using BlueprintCore.Utils; namespace WOTR_PATH_OF_RAGE.NewFeatures { class DemonBlast { public static void AddDemonBlast() { var demonChargeMainAbility = BlueprintTool.Get<BlueprintAbility>("1b677ed598d47a048a0f6b4b671b8f84"); var demonBlastGuid = new BlueprintGuid(new Guid("6fc3b519-1853-4144-9e4a-4fd803b34d35")); var demonBlast = Helpers.CreateCopy(demonChargeMainAbility, bp => { bp.AssetGuid = demonBlastGuid; bp.m_Icon = AssetLoader.LoadInternal("Abilities", "DemonBlast.png"); bp.Range = AbilityRange.Personal; bp.CanTargetSelf = true; bp.name = "Demon Blast"; }); demonBlast.m_DisplayName = Helpers.CreateString(demonBlast + ".Name", "Demonic Blast"); demonBlast.LocalizedSavingThrow = Helpers.CreateString(demonBlast + ".SavingThrow", "None"); var demonSoulDescription = "As a {g|Encyclopedia:Move_Action}move action{/g}, you can let loose an explosion, dealing {g|Encyclopedia:Dice}2d6{/g} unholy {g|Encyclopedia:Damage}damage{/g} " + "per mythic rank to all enemies in a 10 feet range.\n An enemy can only be damaged by this ability or Demonic Charge once per {g|Encyclopedia:Combat_Round}round{/g}."; demonBlast.m_Description = Helpers.CreateString(demonBlast + ".Description", demonSoulDescription); demonBlast.RemoveComponents<AbilityCustomTeleportation>(); Helpers.AddBlueprint(demonBlast, demonBlastGuid); Main.Log("Demon Blast Added"); var demonBlastFeatureGuid = new BlueprintGuid(new Guid("6cf0d55c-050c-497a-8b98-e245435ce6aa")); var demonBlastFeature = Helpers.Create<BlueprintFeature>(c => { c.AssetGuid = demonBlastFeatureGuid; c.m_DisplayName = demonBlast.m_DisplayName; c.m_Description = demonBlast.m_Description; c.m_Icon = demonBlast.m_Icon; c.Ranks = 1; c.IsClassFeature = true; c.ReapplyOnLevelUp = true; c.HideInCharacterSheetAndLevelUp = true; c.m_DescriptionShort = new LocalizedString(); c.Groups = new FeatureGroup[] { }; c.name = "Demon Blast"; }); demonBlastFeature.AddComponent<AddFacts>(c => { c.m_Facts = new BlueprintUnitFactReference[]{ demonBlast.ToReference<BlueprintUnitFactReference>() }; }); Helpers.AddBlueprint(demonBlastFeature, demonBlastFeatureGuid); Main.Log("Demon Blast Feature Created" + demonBlastFeatureGuid); if (Main.settings.AddDemonBlast == false) { return; } var demonProgression = BlueprintTool.Get<BlueprintProgression>("285fe49f7df8587468f676aa49362213"); demonProgression.LevelEntries[0].m_Features.Add(demonBlastFeature.ToReference<BlueprintFeatureBaseReference>()); Main.Log("Demon Blast Added To Mythic"); } } }
41.225225
203
0.692089
[ "MIT" ]
bje259/WOTR_PATH_OF_RAGE
NewFeatures/DemonBlast.cs
4,578
C#
using System; using System.Text; using System.Text.RegularExpressions; namespace Moralis.WebGL.Platform.Services.ClientServices { public static class CommandRunnerExtensions { public static string AdjustJsonForParseDate(this string json) { string adjusted = json; Regex r = new Regex("{\"__type\":\"Date\",\"iso\":(\"\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z)\")}"); MatchCollection matches = r.Matches(json); // Use foreach-loop. foreach (Match match in matches) { if (match.Groups.Count >= 2) { adjusted = adjusted.Replace(match.Groups[0].Value, match.Groups[1].Value); } } return adjusted; } public static string JsonInsertParseDate(this string json) { string adjusted = json; Regex r = new Regex("(\"\\d{4}-[01]\\d-[0-3]\\dT[0-2]\\d:[0-5]\\d:[0-5]\\d\\.\\d+([+-][0-2]\\d:[0-5]\\d|Z)\")"); MatchCollection matches = r.Matches(json); // Use foreach-loop. foreach (Match match in matches) { if (match.Groups.Count >= 1) { StringBuilder sb = new StringBuilder(); sb.Append("{\"__type\":\"Date\",\"iso\":"); sb.Append(match.Groups[0].Value); sb.Append("}"); adjusted = adjusted.Replace(match.Groups[0].Value, sb.ToString()); } } return adjusted; } } }
31.296296
154
0.467456
[ "MIT" ]
AllTrueVision/ethereum-unity-boilerplate
Assets/MoralisWeb3ApiSdk/Moralis/Moralis.WebGL/MoralisDotNet/Platform/Services/ClientServices/CommandRunnerExtensions.cs
1,692
C#
// Copyright (c) Microsoft. All Rights Reserved. Licensed under the Apache License, Version 2.0. See License.txt in the project root for license information. using System; using System.Runtime.InteropServices; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.Navigation; using Microsoft.CodeAnalysis.Text; using Microsoft.VisualStudio.Shell.Interop; namespace Microsoft.VisualStudio.LanguageServices.Implementation.Library.FindResults { [Guid(Guids.RoslynLibraryIdString)] internal partial class LibraryManager : AbstractLibraryManager { private readonly Workspace _workspace; public LibraryManager(Workspace workspace, IServiceProvider serviceProvider) : base(Guids.RoslynLibraryId, serviceProvider) { _workspace = workspace; } public override uint GetLibraryFlags() { return (uint)_LIB_FLAGS2.LF_SUPPORTSLISTREFERENCES; } protected override IVsSimpleObjectList2 GetList(uint listType, uint flags, VSOBSEARCHCRITERIA2[] pobSrch) { switch (listType) { case (uint)_LIB_LISTTYPE.LLT_HIERARCHY: if (IsSymbolObjectList((_LIB_LISTFLAGS)flags, pobSrch)) { return ((NavInfo)pobSrch[0].pIVsNavInfo).CreateObjectList(); } break; } return null; } private bool IsSymbolObjectList(_LIB_LISTFLAGS flags, VSOBSEARCHCRITERIA2[] pobSrch) { return (flags & _LIB_LISTFLAGS.LLF_USESEARCHFILTER) != 0 && pobSrch != null && pobSrch.Length == 1 && (pobSrch[0].grfOptions & (uint)_VSOBSEARCHOPTIONS2.VSOBSO_LISTREFERENCES) != 0 && pobSrch[0].pIVsNavInfo is NavInfo; } protected override uint GetSupportedCategoryFields(uint category) { switch (category) { case (uint)LIB_CATEGORY.LC_LISTTYPE: return (uint)_LIB_LISTTYPE.LLT_HIERARCHY; } return 0; } protected override uint GetUpdateCounter() { return 0; } private void PresentObjectList(string title, ObjectList objectList) { if (string.IsNullOrWhiteSpace(title)) { title = "None"; } var navInfo = new NavInfo(objectList); var findSymbol = (IVsFindSymbol)this.ServiceProvider.GetService(typeof(SVsObjectSearch)); var searchCriteria = new VSOBSEARCHCRITERIA2() { dwCustom = 0, eSrchType = VSOBSEARCHTYPE.SO_ENTIREWORD, grfOptions = (uint)_VSOBSEARCHOPTIONS2.VSOBSO_LISTREFERENCES | (uint)_VSOBSEARCHOPTIONS.VSOBSO_CASESENSITIVE, pIVsNavInfo = navInfo, szName = title, }; var criteria = new[] { searchCriteria }; var hresult = findSymbol.DoSearch(Guids.RoslynLibraryId, criteria); ErrorHandler.ThrowOnFailure(hresult); } private bool IsValidSourceLocation(Location location, Solution solution) { if (!location.IsInSource) { return false; } var document = solution.GetDocument(location.SourceTree); return IsValidSourceLocation(document, location.SourceSpan); } private bool IsValidSourceLocation(Document document, TextSpan sourceSpan) { if (document == null) { return false; } var solution = document.Project.Solution; var documentNavigationService = solution.Workspace.Services.GetService<IDocumentNavigationService>(); return documentNavigationService.CanNavigateToSpan(solution.Workspace, document.Id, sourceSpan); } } }
33.957627
161
0.599451
[ "Apache-2.0" ]
amcasey/roslyn
src/VisualStudio/Core/Def/Implementation/Library/FindResults/LibraryManager.cs
4,009
C#
using Autofac.Extensions.DependencyInjection; namespace Xunit.DependencyInjection.Test; public class HostTest { private readonly IHostingEnvironment _environment; private readonly IServiceProvider _provider; public HostTest(IHostingEnvironment environment, IServiceProvider provider) { _environment = environment; _provider = provider; } [Fact] public void ApplicationNameTest() => Assert.Equal(typeof(HostTest).Assembly.GetName().Name, _environment.ApplicationName); [Fact] public void IsAutofac() => Assert.IsType<AutofacServiceProvider>(_provider); }
27.818182
126
0.753268
[ "MIT" ]
libaowei/Xunit.DependencyInjection
Xunit.DependencyInjection.Test/HostTest.cs
614
C#
using CleanArchitecture.Application.Common.Exceptions; using CleanArchitecture.Application.Common.Interfaces; using CleanArchitecture.Domain.Entities; using MediatR; using System.Threading; using System.Threading.Tasks; namespace CleanArchitecture.Application.TodoLists.Commands.UpdateTodoList { public class UpdateTodoListCommand : IRequest { public int Id { get; set; } public string Title { get; set; } } public class UpdateTodoListCommandHandler : IRequestHandler<UpdateTodoListCommand> { private readonly IApplicationDbContext _context; public UpdateTodoListCommandHandler(IApplicationDbContext context) { _context = context; } public async Task<Unit> Handle(UpdateTodoListCommand request, CancellationToken cancellationToken) { //var entity = await _context.TodoLists.FindAsync(request.Id); //if (entity == null) //{ // throw new NotFoundException(nameof(TodoList), request.Id); //} //entity.Title = request.Title; //await _context.SaveChangesAsync(cancellationToken); return Unit.Value; } } }
28.302326
106
0.66968
[ "MIT" ]
ElderJames/CleanArchitecture
src/Application/TodoLists/Commands/UpdateTodoList/UpdateTodoListCommand.cs
1,219
C#
using BizHawk.Common; using BizHawk.BizInvoke; using BizHawk.Emulation.Common; using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices; using System.Threading; namespace BizHawk.Emulation.Cores.Waterbox { public class WaterboxOptions { // string directory, string filename, ulong heapsize, ulong sealedheapsize, ulong invisibleheapsize /// <summary> /// path which the main executable and all associated libraries should be found /// </summary> public string Path { get; set; } /// <summary> /// filename of the main executable; expected to be in Path /// </summary> public string Filename { get; set; } /// <summary> /// how large the normal heap should be. it services sbrk calls /// can be 0, but sbrk calls will crash. /// </summary> public uint SbrkHeapSizeKB { get; set; } /// <summary> /// how large the sealed heap should be. it services special allocations that become readonly after init /// Must be > 0 and at least large enough to store argv and envp, and any alloc_sealed() calls /// </summary> public uint SealedHeapSizeKB { get; set; } /// <summary> /// how large the invisible heap should be. it services special allocations which are not savestated /// Must be > 0 and at least large enough for the internal vtables, and any alloc_invisible() calls /// </summary> public uint InvisibleHeapSizeKB { get; set; } /// <summary> /// how large the "plain" heap should be. it is savestated, and contains /// Must be > 0 and at least large enough for the internal pthread structure, and any alloc_plain() calls /// </summary> public uint PlainHeapSizeKB { get; set; } /// <summary> /// how large the mmap heap should be. it is savestated. /// can be 0, but mmap calls will crash. /// </summary> public uint MmapHeapSizeKB { get; set; } /// <summary> /// start address in memory /// </summary> public ulong StartAddress { get; set; } = WaterboxHost.CanonicalStart; /// <summary> /// Skips the check that the wbx file and other associated dlls match from state save to state load. /// DO NOT SET THIS TO TRUE. A different executable most likely means different meanings for memory locations, /// and nothing will make sense. /// </summary> public bool SkipCoreConsistencyCheck { get; set; } = false; /// <summary> /// Skips the check that the initial memory state (after init, but before any running) matches from state save to state load. /// DO NOT SET THIS TO TRUE. The initial memory state must be the same for the XORed memory contents in the savestate to make sense. /// </summary> public bool SkipMemoryConsistencyCheck { get; set; } = false; } public class WaterboxHost : Swappable, IImportResolver, IBinaryStateable { static WaterboxHost() { if (OSTailoredCode.IsUnixHost) { WaterboxLibcoLinuxStartup.Setup(); } } /// <summary> /// usual starting point for the executable /// </summary> public const ulong CanonicalStart = 0x0000036f00000000; /// <summary> /// the next place where we can put a module or heap /// </summary> private ulong _nextStart = CanonicalStart; /// <summary> /// increment _nextStart after adding a module /// </summary> private void ComputeNextStart(ulong size) { _nextStart += size; // align to 1MB, then increment 16MB _nextStart = ((_nextStart - 1) | 0xfffff) + 0x1000001; } /// <summary> /// standard malloc() heap /// </summary> internal Heap _heap; /// <summary> /// sealed heap (writable only during init) /// </summary> internal Heap _sealedheap; /// <summary> /// invisible heap (not savestated, use with care) /// </summary> internal Heap _invisibleheap; /// <summary> /// extra savestated heap /// </summary> internal Heap _plainheap; /// <summary> /// memory map emulation /// </summary> internal MapHeap _mmapheap; /// <summary> /// the loaded elf file /// </summary> private ElfLoader _module; /// <summary> /// all loaded heaps /// </summary> private readonly List<Heap> _heaps = new List<Heap>(); /// <summary> /// anything at all that needs to be disposed on finish /// </summary> private readonly List<IDisposable> _disposeList = new List<IDisposable>(); /// <summary> /// anything at all that needs its state saved and loaded /// </summary> private readonly List<IBinaryStateable> _savestateComponents = new List<IBinaryStateable>(); private readonly EmuLibc _emu; private readonly Syscalls _syscalls; /// <summary> /// the set of functions made available for the elf module /// </summary> private readonly IImportResolver _imports; /// <summary> /// timestamp of creation acts as a sort of "object id" in the savestate /// </summary> private readonly long _createstamp = WaterboxUtils.Timestamp(); private Heap CreateHeapHelper(uint sizeKB, string name, bool saveStated) { if (sizeKB != 0) { var heap = new Heap(_nextStart, sizeKB * 1024, name); heap.Memory.Activate(); ComputeNextStart(sizeKB * 1024); AddMemoryBlock(heap.Memory, name); if (saveStated) _savestateComponents.Add(heap); _disposeList.Add(heap); _heaps.Add(heap); return heap; } else { return null; } } public WaterboxHost(WaterboxOptions opt) { _nextStart = opt.StartAddress; Initialize(_nextStart); using (this.EnterExit()) { _emu = new EmuLibc(this); _syscalls = new Syscalls(this); _imports = new PatchImportResolver( NotImplementedSyscalls.Instance, BizExvoker.GetExvoker(_emu, CallingConventionAdapters.Waterbox), BizExvoker.GetExvoker(_syscalls, CallingConventionAdapters.Waterbox) ); if (true) { var moduleName = opt.Filename; var path = Path.Combine(opt.Path, moduleName); var gzpath = path + ".gz"; byte[] data; if (File.Exists(gzpath)) { using var fs = new FileStream(gzpath, FileMode.Open, FileAccess.Read); data = Util.DecompressGzipFile(fs); } else { data = File.ReadAllBytes(path); } _module = new ElfLoader(moduleName, data, _nextStart, opt.SkipCoreConsistencyCheck, opt.SkipMemoryConsistencyCheck); ComputeNextStart(_module.Memory.Size); AddMemoryBlock(_module.Memory, moduleName); _savestateComponents.Add(_module); _disposeList.Add(_module); } ConnectAllImports(); // load all heaps _heap = CreateHeapHelper(opt.SbrkHeapSizeKB, "brk-heap", true); _sealedheap = CreateHeapHelper(opt.SealedHeapSizeKB, "sealed-heap", true); _invisibleheap = CreateHeapHelper(opt.InvisibleHeapSizeKB, "invisible-heap", false); _plainheap = CreateHeapHelper(opt.PlainHeapSizeKB, "plain-heap", true); if (opt.MmapHeapSizeKB != 0) { _mmapheap = new MapHeap(_nextStart, opt.MmapHeapSizeKB * 1024, "mmap-heap"); _mmapheap.Memory.Activate(); ComputeNextStart(opt.MmapHeapSizeKB * 1024); AddMemoryBlock(_mmapheap.Memory, "mmap-heap"); _savestateComponents.Add(_mmapheap); _disposeList.Add(_mmapheap); } // TODO: This debugger stuff doesn't work on nix? System.Diagnostics.Debug.WriteLine($"About to enter unmanaged code for {opt.Filename}"); if (OSTailoredCode.IsUnixHost) { if (System.Diagnostics.Debugger.IsAttached) System.Diagnostics.Debugger.Break(); } else { if (!System.Diagnostics.Debugger.IsAttached && Win32Imports.IsDebuggerPresent()) { // this means that GDB or another unconventional debugger is attached. // if that's the case, and it's observing this core, it probably wants a break System.Diagnostics.Debugger.Break(); } } _module.RunNativeInit(); } } public IntPtr GetProcAddrOrZero(string entryPoint) { var addr = _module.GetProcAddrOrZero(entryPoint); if (addr != IntPtr.Zero) { var exclude = _imports.GetProcAddrOrZero(entryPoint); if (exclude != IntPtr.Zero) { // don't reexport anything that's part of waterbox internals return IntPtr.Zero; } } return addr; } public IntPtr GetProcAddrOrThrow(string entryPoint) { var addr = _module.GetProcAddrOrZero(entryPoint); if (addr != IntPtr.Zero) { var exclude = _imports.GetProcAddrOrZero(entryPoint); if (exclude != IntPtr.Zero) { // don't reexport anything that's part of waterbox internals throw new InvalidOperationException($"Tried to resolve {entryPoint}, but it should not be exported"); } else { return addr; } } else { throw new InvalidOperationException($"{entryPoint} was not exported from elf"); } } public void Seal() { using (this.EnterExit()) { // if libco is used, the jmp_buf for the main cothread can have stack stuff in it. // this isn't a problem, since we only savestate when the core is not running, and // the next time it's run, that buf will be overridden again. // but it breaks xor state verification, so when we seal, nuke it. // this could be the responsibility of something else other than the PeRunner; I am not sure yet... // TODO: MAKE SURE THIS STILL WORKS IntPtr co_clean; if ((co_clean = _module.GetProcAddrOrZero("co_clean")) != IntPtr.Zero) { Console.WriteLine("Calling co_clean()."); CallingConventionAdapters.Waterbox.GetDelegateForFunctionPointer<Action>(co_clean)(); } _sealedheap.Seal(); foreach (var h in _heaps) { if (h != _invisibleheap && h != _sealedheap) // TODO: if we have more non-savestated heaps, refine this hack h.Memory.Seal(); } _module.SealImportsAndTakeXorSnapshot(); _mmapheap?.Memory.Seal(); } Console.WriteLine("WaterboxHost Sealed!"); } private void ConnectAllImports() { _module.ConnectSyscalls(_imports); } /// <summary> /// Adds a file that will appear to the waterbox core's libc. the file will be read only. /// All savestates must have the same file list, so either leave it up forever or remove it during init! /// </summary> /// <param name="name">the filename that the unmanaged core will access the file by</param> public void AddReadonlyFile(byte[] data, string name) { _syscalls.AddReadonlyFile((byte[])data.Clone(), name); } /// <summary> /// Remove a file previously added by AddReadonlyFile. Frees the internal copy of the filedata, saving memory. /// All savestates must have the same file list, so either leave it up forever or remove it during init! /// </summary> public void RemoveReadonlyFile(string name) { _syscalls.RemoveReadonlyFile(name); } /// <summary> /// Add a transient file that will appear to the waterbox core's libc. The file will be readable /// and writable. Any attempt to save state while the file is loaded will fail. /// </summary> public void AddTransientFile(byte[] data, string name) { _syscalls.AddTransientFile(data, name); // don't need to clone data, as it's used at init only } /// <summary> /// Remove a file previously added by AddTransientFile /// </summary> /// <returns>The state of the file when it was removed</returns> public byte[] RemoveTransientFile(string name) { return _syscalls.RemoveTransientFile(name); } /// <summary> /// Can be set by the frontend and will be called if the core attempts to open a missing file. /// The callee may add additional files to the waterbox during the callback and return `true` to indicate /// that the right file was added and the scan should be rerun. The callee may return `false` to indicate /// that the file should be reported as missing. Do not call other things during this callback. /// Can be called at any time by the core, so you may want to remove your callback entirely after init /// if it was for firmware only. /// </summary> public Func<string, bool> MissingFileCallback { get => _syscalls.MissingFileCallback; set => _syscalls.MissingFileCallback = value; } private const ulong MAGIC = 0x736b776162727477; private const ulong WATERBOXSTATEVERSION = 2; public void SaveStateBinary(BinaryWriter bw) { bw.Write(MAGIC); bw.Write(WATERBOXSTATEVERSION); bw.Write(_createstamp); bw.Write(_savestateComponents.Count); using (this.EnterExit()) { foreach (var c in _savestateComponents) { c.SaveStateBinary(bw); } } } public void LoadStateBinary(BinaryReader br) { if (br.ReadUInt64() != MAGIC) throw new InvalidOperationException("Internal savestate error"); if (br.ReadUInt64() != WATERBOXSTATEVERSION) throw new InvalidOperationException("Waterbox savestate version mismatch"); var differentCore = br.ReadInt64() != _createstamp; // true if a different core instance created the state if (br.ReadInt32() != _savestateComponents.Count) throw new InvalidOperationException("Internal savestate error"); using (this.EnterExit()) { foreach (var c in _savestateComponents) { c.LoadStateBinary(br); } if (differentCore) { // if a different runtime instance than this one saved the state, // Exvoker imports need to be reconnected Console.WriteLine($"Restoring {nameof(WaterboxHost)} state from a different core..."); ConnectAllImports(); } } } protected override void Dispose(bool disposing) { base.Dispose(disposing); if (disposing) { foreach (var d in _disposeList) d.Dispose(); _disposeList.Clear(); PurgeMemoryBlocks(); _module = null; _heap = null; _sealedheap = null; _invisibleheap = null; _plainheap = null; _mmapheap = null; } } } internal static class WaterboxLibcoLinuxStartup { // TODO: This is a giant mess and get rid of it entirely internal static void Setup() { // Our libco implementation plays around with stuff in the TEB block. This is bad for a few reasons: // 1. It's windows specific // 2. It's only doing this to satisfy some msvs __stkchk code that should never run // 3. That code is only running because memory allocations in a cothread still send you back // to managed land where things like the .NET jit might run on the costack, oof. // We need to stop #3 from happening, probably by making the waterboxhost unmanaged code. Then if we // still need "GS fiddling" we can have it be part of our syscall layer without having a managed transition // Until then, just fake a TEB block for linux -- nothing else uses GS anyway. var ptr = Marshal.AllocHGlobal(0x40); WaterboxUtils.ZeroMemory(ptr, 0x40); Marshal.WriteIntPtr(ptr, 0x30, ptr); if (ArchPrCtl(0x1001 /* SET_GS */, Z.SU((long)ptr)) != 0) throw new InvalidOperationException("ArchPrCtl failed!"); } [DllImport("libc.so.6", EntryPoint = "arch_prctl")] private static extern int ArchPrCtl(int code, UIntPtr addr); } }
32.680761
136
0.66561
[ "MIT" ]
diddily/BizHawk
src/BizHawk.Emulation.Cores/Waterbox/WaterboxHost.cs
15,460
C#
using System; using System.CodeDom.Compiler; using System.ComponentModel; using System.Diagnostics; using System.Runtime.CompilerServices; using System.Xml.Schema; using System.Xml.Serialization; namespace Workday.HumanResources { [GeneratedCode("System.Xml", "4.6.1590.0"), DesignerCategory("code"), DebuggerStepThrough, XmlType(Namespace = "urn:com.workday/bsvc")] [Serializable] public class Passports_and_Visas_Identification_DataType : INotifyPropertyChanged { private Passport_IDType[] passport_IDField; private Visa_IDType[] visa_IDField; private bool replace_AllField; private bool replace_AllFieldSpecified; [method: CompilerGenerated] [CompilerGenerated] public event PropertyChangedEventHandler PropertyChanged; [XmlElement("Passport_ID", Order = 0)] public Passport_IDType[] Passport_ID { get { return this.passport_IDField; } set { this.passport_IDField = value; this.RaisePropertyChanged("Passport_ID"); } } [XmlElement("Visa_ID", Order = 1)] public Visa_IDType[] Visa_ID { get { return this.visa_IDField; } set { this.visa_IDField = value; this.RaisePropertyChanged("Visa_ID"); } } [XmlAttribute(Form = XmlSchemaForm.Qualified)] public bool Replace_All { get { return this.replace_AllField; } set { this.replace_AllField = value; this.RaisePropertyChanged("Replace_All"); } } [XmlIgnore] public bool Replace_AllSpecified { get { return this.replace_AllFieldSpecified; } set { this.replace_AllFieldSpecified = value; this.RaisePropertyChanged("Replace_AllSpecified"); } } protected void RaisePropertyChanged(string propertyName) { PropertyChangedEventHandler propertyChanged = this.PropertyChanged; if (propertyChanged != null) { propertyChanged(this, new PropertyChangedEventArgs(propertyName)); } } } }
20.666667
136
0.721124
[ "MIT" ]
matteofabbri/Workday.WebServices
Workday.HumanResources/Passports_and_Visas_Identification_DataType.cs
1,922
C#
using System.Web; using System.Web.Mvc; namespace TableList.Example.Mvc { public class FilterConfig { public static void RegisterGlobalFilters(GlobalFilterCollection filters) { filters.Add(new HandleErrorAttribute()); } } }
19.571429
80
0.660584
[ "MIT" ]
Hasmik7/TableList
examples/TableList.Example.Mvc/App_Start/FilterConfig.cs
276
C#
using MTProto.NET.Schema.Layer72; using System; using System.Collections.Generic; using System.Text; using System.Threading.Tasks; namespace MTProto.NET.Server.Infrastructure { public interface IChatManager { /// <summary> /// Gets user's chats. /// </summary> /// <param name="userId"></param> /// <param name="offset"></param> /// <param name="count"></param> /// <returns></returns> Task<IEnumerable<IChat>> GetUserChats(int userId, int offset = 0, int count = 30); /// <summary> /// Gets a messages of a private chat. /// </summary> /// <param name="fromUserId"></param> /// <param name="userPeerId"></param> /// <returns></returns> Task<IEnumerable<IMessage>> GetPrivateChatMessages(int fromUserId, int userPeerId); /// <summary> /// Registers a message in a private chat. /// </summary> /// <param name="fromUserId"></param> /// <param name="toUserPeerId"></param> /// <returns></returns> Task<IMessage> SendPrivateChatMessage(int fromUserId,int peerUserId,TLSendMessage message); } }
27.473684
93
0.66954
[ "MIT" ]
Gostareh-Negar/TeleNet
MTProto.Net.Server/Infrastructure/IChatManager.cs
1,046
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. See License.txt in the project root for license information. // Code generated by Microsoft (R) AutoRest Code Generator. // Changes may cause incorrect behavior and will be lost if the code is regenerated. namespace Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support { /// <summary>Describes operator to be matched</summary> public partial struct RemoteAddressOperator : System.IEquatable<RemoteAddressOperator> { public static Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.RemoteAddressOperator Any = @"Any"; public static Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.RemoteAddressOperator GeoMatch = @"GeoMatch"; public static Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.RemoteAddressOperator IPMatch = @"IPMatch"; /// <summary>the value for an instance of the <see cref="RemoteAddressOperator" /> Enum.</summary> private string _value { get; set; } /// <summary>Conversion from arbitrary object to RemoteAddressOperator</summary> /// <param name="value">the value to convert to an instance of <see cref="RemoteAddressOperator" />.</param> internal static object CreateFrom(object value) { return new RemoteAddressOperator(global::System.Convert.ToString(value)); } /// <summary>Compares values of enum type RemoteAddressOperator</summary> /// <param name="e">the value to compare against this instance.</param> /// <returns><c>true</c> if the two instances are equal to the same value</returns> public bool Equals(Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.RemoteAddressOperator e) { return _value.Equals(e._value); } /// <summary>Compares values of enum type RemoteAddressOperator (override for Object)</summary> /// <param name="obj">the value to compare against this instance.</param> /// <returns><c>true</c> if the two instances are equal to the same value</returns> public override bool Equals(object obj) { return obj is RemoteAddressOperator && Equals((RemoteAddressOperator)obj); } /// <summary>Returns hashCode for enum RemoteAddressOperator</summary> /// <returns>The hashCode of the value</returns> public override int GetHashCode() { return this._value.GetHashCode(); } /// <summary>Creates an instance of the <see cref="RemoteAddressOperator"/> Enum class.</summary> /// <param name="underlyingValue">the value to create an instance for.</param> private RemoteAddressOperator(string underlyingValue) { this._value = underlyingValue; } /// <summary>Returns string representation for RemoteAddressOperator</summary> /// <returns>A string for this value.</returns> public override string ToString() { return this._value; } /// <summary>Implicit operator to convert string to RemoteAddressOperator</summary> /// <param name="value">the value to convert to an instance of <see cref="RemoteAddressOperator" />.</param> public static implicit operator RemoteAddressOperator(string value) { return new RemoteAddressOperator(value); } /// <summary>Implicit operator to convert RemoteAddressOperator to string</summary> /// <param name="e">the value to convert to an instance of <see cref="RemoteAddressOperator" />.</param> public static implicit operator string(Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.RemoteAddressOperator e) { return e._value; } /// <summary>Overriding != operator for enum RemoteAddressOperator</summary> /// <param name="e1">the value to compare against <paramref name="e2" /></param> /// <param name="e2">the value to compare against <paramref name="e1" /></param> /// <returns><c>true</c> if the two instances are not equal to the same value</returns> public static bool operator !=(Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.RemoteAddressOperator e1, Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.RemoteAddressOperator e2) { return !e2.Equals(e1); } /// <summary>Overriding == operator for enum RemoteAddressOperator</summary> /// <param name="e1">the value to compare against <paramref name="e2" /></param> /// <param name="e2">the value to compare against <paramref name="e1" /></param> /// <returns><c>true</c> if the two instances are equal to the same value</returns> public static bool operator ==(Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.RemoteAddressOperator e1, Microsoft.Azure.PowerShell.Cmdlets.Cdn.Support.RemoteAddressOperator e2) { return e2.Equals(e1); } } }
50.74
185
0.658849
[ "MIT" ]
AlanFlorance/azure-powershell
src/Cdn/generated/api/Support/RemoteAddressOperator.cs
4,975
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // This file is used by Code Analysis to maintain SuppressMessage // attributes that are applied to this project. // Project-level suppressions either have no target or are given // a specific target and scoped to a namespace, type, member, etc. using System.Diagnostics.CodeAnalysis; [assembly: SuppressMessage("Usage", "AZC0001:Use one of the following pre-approved namespace groups (https://azure.github.io/azure-sdk/registered_namespaces.html): Azure.AI, Azure.Analytics, Azure.Communication, Azure.Data, Azure.DigitalTwins, Azure.Iot, Azure.Learn, Azure.Media, Azure.Management, Azure.Messaging, Azure.Search, Azure.Security, Azure.Storage, Azure.Template, Azure.Identity, Microsoft.Extensions.Azure", Justification = "<Pending>", Scope = "namespace", Target = "~N:Azure.IoT.Hub.Service.Authentication")] [assembly: SuppressMessage("Usage", "AZC0001:Use one of the following pre-approved namespace groups (https://azure.github.io/azure-sdk/registered_namespaces.html): Azure.AI, Azure.Analytics, Azure.Communication, Azure.Data, Azure.DigitalTwins, Azure.Iot, Azure.Learn, Azure.Media, Azure.Management, Azure.Messaging, Azure.Search, Azure.Security, Azure.Storage, Azure.Template, Azure.Identity, Microsoft.Extensions.Azure", Justification = "<Pending>", Scope = "namespace", Target = "~N:Azure.IoT.Hub.Service")] [assembly: SuppressMessage("Usage", "AZC0001:Use one of the following pre-approved namespace groups (https://azure.github.io/azure-sdk/registered_namespaces.html): Azure.AI, Azure.Analytics, Azure.Communication, Azure.Data, Azure.DigitalTwins, Azure.Iot, Azure.Learn, Azure.Media, Azure.Management, Azure.Messaging, Azure.Search, Azure.Security, Azure.Storage, Azure.Template, Azure.Identity, Microsoft.Extensions.Azure", Justification = "<Pending>", Scope = "namespace", Target = "~N:Azure.IoT.Hub.Service.Models")]
138.357143
524
0.782137
[ "MIT" ]
93mishra/azure-sdk-for-net
sdk/iot/Azure.IoT.Hub.Service/src/GlobalSuppressions.cs
1,939
C#
using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Toolkit.UI; using Esri.ArcGISRuntime.UI.Controls; using System; using System.ComponentModel; using System.Linq; using System.Windows; using System.Windows.Controls; namespace Esri.ArcGISRuntime.Toolkit.Samples.BasemapGallery { [SampleInfoAttribute(Category = "BasemapGallery", DisplayName = "BasemapGallery - Behavior", Description = "Sample showing behaviors")] public partial class BasemapGalleryBehaviorSample : UserControl, INotifyPropertyChanged { private GeoView _selectedGeoView; private MapView _mapView = new MapView(); private SceneView _sceneView = new SceneView(); public event PropertyChangedEventHandler PropertyChanged; public GeoView SelectedGeoView { get => _selectedGeoView; set { if (_selectedGeoView != value) { _selectedGeoView = value; PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(nameof(SelectedGeoView))); if (_selectedGeoView is MapView mv) { Gallery.GeoModel = mv.Map; } else if (_selectedGeoView is SceneView sv) { Gallery.GeoModel = sv.Scene; } else { Gallery.GeoModel = null; } } } } public BasemapGalleryBehaviorSample() { InitializeComponent(); this.DataContext = this; _mapView.Map = new Map(BasemapStyle.ArcGISImagery); _sceneView.Scene = new Scene(BasemapStyle.ArcGISImageryStandard); ViewStyleCombobox.Items.Add("List"); ViewStyleCombobox.Items.Add("Grid"); ViewStyleCombobox.SelectedIndex = 0; } private void ViewStyleCombobox_SelectionChanged(object sender, SelectionChangedEventArgs e) { switch (ViewStyleCombobox.SelectedIndex) { case 0: Gallery.GalleryViewStyle = BasemapGalleryViewStyle.List; break; case 1: Gallery.GalleryViewStyle = BasemapGalleryViewStyle.Grid; break; } } private async void Button_Load_Portal(object sender, RoutedEventArgs e) { try { Gallery.Portal = await Portal.ArcGISPortal.CreateAsync(new Uri("https://arcgisruntime.maps.arcgis.com/")); } catch (Exception) { } } private async void Button_Load_AGOL(object sender, RoutedEventArgs e) { try { Gallery.Portal = await Portal.ArcGISPortal.CreateAsync(); } catch (Exception) { } } private void Button_Switch_To_Map(object sender, RoutedEventArgs e) { SelectedGeoView = _mapView; } private void Button_Switch_To_Scene(object sender, RoutedEventArgs e) { SelectedGeoView = _sceneView; } private void Button_Disconect_View(object sender, RoutedEventArgs e) { SelectedGeoView = null; } private async void Button_Add_Last(object sender, RoutedEventArgs e) { BasemapGalleryItem item = await BasemapGalleryItem.CreateAsync(new Basemap()); item.Name = "With Thumbnail"; item.Tooltip = Guid.NewGuid().ToString(); item.Thumbnail = new ArcGISRuntime.UI.RuntimeImage(new Uri("https://www.esri.com/content/dam/esrisites/en-us/home/homepage-tile-arcgis-collaboration.jpg")); Gallery.AvailableBasemaps.Add(item); BasemapGalleryItem item2 = await BasemapGalleryItem.CreateAsync(new Basemap()); item2.Name = "Without Thumbnail"; Gallery.AvailableBasemaps.Add(item2); } private void Button_Remove_Last(object sender, RoutedEventArgs e) { if (Gallery.AvailableBasemaps.Any()) { Gallery.AvailableBasemaps.Remove(Gallery.AvailableBasemaps.Last()); } } private void Gallery_BasemapSelected(object sender, BasemapGalleryItem e) { LastSelectedDateLabel.Content = DateTime.Now.ToLongTimeString(); } } }
34.270677
168
0.576569
[ "Apache-2.0" ]
Esri/arcgis-toolkit-dotnet
src/Samples/Toolkit.SampleApp.WPF_Net5/Samples/BasemapGallery/BasemapGalleryBehaviorSample.xaml.cs
4,560
C#
namespace Craiel.UnityGameData.Editor.Window { using System.Collections.Generic; using System.Linq; using Common; using GameData.Editor.Events; using UnityEditor; using UnityEditor.IMGUI.Controls; using UnityEngine; using UnityEssentials.Editor.UserInterface; using UnityEssentials.Runtime.Collections; using UnityEssentials.Runtime.Event.Editor; using UnityEssentials.Runtime.Utils; public class GameDataTreeContentPresenter : TreeView, IGameDataContentPresenter { private const float MinWidth = 200; private const float MaxWidth = 600; private readonly SearchField searchField; private readonly ExtendedDictionary<int, GameDataObject> idObjectMap; private readonly IList<int> selection; private readonly IList<TreeViewItem> treeViewEntryTempList; private readonly IList<GameDataObject> entryTempList; private TreeViewItem root; private int nextEntryId; private Vector2 scrollPos; private float treeViewWidth = MinWidth + 100; private SerializedObject copyObject; private GameDataEditorContent activeContent; private Editor currentEditor; private bool createOnNextRepaint; private bool isSplitterDragging; private GUIStyle toolBarStyle; // ------------------------------------------------------------------- // Constructor // ------------------------------------------------------------------- public GameDataTreeContentPresenter() : base(new TreeViewState()) { this.searchField = new SearchField(); this.selection = new List<int>(); this.idObjectMap = new ExtendedDictionary<int, GameDataObject> {EnableReverseLookup = true}; this.treeViewEntryTempList = new List<TreeViewItem>(); this.entryTempList = new List<GameDataObject>(); this.showAlternatingRowBackgrounds = true; } // ------------------------------------------------------------------- // Public // ------------------------------------------------------------------- public void Draw(Rect drawArea, GameDataEditorContent content) { if (this.toolBarStyle == null) { this.toolBarStyle = new GUIStyle(GameDataEditorWindow.Instance.ToolBarStyle) { fixedWidth = 32, fixedHeight = 32 }; } Rect splitterRect; if (this.activeContent != content) { this.activeContent = content; this.Reload(); this.RebuildEditor(); } if (this.createOnNextRepaint) { this.createOnNextRepaint = false; this.OpenCreateItemDialog(content); } EditorGUILayout.BeginHorizontal(); { // Left EditorGUILayout.BeginVertical("box", GUILayout.Width(this.treeViewWidth), GUILayout.ExpandHeight(true)); { GUILayout.Space(5); this.DrawToolBar(content); GUILayout.Space(5); this.searchString = this.searchField.OnGUI(this.searchString); GUILayout.Space(5); var rect = GUILayoutUtility.GetRect(this.treeViewWidth, this.treeViewWidth, 0, 100000); this.OnGUI(rect); } EditorGUILayout.EndVertical(); GUILayout.Box ("", GUILayout.Width(2), GUILayout.MaxWidth (2), GUILayout.MinWidth(2), GUILayout.ExpandHeight(true)); splitterRect = GUILayoutUtility.GetLastRect (); EditorGUIUtility.AddCursorRect(splitterRect, MouseCursor.ResizeHorizontal); // Right EditorGUILayout.BeginVertical("box"); { this.scrollPos = EditorGUILayout.BeginScrollView(this.scrollPos); if (this.currentEditor != null) { Layout.SetExtendedLabelSize(); EditorGUI.BeginChangeCheck(); this.currentEditor.OnInspectorGUI(); Layout.SetDefaultLabelSize(); } EditorGUILayout.EndScrollView(); } EditorGUILayout.EndVertical(); } EditorGUILayout.EndHorizontal(); this.HandleSplitter(splitterRect); } public bool ProcessEvent(Event eventData) { switch (eventData.type) { case EventType.KeyUp: { return this.ProcessEventKeyUp(eventData.keyCode); } default: { return false; } } } // ------------------------------------------------------------------- // Protected // ------------------------------------------------------------------- protected override TreeViewItem BuildRoot() { this.nextEntryId = 0; this.root = new TreeViewItem { id = 0, depth = -1, displayName = "Root" }; this.idObjectMap.Clear(); if (this.activeContent != null) { this.treeViewEntryTempList.Clear(); var orderedEntries = this.activeContent.Entries.OrderBy(x => x.Deprecated ? "XX - " + x.Name : x.Name); foreach (GameDataObject entry in orderedEntries) { var item = new TreeViewItem(this.nextEntryId++, -1, entry.Name); if (entry.Deprecated) { item.displayName = "XX - " + item.displayName; var icon = GameDataHelpers.GetIcon("Deprecated"); if (icon != null) { item.icon = icon; } } else { if (entry.IconSmall != null && entry.IconSmall.IsValid()) { item.icon = ((Sprite) entry.IconSmall.Resource).texture; } else { item.icon = GameDataHelpers.GetIconForBaseType(entry.GetType()); } } this.idObjectMap.Add(item.id, entry); this.treeViewEntryTempList.Add(item); } SetupParentsAndChildrenFromDepths(this.root, this.treeViewEntryTempList); this.treeViewEntryTempList.Clear(); } this.ResetSelection(); return this.root; } protected override void SelectionChanged(IList<int> selectedIds) { this.selection.Clear(); foreach (var index in selectedIds) { this.selection.Add(index); } this.SendSelectedEvent(); this.RebuildEditor(); } // ------------------------------------------------------------------- // Private // ------------------------------------------------------------------- private void HandleSplitter(Rect splitterRect) { if (Event.current != null) { switch (Event.current.rawType) { case EventType.MouseDown: { if (splitterRect.Contains(Event.current.mousePosition)) { this.isSplitterDragging = true; } Event.current.Use(); break; } case EventType.MouseDrag: { if (this.isSplitterDragging) { this.treeViewWidth += Event.current.delta.x; this.treeViewWidth = this.treeViewWidth.Clamp(MinWidth, MaxWidth); Repaint(); } Event.current.Use(); break; } case EventType.MouseUp: { if (this.isSplitterDragging) { this.isSplitterDragging = false; } Event.current.Use(); break; } } } } private void SendSelectedEvent() { if (this.selection.Count == 0) { EditorEvents.Send(new EditorEventGameDataSelectionChanged()); return; } IList<GameDataObject> selectedObjects = new List<GameDataObject>(); foreach (int id in this.selection) { GameDataObject entry; if(this.idObjectMap.TryGetValue(id, out entry)) { selectedObjects.Add(entry); } } EditorEvents.Send(new EditorEventGameDataSelectionChanged(selectedObjects.ToArray())); } private void DrawToolBar(GameDataEditorContent content) { GUIContent guiContent = new GUIContent(); EditorGUILayout.BeginHorizontal(); { GUILayout.Space(4); guiContent.tooltip = "Add (F2)"; guiContent.image = EditorGUIUtility.Load("icons/d_Collab.FileAdded.png") as Texture2D; if (GUILayout.Button(guiContent, this.toolBarStyle)) { this.OpenCreateItemDialog(content); } guiContent.tooltip = "Delete Selection"; guiContent.image = EditorGUIUtility.Load("icons/d_TreeEditor.Trash.png") as Texture2D; if (GUILayout.Button(guiContent, this.toolBarStyle)) { if (EditorUtility.DisplayDialog("Confirm Delete", "This operation can not be undone, continue?", "yes", "no")) { this.currentEditor = null; foreach (int id in this.selection) { GameDataObject entry; if(this.idObjectMap.TryGetValue(id, out entry)) { content.DeleteEntry(entry); } } this.Reload(); } } guiContent.tooltip = "Clone Selected"; guiContent.image = EditorGUIUtility.Load("icons/d_TreeEditor.Duplicate.png") as Texture2D; if (GUILayout.Button(guiContent, this.toolBarStyle)) { this.OpenCreateItemDialog(content, true); } GUILayout.Space(8); if (this.copyObject == null) { guiContent.tooltip = "Copy"; guiContent.image = EditorGUIUtility.Load("icons/Clipboard.png") as Texture2D; if (GUILayout.Button(guiContent, this.toolBarStyle)) { this.CopySelectedObject(); } } else { guiContent.tooltip = "Paste"; guiContent.image = EditorGUIUtility.Load("icons/d_Collab.FileUpdated.png") as Texture2D; if (GUILayout.Button(guiContent, this.toolBarStyle)) { this.PastCopyObjectToSelected(); } guiContent.tooltip = "Cancel Copy"; guiContent.image = EditorGUIUtility.Load("icons/d_LookDevClose.png") as Texture2D; if (GUILayout.Button(guiContent, this.toolBarStyle)) { this.copyObject = null; } } } EditorGUILayout.EndHorizontal(); } private void ResetSelection() { this.selection.Clear(); if (this.activeContent != null) { GameDataObject firstEntry = this.activeContent.Entries.FirstOrDefault(); if (firstEntry != null) { this.Select(firstEntry); } } } private void Select(GameDataObject entry) { this.selection.Clear(); int entryId; if (this.idObjectMap.TryGetKey(entry, out entryId)) { var ids = new List<int> {entryId}; this.SetSelection(ids); this.SelectionChanged(ids); } } private void OpenCreateItemDialog(GameDataEditorContent content, bool clone = false) { if (clone) { this.CopySelectedObject(); } var prompt = ScriptableObject.CreateInstance<GameDataCreatePrompt>(); prompt.Init(newName => { GameDataObject entry = content.CreateEntry(newName); this.Reload(); this.Select(entry); EditorWindow.GetWindow<GameDataEditorWindow>().Focus(); if (clone) { this.PastCopyObjectToSelected(); } }); } private void PastCopyObjectToSelected() { if (this.copyObject == null) { return; } this.copyObject.Update(); foreach (int id in this.selection) { GameDataObject entry; if(!this.idObjectMap.TryGetValue(id, out entry)) { continue; } var target = new SerializedObject(entry); target.Update(); SerializedProperty property = this.copyObject.GetIterator(); if (property.NextVisible(true)) { do { if (property.name == "Guid" || property.name == "Name") { continue; } target.CopyFromSerializedProperty(this.copyObject.FindProperty(property.name)); } while (property.NextVisible(false)); } target.ApplyModifiedProperties(); } } private void CopySelectedObject() { this.copyObject = null; if (this.selection.Count == 0) { return; } GameDataObject entry; if (this.idObjectMap.TryGetValue(this.selection.First(), out entry)) { this.copyObject = new SerializedObject(entry); } } private void RebuildEditor() { this.entryTempList.Clear(); foreach (int id in this.selection) { GameDataObject entry; if (this.idObjectMap.TryGetValue(id, out entry)) { this.entryTempList.Add(entry); } } this.currentEditor = Editor.CreateEditor(this.entryTempList.ToArray()); this.entryTempList.Clear(); } private bool ProcessEventKeyUp(KeyCode key) { switch (key) { case KeyCode.F2: { this.createOnNextRepaint = true; GUI.changed = true; return true; } default: { return false; } } } } }
33.539841
130
0.443428
[ "MIT" ]
Craiel/UnityGameData
Editor/Window/GameDataTreeContentPresenter.cs
16,839
C#
// *** WARNING: this file was generated by the Pulumi SDK Generator. *** // *** Do not edit by hand unless you're certain you know what you are doing! *** using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Threading.Tasks; using Pulumi.Serialization; namespace Pulumi.AzureNative.ApiManagement.V20210101Preview.Inputs { /// <summary> /// Http message diagnostic settings. /// </summary> public sealed class HttpMessageDiagnosticArgs : Pulumi.ResourceArgs { /// <summary> /// Body logging settings. /// </summary> [Input("body")] public Input<Inputs.BodyDiagnosticSettingsArgs>? Body { get; set; } /// <summary> /// Data masking settings. /// </summary> [Input("dataMasking")] public Input<Inputs.DataMaskingArgs>? DataMasking { get; set; } [Input("headers")] private InputList<string>? _headers; /// <summary> /// Array of HTTP Headers to log. /// </summary> public InputList<string> Headers { get => _headers ?? (_headers = new InputList<string>()); set => _headers = value; } public HttpMessageDiagnosticArgs() { } } }
27.446809
81
0.599225
[ "Apache-2.0" ]
polivbr/pulumi-azure-native
sdk/dotnet/ApiManagement/V20210101Preview/Inputs/HttpMessageDiagnosticArgs.cs
1,290
C#