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
sequence
repository_name
stringlengths
7
92
path
stringlengths
3
249
size
int64
5
1.04M
lang
stringclasses
2 values
namespace A { class Program { static void Main() { Test test = new Test(1); } } class Test { private Test(int i) { /* inserted */ int _10 = 10; } } }
13.785714
30
0.476684
[ "Apache-2.0" ]
thufv/DeepFix-C-
data/Mutation/CS0122_4_mutation_10/[E]CS0122.cs
195
C#
/* * Copyright (c) 2014 Universal Technical Resource Services, Inc. * * This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at http://mozilla.org/MPL/2.0/. */ using System; using System.Collections.Generic; using System.ComponentModel; using System.Drawing; using System.Data; using System.Linq; using System.Text; using System.Windows.Forms; using ATMLCommonLibrary.forms; using ATMLModelLibrary.model.common; namespace ATMLCommonLibrary.controls.datum { public partial class DatumTypeDoubleControl : ATMLControl { private boolean _useFlowControl; private @double _doubleValue; public DatumTypeDoubleControl() { InitializeComponent(); standardUnitControl.OnChange += new StandardUnitControl.OnChangeDelegate(standardUnitControl_OnChange); } void standardUnitControl_OnChange(string stdUnit) { if (_doubleValue != null ) _doubleValue.standardUnit = standardUnitControl.StandardUnit; } [Browsable(false)] [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)] public @double DoubleValue { get{ControlsToData(); return _doubleValue; } set { _doubleValue = value;DataToControls();} } public boolean UseFlowControl { get { return _useFlowControl; } set { _useFlowControl = value; } } private void DataToControls() { if (_doubleValue != null) { edtDoubleValue.Value = _doubleValue.value; lblDoubleDescription.Text = _doubleValue.ToString(); standardUnitControl.StandardUnit = _doubleValue.standardUnit; } } private void ControlsToData() { if (!edtDoubleValue.HasValue()) _doubleValue = null; else { if (_doubleValue == null) _doubleValue = new @double(); _doubleValue.value = edtDoubleValue.GetValue<double>(); _doubleValue.standardUnit = standardUnitControl.StandardUnit; } } private void btnDatum_Click(object sender, EventArgs e) { DatumForm form = new DatumForm(); ControlsToData(); form.Datum = _doubleValue; if (DialogResult.OK == form.ShowDialog()) { _doubleValue = form.Datum as @double; DataToControls(); } } private void edtDoubleValue_KeyDown(object sender, KeyEventArgs e) { bool isNum = char.IsNumber((char) e.KeyCode); e.SuppressKeyPress = !isNum; } } }
31.368421
116
0.582215
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
UtrsSoftware/ATMLWorkBench
ATMLLibraries/ATMLCommonLibrary/controls/datum/DatumTypeDoubleControl.cs
2,982
C#
// Copyright (c) Microsoft Open Technologies, Inc. All rights reserved. See License.txt in the project root for license information. namespace System.Data.Entity.Migrations.Utilities { using System.Collections; using System.Data.Entity.Migrations.Design; using System.IO; using System.Linq; using System.Resources; using EnvDTE; using Moq; using Xunit; public class MigrationWriterTests : IDisposable { private const string MigrationName = "InitialCreate"; private const string MigrationId = "201206072128312_" + MigrationName; private const string Language = "cs"; private const string MigrationsDirectory = "Migrations"; private const string UserCodeFileName = MigrationId + "." + Language; private const string DesignerCodeFileName = MigrationId + ".Designer." + Language; private const string ResourcesFileName = MigrationId + ".resx"; private const string UserCodePath = MigrationsDirectory + @"\" + UserCodeFileName; private const string DesignerCodePath = MigrationsDirectory + @"\" + DesignerCodeFileName; private const string ResourcesPath = MigrationsDirectory + @"\" + ResourcesFileName; private const string ResourceName = "MyResource"; private readonly string _projectDir = IOHelpers.GetTempDirName(); [Fact] public void Write_writes_artifacts() { TestWrite( (writer, scaffoldedMigration) => writer.Write(scaffoldedMigration)); } [Fact] public void Write_overwrites_designerCode_and_resources_when_rescaffolding() { CreateProject( "The user code.", "The old designer code.", "The old resource."); TestWrite( (writer, scaffoldedMigration) => writer.Write(scaffoldedMigration, rescaffolding: true)); } [Fact] public void Write_doesnt_overwrite_userCode_when_rescaffolding() { CreateProject( "The edited user code.", "The old designer code.", "The old resource."); TestWrite( (writer, scaffoldedMigration) => writer.Write(scaffoldedMigration, rescaffolding: true, name: MigrationName), skipUserCodeVerification: true); var userCodePath = Path.Combine(_projectDir, UserCodePath); Assert.Equal("The edited user code.", File.ReadAllText(userCodePath)); } [Fact] public void Write_overwrites_artifacts_when_rescaffolding_with_force() { CreateProject( "The edited user code.", "The old designer code.", "The old resource."); TestWrite( (writer, scaffoldedMigration) => writer.Write(scaffoldedMigration, rescaffolding: true, force: true)); } public void Dispose() { Directory.Delete(_projectDir, recursive: true); } private void CreateProject(string userCode, string designerCode, string resource) { Directory.CreateDirectory(Path.Combine(_projectDir, MigrationsDirectory)); var userCodePath = Path.Combine(_projectDir, UserCodePath); File.WriteAllText(userCodePath, userCode); var designerCodePath = Path.Combine(_projectDir, DesignerCodePath); File.WriteAllText(designerCodePath, designerCode); var resourcesPath = Path.Combine(_projectDir, ResourcesPath); using (var resourceWriter = new ResXResourceWriter(resourcesPath)) { resourceWriter.AddResource(ResourceName, resource); } } private void TestWrite( Func<System.Data.Entity.Migrations.Utilities.MigrationWriter, ScaffoldedMigration, string> action, bool skipUserCodeVerification = false) { var command = CreateCommand(_projectDir); var writer = new System.Data.Entity.Migrations.Utilities.MigrationWriter(command); var scaffoldedMigration = new ScaffoldedMigration { MigrationId = MigrationId, Language = Language, Directory = MigrationsDirectory, UserCode = "The user code.", DesignerCode = "The designer code.", Resources = { { ResourceName, "The resource." } } }; var relativeUserCodePath = action(writer, scaffoldedMigration); Assert.Equal(UserCodePath, relativeUserCodePath); if (!skipUserCodeVerification) { var userCodePath = Path.Combine(_projectDir, UserCodePath); Assert.Equal("The user code.", File.ReadAllText(userCodePath)); } var designerCodePath = Path.Combine(_projectDir, DesignerCodePath); Assert.Equal("The designer code.", File.ReadAllText(designerCodePath)); var resourcesPath = Path.Combine(_projectDir, ResourcesPath); using (var reader = new ResXResourceReader(resourcesPath)) { var resources = reader.Cast<DictionaryEntry>(); Assert.Equal(1, resources.Count()); Assert.Contains(new DictionaryEntry(ResourceName, "The resource."), resources); } } private static System.Data.Entity.Migrations.MigrationsDomainCommand CreateCommand(string projectDir) { var fullPathProperty = new Mock<Property>(); fullPathProperty.SetupGet(p => p.Value).Returns(projectDir); var properties = new Mock<Properties>(); properties.Setup(p => p.Item("FullPath")).Returns(fullPathProperty.Object); var dte = new Mock<DTE>(); var projectItems = new Mock<ProjectItems>(); projectItems.SetupGet(pi => pi.Kind).Returns( System.Data.Entity.Migrations.Extensions.ProjectExtensions.VsProjectItemKindPhysicalFolder); projectItems.Setup(pi => pi.AddFromDirectory(It.IsAny<string>())).Returns( () => { var dirProjectItems = new Mock<ProjectItems>(); var dirProjectItem = new Mock<ProjectItem>(); dirProjectItem.SetupGet(pi => pi.ProjectItems).Returns(dirProjectItems.Object); return dirProjectItem.Object; }); var project = new Mock<Project>(); projectItems.SetupGet(pi => pi.Parent).Returns(() => project.Object); project.SetupGet(p => p.Properties).Returns(properties.Object); project.SetupGet(p => p.DTE).Returns(dte.Object); project.SetupGet(p => p.ProjectItems).Returns(projectItems.Object); var command = new Mock<System.Data.Entity.Migrations.MigrationsDomainCommand>(); command.SetupGet(c => c.Project).Returns(project.Object); command.Setup(c => c.WriteWarning(It.IsAny<string>())).Callback(() => { }); return command.Object; } } }
42.518919
134
0.562293
[ "Apache-2.0" ]
TerraVenil/entityframework
test/EntityFramework/UnitTests/Migrations/Utilities/MigrationWriterTests.cs
7,868
C#
// <auto-generated> // 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. // </auto-generated> namespace Microsoft.Azure.Management.OperationalInsights { using Microsoft.Rest; using Microsoft.Rest.Azure; using Models; using System.Collections; using System.Collections.Generic; using System.Threading; using System.Threading.Tasks; /// <summary> /// SharedKeysOperations operations. /// </summary> public partial interface ISharedKeysOperations { /// <summary> /// Gets the shared keys for a workspace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// The name of the workspace. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedKeys>> GetSharedKeysWithHttpMessagesAsync(string resourceGroupName, string workspaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); /// <summary> /// Regenerates the shared keys for a Log Analytics Workspace. These /// keys are used to connect Microsoft Operational Insights agents to /// the workspace. /// </summary> /// <param name='resourceGroupName'> /// The name of the resource group. The name is case insensitive. /// </param> /// <param name='workspaceName'> /// The name of the workspace. /// </param> /// <param name='customHeaders'> /// The headers that will be added to request. /// </param> /// <param name='cancellationToken'> /// The cancellation token. /// </param> /// <exception cref="Microsoft.Rest.Azure.CloudException"> /// Thrown when the operation returned an invalid status code /// </exception> /// <exception cref="Microsoft.Rest.SerializationException"> /// Thrown when unable to deserialize the response /// </exception> /// <exception cref="Microsoft.Rest.ValidationException"> /// Thrown when a required parameter is null /// </exception> Task<AzureOperationResponse<SharedKeys>> RegenerateWithHttpMessagesAsync(string resourceGroupName, string workspaceName, Dictionary<string, List<string>> customHeaders = null, CancellationToken cancellationToken = default(CancellationToken)); } }
42.8375
253
0.644295
[ "MIT" ]
0rland0Wats0n/azure-sdk-for-net
sdk/operationalinsights/Microsoft.Azure.Management.OperationalInsights/src/Generated/ISharedKeysOperations.cs
3,427
C#
/* * ORY Hydra * * Welcome to the ORY Hydra HTTP API documentation. You will find documentation for all HTTP APIs here. * * The version of the OpenAPI document: v1.10.6 * Generated by: https://github.com/openapitools/openapi-generator.git */ using System; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Linq; using System.IO; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using Newtonsoft.Json.Linq; using System.ComponentModel.DataAnnotations; using OpenAPIDateConverter = Ory.Hydra.Client.Client.OpenAPIDateConverter; namespace Ory.Hydra.Client.Model { /// <summary> /// PluginEnv plugin env /// </summary> [DataContract(Name = "PluginEnv")] public partial class HydraPluginEnv : IEquatable<HydraPluginEnv>, IValidatableObject { /// <summary> /// Initializes a new instance of the <see cref="HydraPluginEnv" /> class. /// </summary> [JsonConstructorAttribute] protected HydraPluginEnv() { this.AdditionalProperties = new Dictionary<string, object>(); } /// <summary> /// Initializes a new instance of the <see cref="HydraPluginEnv" /> class. /// </summary> /// <param name="description">description (required).</param> /// <param name="name">name (required).</param> /// <param name="settable">settable (required).</param> /// <param name="value">value (required).</param> public HydraPluginEnv(string description = default(string), string name = default(string), List<string> settable = default(List<string>), string value = default(string)) { // to ensure "description" is required (not null) this.Description = description ?? throw new ArgumentNullException("description is a required property for HydraPluginEnv and cannot be null"); // to ensure "name" is required (not null) this.Name = name ?? throw new ArgumentNullException("name is a required property for HydraPluginEnv and cannot be null"); // to ensure "settable" is required (not null) this.Settable = settable ?? throw new ArgumentNullException("settable is a required property for HydraPluginEnv and cannot be null"); // to ensure "value" is required (not null) this.Value = value ?? throw new ArgumentNullException("value is a required property for HydraPluginEnv and cannot be null"); this.AdditionalProperties = new Dictionary<string, object>(); } /// <summary> /// description /// </summary> /// <value>description</value> [DataMember(Name = "Description", IsRequired = true, EmitDefaultValue = false)] public string Description { get; set; } /// <summary> /// name /// </summary> /// <value>name</value> [DataMember(Name = "Name", IsRequired = true, EmitDefaultValue = false)] public string Name { get; set; } /// <summary> /// settable /// </summary> /// <value>settable</value> [DataMember(Name = "Settable", IsRequired = true, EmitDefaultValue = false)] public List<string> Settable { get; set; } /// <summary> /// value /// </summary> /// <value>value</value> [DataMember(Name = "Value", IsRequired = true, EmitDefaultValue = false)] public string Value { get; set; } /// <summary> /// Gets or Sets additional properties /// </summary> [JsonExtensionData] public IDictionary<string, object> AdditionalProperties { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class HydraPluginEnv {\n"); sb.Append(" Description: ").Append(Description).Append("\n"); sb.Append(" Name: ").Append(Name).Append("\n"); sb.Append(" Settable: ").Append(Settable).Append("\n"); sb.Append(" Value: ").Append(Value).Append("\n"); sb.Append(" AdditionalProperties: ").Append(AdditionalProperties).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return Newtonsoft.Json.JsonConvert.SerializeObject(this, Newtonsoft.Json.Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as HydraPluginEnv); } /// <summary> /// Returns true if HydraPluginEnv instances are equal /// </summary> /// <param name="input">Instance of HydraPluginEnv to be compared</param> /// <returns>Boolean</returns> public bool Equals(HydraPluginEnv input) { if (input == null) return false; return ( this.Description == input.Description || (this.Description != null && this.Description.Equals(input.Description)) ) && ( this.Name == input.Name || (this.Name != null && this.Name.Equals(input.Name)) ) && ( this.Settable == input.Settable || this.Settable != null && input.Settable != null && this.Settable.SequenceEqual(input.Settable) ) && ( this.Value == input.Value || (this.Value != null && this.Value.Equals(input.Value)) ) && (this.AdditionalProperties.Count == input.AdditionalProperties.Count && !this.AdditionalProperties.Except(input.AdditionalProperties).Any()); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Description != null) hashCode = hashCode * 59 + this.Description.GetHashCode(); if (this.Name != null) hashCode = hashCode * 59 + this.Name.GetHashCode(); if (this.Settable != null) hashCode = hashCode * 59 + this.Settable.GetHashCode(); if (this.Value != null) hashCode = hashCode * 59 + this.Value.GetHashCode(); if (this.AdditionalProperties != null) hashCode = hashCode * 59 + this.AdditionalProperties.GetHashCode(); return hashCode; } } /// <summary> /// To validate all properties of the instance /// </summary> /// <param name="validationContext">Validation context</param> /// <returns>Validation Result</returns> IEnumerable<System.ComponentModel.DataAnnotations.ValidationResult> IValidatableObject.Validate(ValidationContext validationContext) { yield break; } } }
39.272277
177
0.569142
[ "Apache-2.0" ]
ALTELMA/sdk
clients/hydra/dotnet/src/Ory.Hydra.Client/Model/HydraPluginEnv.cs
7,933
C#
// Copyright (c) ppy Pty Ltd <contact@ppy.sh>. Licensed under the MIT Licence. // See the LICENCE file in the repository root for full licence text. using System; using System.Collections.Generic; using System.Linq; using NUnit.Framework; using osu.Framework.Testing; using osu.Game.Beatmaps; using osu.Game.Rulesets.Catch.Objects; using osu.Game.Rulesets.Catch.UI; using osu.Game.Rulesets.Objects; using osu.Game.Tests.Visual; using osuTK; namespace osu.Game.Rulesets.Catch.Tests { [TestFixture] public class TestSceneHyperDash : PlayerTestScene { public override IReadOnlyList<Type> RequiredTypes => new[] { typeof(CatcherArea), }; public TestSceneHyperDash() : base(new CatchRuleset()) { } protected override bool Autoplay => true; [Test] public void TestHyperDash() { AddAssert("First note is hyperdash", () => Beatmap.Value.Beatmap.HitObjects[0] is Fruit f && f.HyperDash); AddUntilStep("wait for right movement", () => getCatcher().Scale.X > 0); // don't check hyperdashing as it happens too fast. AddUntilStep("wait for left movement", () => getCatcher().Scale.X < 0); for (int i = 0; i < 3; i++) { AddUntilStep("wait for right hyperdash", () => getCatcher().Scale.X > 0 && getCatcher().HyperDashing); AddUntilStep("wait for left hyperdash", () => getCatcher().Scale.X < 0 && getCatcher().HyperDashing); } } private Catcher getCatcher() => Player.ChildrenOfType<CatcherArea>().First().MovableCatcher; protected override IBeatmap CreateBeatmap(RulesetInfo ruleset) { var beatmap = new Beatmap { BeatmapInfo = { Ruleset = ruleset, BaseDifficulty = new BeatmapDifficulty { CircleSize = 3.6f } } }; // Should produce a hyper-dash (edge case test) beatmap.HitObjects.Add(new Fruit { StartTime = 1816, X = 56 / 512f, NewCombo = true }); beatmap.HitObjects.Add(new Fruit { StartTime = 2008, X = 308 / 512f, NewCombo = true }); double startTime = 3000; const float left_x = 0.02f; const float right_x = 0.98f; createObjects(() => new Fruit { X = left_x }); createObjects(() => new TestJuiceStream(right_x), 1); createObjects(() => new TestJuiceStream(left_x), 1); createObjects(() => new Fruit { X = right_x }); createObjects(() => new Fruit { X = left_x }); createObjects(() => new Fruit { X = right_x }); createObjects(() => new TestJuiceStream(left_x), 1); return beatmap; void createObjects(Func<CatchHitObject> createObject, int count = 3) { const float spacing = 140; for (int i = 0; i < count; i++) { var hitObject = createObject(); hitObject.StartTime = startTime + i * spacing; beatmap.HitObjects.Add(hitObject); } startTime += 700; } } private class TestJuiceStream : JuiceStream { public TestJuiceStream(float x) { X = x; Path = new SliderPath(new[] { new PathControlPoint(Vector2.Zero), new PathControlPoint(new Vector2(30, 0)), }); } } } }
34.336364
137
0.527138
[ "MIT" ]
EVAST9919/osu
osu.Game.Rulesets.Catch.Tests/TestSceneHyperDash.cs
3,670
C#
namespace HunterPie.Core { public class Member { private string _Name = ""; private int _Damage; private byte _Weapon = 255; public string Name { get => _Name; set { if (value == "" && "" == _Name && Damage > 0) { _Name = "Player"; _OnSpawn(); return; } else if (value != "" && value != _Name) { if (value == "" && Damage > 0) { _OnSpawn(); } else { _Name = value; _OnSpawn(); } } else if (value == "" && value != _Name && Damage == 0) { _Name = value; _OnSpawn(); } } } public float DamagePercentage { get; set; } public int Damage { get => _Damage; set { if (value != _Damage) { _Damage = value; _OnDamageChange(); } } } public byte Weapon { get => _Weapon; set { if (value != _Weapon) { if (_Weapon != 255 && value == 255) return; _Weapon = value; WeaponIconName = GetWeaponIconNameByID(value); _OnWeaponChange(); } } } public string WeaponIconName; public bool IsPartyLeader { get; set; } public bool IsInParty { get; set; } public short HR { get; set; } public short MR { get; set; } public bool IsMe { get; set; } public delegate void PartyMemberEvents(object source, PartyMemberEventArgs args); public event PartyMemberEvents OnDamageChange; public event PartyMemberEvents OnWeaponChange; public event PartyMemberEvents OnSpawn; protected virtual void _OnDamageChange() => OnDamageChange?.Invoke(this, new PartyMemberEventArgs(this)); protected virtual void _OnWeaponChange() => OnWeaponChange?.Invoke(this, new PartyMemberEventArgs(this)); protected virtual void _OnSpawn() => OnSpawn?.Invoke(this, new PartyMemberEventArgs(this)); public void SetPlayerInfo(string name, byte weapon_id, int damage, float damagePercentage) { if (string.IsNullOrEmpty(name) && weapon_id == 0) { Weapon = Weapon; } else { Weapon = weapon_id; } if (string.IsNullOrEmpty(name) && damage == 0) IsInParty = false; else { IsInParty = true; } DamagePercentage = damagePercentage; Damage = damage; Name = name; } private string GetWeaponIconNameByID(int id) { switch (id) { case 0: return "ICON_GREATSWORD"; case 1: return "ICON_SWORDANDSHIELD"; case 2: return "ICON_DUALBLADES"; case 3: return "ICON_LONGSWORD"; case 4: return "ICON_HAMMER"; case 5: return "ICON_HUNTINGHORN"; case 6: return "ICON_LANCE"; case 7: return "ICON_GUNLANCE"; case 8: return "ICON_SWITCHAXE"; case 9: return "ICON_CHARGEBLADE"; case 10: return "ICON_INSECTGLAIVE"; case 11: return "ICON_BOW"; case 12: return "ICON_HEAVYBOWGUN"; case 13: return "ICON_LIGHTBOWGUN"; default: return null; } } } }
30.283688
113
0.413583
[ "MIT" ]
nicodiaz55/HunterPie
HunterPie/Core/Party/Member.cs
4,272
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("PreviewControlModel")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("PreviewControlModel")] [assembly: AssemblyCopyright("Copyright © 2021")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("ef4a1334-7797-4da5-9e35-d5834a383fd6")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38
84
0.750356
[ "MIT" ]
SoftBIM/PreviewControlRevitAPI
PreviewControlRevitAPI/Properties/AssemblyInfo.cs
1,409
C#
namespace SoccerStatistics.Api.Database.Entities { public enum InteractionType { Goal, Change, Foul, ShotOnGoal } }
14.636364
49
0.57764
[ "MIT" ]
JustD4nTe/SoccerStatistics.Api
src/SoccerStatistics.Api.Database/Entities/Enums/InteractionType.cs
163
C#
namespace Bitfinex.Client.Websocket.Client { internal static class BitfinexLogger { public static string L(string msg) { return $"[BFX WEBSOCKET CLIENT] {msg}"; } } }
21.5
51
0.586047
[ "Apache-2.0" ]
ColossusFX/bitfinex-client-websocket
src/Bitfinex.Client.Websocket/Client/BitfinexLogger.cs
217
C#
using System; using System.Collections.Generic; using System.Linq; using System.IO; using System.Threading; using TrueCraft.API; using TrueCraft.API.World; using TrueCraft.API.Logic; using fNbt; namespace TrueCraft.Core.World { public class World : IDisposable, IWorld { public static readonly int Height = 128; public string Name { get; set; } public int Seed { get; set; } private Coordinates3D? _SpawnPoint; public Coordinates3D SpawnPoint { get { if (_SpawnPoint == null) _SpawnPoint = ChunkProvider.GetSpawn(this); return _SpawnPoint.Value; } set { _SpawnPoint = value; } } public string BaseDirectory { get; internal set; } public IDictionary<Coordinates2D, IRegion> Regions { get; set; } public IBiomeMap BiomeDiagram { get; set; } public IChunkProvider ChunkProvider { get; set; } public IBlockRepository BlockRepository { get; set; } public DateTime BaseTime { get; set; } public long Time { get { return (long)((DateTime.Now - BaseTime).TotalSeconds * 20) % 24000; } set { // TODO } } public event EventHandler<BlockChangeEventArgs> BlockChanged; public World() { Regions = new Dictionary<Coordinates2D, IRegion>(); BaseTime = DateTime.Now; } public World(string name) : this() { Name = name; Seed = new Random().Next(); BiomeDiagram = new BiomeMap(Seed); } public World(string name, IChunkProvider chunkProvider) : this(name) { ChunkProvider = chunkProvider; } public World(string name, int seed, IChunkProvider chunkProvider) : this(name, chunkProvider) { Seed = seed; BiomeDiagram = new BiomeMap(Seed); } public static World LoadWorld(string baseDirectory) { if (!Directory.Exists(baseDirectory)) throw new DirectoryNotFoundException(); var world = new World(Path.GetFileName(baseDirectory)); world.BaseDirectory = baseDirectory; if (File.Exists(Path.Combine(baseDirectory, "manifest.nbt"))) { var file = new NbtFile(Path.Combine(baseDirectory, "manifest.nbt")); world.SpawnPoint = new Coordinates3D(file.RootTag["SpawnPoint"]["X"].IntValue, file.RootTag["SpawnPoint"]["Y"].IntValue, file.RootTag["SpawnPoint"]["Z"].IntValue); world.Seed = file.RootTag["Seed"].IntValue; var providerName = file.RootTag["ChunkProvider"].StringValue; var provider = (IChunkProvider)Activator.CreateInstance(Type.GetType(providerName), world); world.ChunkProvider = provider; } return world; } /// <summary> /// Finds a chunk that contains the specified block coordinates. /// </summary> public IChunk FindChunk(Coordinates3D coordinates) { IChunk chunk; FindBlockPosition(coordinates, out chunk); return chunk; } public IChunk GetChunk(Coordinates2D coordinates) { int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0); int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0); var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ)); return region.GetChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32)); } public void GenerateChunk(Coordinates2D coordinates) { int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0); int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0); var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ)); region.GenerateChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32)); } public void SetChunk(Coordinates2D coordinates, Chunk chunk) { int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0); int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0); var region = LoadOrGenerateRegion(new Coordinates2D(regionX, regionZ)); lock (region) { chunk.IsModified = true; region.SetChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32), chunk); } } public void UnloadRegion(Coordinates2D coordinates) { lock (Regions) { Regions[coordinates].Save(Path.Combine(BaseDirectory, Region.GetRegionFileName(coordinates))); Regions.Remove(coordinates); } } public void UnloadChunk(Coordinates2D coordinates) { int regionX = coordinates.X / Region.Width - ((coordinates.X < 0) ? 1 : 0); int regionZ = coordinates.Z / Region.Depth - ((coordinates.Z < 0) ? 1 : 0); var regionPosition = new Coordinates2D(regionX, regionZ); if (!Regions.ContainsKey(regionPosition)) throw new ArgumentOutOfRangeException("coordinates"); Regions[regionPosition].UnloadChunk(new Coordinates2D(coordinates.X - regionX * 32, coordinates.Z - regionZ * 32)); } public byte GetBlockID(Coordinates3D coordinates) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); return chunk.GetBlockID(coordinates); } public byte GetMetadata(Coordinates3D coordinates) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); return chunk.GetMetadata(coordinates); } public byte GetSkyLight(Coordinates3D coordinates) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); return chunk.GetSkyLight(coordinates); } public byte GetBlockLight(Coordinates3D coordinates) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); return chunk.GetBlockLight(coordinates); } public BlockDescriptor GetBlockData(Coordinates3D coordinates) { IChunk chunk; var adjustedCoordinates = FindBlockPosition(coordinates, out chunk); return GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates); } public void SetBlockData(Coordinates3D coordinates, BlockDescriptor descriptor) { // TODO: Figure out the best way to handle light in this scenario IChunk chunk; var adjustedCoordinates = FindBlockPosition(coordinates, out chunk); var old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates); chunk.SetBlockID(adjustedCoordinates, descriptor.ID); chunk.SetMetadata(adjustedCoordinates,descriptor.Metadata); if (BlockChanged != null) BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates))); } private BlockDescriptor GetBlockDataFromChunk(Coordinates3D adjustedCoordinates, IChunk chunk, Coordinates3D coordinates) { return new BlockDescriptor { ID = chunk.GetBlockID(adjustedCoordinates), Metadata = chunk.GetMetadata(adjustedCoordinates), BlockLight = chunk.GetBlockLight(adjustedCoordinates), SkyLight = chunk.GetSkyLight(adjustedCoordinates), Coordinates = coordinates }; } public void SetBlockID(Coordinates3D coordinates, byte value) { IChunk chunk; var adjustedCoordinates = FindBlockPosition(coordinates, out chunk); BlockDescriptor old = new BlockDescriptor(); if (BlockChanged != null) old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates); chunk.SetBlockID(adjustedCoordinates, value); if (BlockChanged != null) BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates))); } public void SetMetadata(Coordinates3D coordinates, byte value) { IChunk chunk; var adjustedCoordinates = FindBlockPosition(coordinates, out chunk); BlockDescriptor old = new BlockDescriptor(); if (BlockChanged != null) old = GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates); chunk.SetMetadata(adjustedCoordinates, value); if (BlockChanged != null) BlockChanged(this, new BlockChangeEventArgs(coordinates, old, GetBlockDataFromChunk(adjustedCoordinates, chunk, coordinates))); } public void SetSkyLight(Coordinates3D coordinates, byte value) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); chunk.SetSkyLight(coordinates, value); } public void SetBlockLight(Coordinates3D coordinates, byte value) { IChunk chunk; coordinates = FindBlockPosition(coordinates, out chunk); chunk.SetBlockLight(coordinates, value); } public void Save() { lock (Regions) { foreach (var region in Regions) region.Value.Save(Path.Combine(BaseDirectory, Region.GetRegionFileName(region.Key))); } var file = new NbtFile(); file.RootTag.Add(new NbtCompound("SpawnPoint", new[] { new NbtInt("X", this.SpawnPoint.X), new NbtInt("Y", this.SpawnPoint.Y), new NbtInt("Z", this.SpawnPoint.Z) })); file.RootTag.Add(new NbtInt("Seed", this.Seed)); file.RootTag.Add(new NbtString("ChunkProvider", this.ChunkProvider.GetType().FullName)); file.SaveToFile(Path.Combine(this.BaseDirectory, "manifest.nbt"), NbtCompression.ZLib); } public void Save(string path) { if (!Directory.Exists(path)) Directory.CreateDirectory(path); BaseDirectory = path; Save(); } public Coordinates3D FindBlockPosition(Coordinates3D coordinates, out IChunk chunk) { if (coordinates.Y < 0 || coordinates.Y >= Chunk.Height) throw new ArgumentOutOfRangeException("coordinates", "Coordinates are out of range"); var chunkX = (int)Math.Floor((double)coordinates.X / Chunk.Width); var chunkZ = (int)Math.Floor((double)coordinates.Z / Chunk.Depth); chunk = GetChunk(new Coordinates2D(chunkX, chunkZ)); return new Coordinates3D( (coordinates.X - chunkX * Chunk.Width) % Chunk.Width, coordinates.Y, (coordinates.Z - chunkZ * Chunk.Depth) % Chunk.Depth); } public bool IsValidPosition(Coordinates3D position) { return position.Y >= 0 && position.Y <= 255; } private Region LoadOrGenerateRegion(Coordinates2D coordinates) { if (Regions.ContainsKey(coordinates)) return (Region)Regions[coordinates]; Region region; if (BaseDirectory != null) { var file = Path.Combine(BaseDirectory, Region.GetRegionFileName(coordinates)); if (File.Exists(file)) region = new Region(coordinates, this, file); else region = new Region(coordinates, this); } else region = new Region(coordinates, this); lock (Regions) Regions[coordinates] = region; return region; } public void Dispose() { foreach (var region in Regions) region.Value.Dispose(); } } }
38.528875
143
0.584096
[ "MIT" ]
jacobmarshall-etc/TrueCraft
TrueCraft.Core/World/World.cs
12,676
C#
using HW5.DataAccess.EntityFramework.Configurations; using HW5.Domain.Entities; using Microsoft.EntityFrameworkCore; namespace HW5.DataAccess.EntityFramework { public class AppDbContext : DbContext { public AppDbContext(DbContextOptions<AppDbContext> options) : base(options) { } // Database Connection for the Posts Table. public DbSet<Post> Posts { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { base.OnModelCreating(modelBuilder); modelBuilder.ApplyConfiguration(new PostConfiguration()); } } }
31.35
87
0.695375
[ "MIT" ]
PatikaDev-Logo-Net-Bootcamp/Homeworks-Meleknur-Yazlamaz
Homework-5/HW5/HW5.DataAccess.EntityFramework/AppDbContext.cs
629
C#
using System.Collections.Generic; using System.Runtime.CompilerServices; [assembly: InternalsVisibleTo("UnitTests")] namespace Consart.Measures { /// <summary>Base Measure Units of equivalence classes</summary> internal static class MeasureBase { private readonly static Dictionary<string, MeasureUnit> Base = new Dictionary<string, MeasureUnit>(); /// <summary>Checks if a unit already exists</summary> public static bool Contains(MeasureUnit unit) => Base.ContainsKey(unit.GetType().Name); /// <summary>Adds a unit if it does not exist</summary> public static void Add(MeasureUnit unit) { if (!Contains(unit)) Base.Add(unit.GetType().Name, unit); } /// <summary>Returns a base measure unit for a given unit (if exists)</summary> public static MeasureUnit Get(MeasureUnit unit) => Contains(unit) ? Base[unit.GetType().Name] : null; } }
33.896552
109
0.651068
[ "MIT" ]
TadeuszGruzlewski/Price-Framework
Measure/Measures/MeasureUnit/MeasureBase.cs
985
C#
// Copyright (c) Microsoft Corporation. // Licensed under the MIT License. using System.Collections.Generic; using System.Diagnostics; using CtfPlayback.Metadata.Interfaces; using CtfPlayback.Metadata.TypeInterfaces; using LTTngCds.CtfExtensions.Descriptors; namespace LTTngCds.CtfExtensions { internal class LTTngMetadata : ICtfMetadataBuilder { private readonly List<ICtfStreamDescriptor> streams = new List<ICtfStreamDescriptor>(); private readonly List<ICtfClockDescriptor> clocks = new List<ICtfClockDescriptor>(); private readonly List<ICtfEventDescriptor> events = new List<ICtfEventDescriptor>(); private readonly Dictionary<uint, ICtfEventDescriptor> eventsById = new Dictionary<uint, ICtfEventDescriptor>(); private readonly Dictionary<string, ICtfClockDescriptor> clocksByName = new Dictionary<string, ICtfClockDescriptor>(); public ICtfTraceDescriptor TraceDescriptor { get; private set; } public ICtfEnvironmentDescriptor EnvironmentDescriptor { get; private set; } public IReadOnlyList<ICtfClockDescriptor> Clocks => this.clocks; public IReadOnlyDictionary<string, ICtfClockDescriptor> ClocksByName => this.clocksByName; public IReadOnlyList<ICtfStreamDescriptor> Streams => this.streams; public IReadOnlyList<ICtfEventDescriptor> Events => this.events; public IReadOnlyDictionary<uint, ICtfEventDescriptor> EventByEventId => this.eventsById; public void SetTraceDescriptor(ICtfTraceDescriptor traceDescriptor) { Debug.Assert(traceDescriptor != null); this.TraceDescriptor = traceDescriptor; } public void SetEnvironmentDescriptor(ICtfEnvironmentDescriptor environmentDescriptor) { Debug.Assert(environmentDescriptor != null); this.EnvironmentDescriptor = environmentDescriptor; } public void AddEvent( IReadOnlyDictionary<string, string> assignments, IReadOnlyDictionary<string, ICtfTypeDescriptor> typeDeclarations) { var eventDescriptor = new EventDescriptor(assignments, typeDeclarations); this.events.Add(eventDescriptor); this.eventsById.Add(eventDescriptor.Id, eventDescriptor); } public void AddClock(ICtfClockDescriptor clockDescriptor) { this.clocks.Add(clockDescriptor); this.clocksByName.Add(clockDescriptor.Name, clockDescriptor); } public void AddStream(ICtfStreamDescriptor streamDescriptor) { this.streams.Add(streamDescriptor); } } }
38.550725
126
0.714286
[ "MIT" ]
Armison/Microsoft-Performance-Tools-Linux-Android
LTTngCds/CtfExtensions/LTTngMetadata.cs
2,660
C#
namespace BinanceAPI.Authentication { /// <summary> /// Api addresses /// </summary> public class BinanceApiAddresses { /// <summary> /// The address used by the BinanceClient for the Spot API /// </summary> public string RestClientAddress { get; set; } = ""; /// <summary> /// The address used by the BinanceSocketClient for the Spot API /// </summary> public string SocketClientAddress { get; set; } = ""; /// <summary> /// The default addresses to connect to the binance.com API /// </summary> public static BinanceApiAddresses Default = new() { RestClientAddress = "https://api.binance.com", SocketClientAddress = "wss://stream.binance.com:9443/", }; /// <summary> /// The addresses to connect to the binance testnet /// </summary> public static BinanceApiAddresses TestNet = new() { RestClientAddress = "https://testnet.binance.vision", SocketClientAddress = "wss://testnet.binance.vision", }; /// <summary> /// The addresses to connect to binance.us. /// </summary> public static BinanceApiAddresses Us = new() { RestClientAddress = "https://api.binance.us", SocketClientAddress = "wss://stream.binance.us:9443", }; } }
31.866667
72
0.557183
[ "MIT" ]
HypsyNZ/Binance-API
Binance-API/Binance-API/Authentication/BinanceApiAddresses.cs
1,436
C#
using System; namespace Weikio.ApiFramework.Abstractions { public class StatusMessage { public DateTime MessageTime { get; } public string Message { get; } public StatusMessage(DateTime messageTime, string message) { MessageTime = messageTime; Message = message; } } }
21.6875
66
0.608069
[ "Apache-2.0" ]
weikio/ApiFramework
src/Weikio.ApiFramework.Abstractions/StatusMessage.cs
349
C#
// Copyright (c) .NET Foundation and Contributors. All Rights Reserved. Licensed under the MIT License (MIT). See License.md in the repository root for more information. // Ported from https://github.com/dotnet/clangsharp/blob/main/sources/libClangSharp namespace ClangSharp.Interop { public enum CX_AtomicOperatorKind { CX_AO_Invalid, CX_AO__c11_atomic_init, CX_AO__c11_atomic_load, CX_AO__c11_atomic_store, CX_AO__c11_atomic_exchange, CX_AO__c11_atomic_compare_exchange_strong, CX_AO__c11_atomic_compare_exchange_weak, CX_AO__c11_atomic_fetch_add, CX_AO__c11_atomic_fetch_sub, CX_AO__c11_atomic_fetch_and, CX_AO__c11_atomic_fetch_or, CX_AO__c11_atomic_fetch_xor, CX_AO__c11_atomic_fetch_max, CX_AO__c11_atomic_fetch_min, CX_AO__atomic_load, CX_AO__atomic_load_n, CX_AO__atomic_store, CX_AO__atomic_store_n, CX_AO__atomic_exchange, CX_AO__atomic_exchange_n, CX_AO__atomic_compare_exchange, CX_AO__atomic_compare_exchange_n, CX_AO__atomic_fetch_add, CX_AO__atomic_fetch_sub, CX_AO__atomic_fetch_and, CX_AO__atomic_fetch_or, CX_AO__atomic_fetch_xor, CX_AO__atomic_fetch_nand, CX_AO__atomic_add_fetch, CX_AO__atomic_sub_fetch, CX_AO__atomic_and_fetch, CX_AO__atomic_or_fetch, CX_AO__atomic_xor_fetch, CX_AO__atomic_max_fetch, CX_AO__atomic_min_fetch, CX_AO__atomic_nand_fetch, CX_AO__opencl_atomic_init, CX_AO__opencl_atomic_load, CX_AO__opencl_atomic_store, CX_AO__opencl_atomic_exchange, CX_AO__opencl_atomic_compare_exchange_strong, CX_AO__opencl_atomic_compare_exchange_weak, CX_AO__opencl_atomic_fetch_add, CX_AO__opencl_atomic_fetch_sub, CX_AO__opencl_atomic_fetch_and, CX_AO__opencl_atomic_fetch_or, CX_AO__opencl_atomic_fetch_xor, CX_AO__opencl_atomic_fetch_min, CX_AO__opencl_atomic_fetch_max, CX_AO__atomic_fetch_min, CX_AO__atomic_fetch_max, } }
35.672131
169
0.72886
[ "MIT" ]
Color-Of-Code/ClangSharp
sources/ClangSharp.Interop/CX_AtomicOperatorKind.cs
2,176
C#
using System; using System.Collections.Generic; using System.Text; namespace Tizen.NUI { internal static partial class Interop { internal static partial class ViewResourceReadySignal { [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ViewResourceReadySignal_Empty")] public static extern bool ViewResourceReadySignal_Empty(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ViewResourceReadySignal_GetConnectionCount")] public static extern uint ViewResourceReadySignal_GetConnectionCount(global::System.Runtime.InteropServices.HandleRef jarg1); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ViewResourceReadySignal_Connect")] public static extern void ViewResourceReadySignal_Connect(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ViewResourceReadySignal_Disconnect")] public static extern void ViewResourceReadySignal_Disconnect(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_ViewResourceReadySignal_Emit")] public static extern void ViewResourceReadySignal_Emit(global::System.Runtime.InteropServices.HandleRef jarg1, global::System.Runtime.InteropServices.HandleRef jarg2); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_new_ViewResourceReadySignal")] public static extern global::System.IntPtr new_ViewResourceReadySignal(); [global::System.Runtime.InteropServices.DllImport(NDalicPINVOKE.Lib, EntryPoint = "CSharp_Dali_delete_ViewResourceReadySignal")] public static extern void delete_ViewResourceReadySignal(global::System.Runtime.InteropServices.HandleRef jarg1); } } }
68.363636
185
0.781472
[ "Apache-2.0", "MIT" ]
Ali-Alzyoud/TizenFX
src/Tizen.NUI/src/internal/Interop/Interop.ViewResourceReadySignal.cs
2,258
C#
namespace DemoDataService.Areas.HelpPage.ModelDescriptions { public class DictionaryModelDescription : KeyValuePairModelDescription { } }
24.833333
74
0.798658
[ "MIT" ]
tlaothong/lab-swp-ws-kiatnakin
LabWsKiatnakin/DemoDataService/Areas/HelpPage/ModelDescriptions/DictionaryModelDescription.cs
149
C#
using System; using DanfeSharp.Enumeracoes; using DanfeSharp.Graphics; namespace DanfeSharp.Elementos { /// <summary> /// Cabeçalho do bloco, normalmente um texto em caixa alta. /// </summary> internal class CabecalhoBloco : ElementoBase { public const float MargemSuperior = 0.8F; public String Cabecalho { get; set; } public CabecalhoBloco(Estilo estilo, String cabecalho) : base(estilo) { Cabecalho = cabecalho ?? throw new ArgumentNullException(cabecalho); } public override void Draw(Gfx gfx) { base.Draw(gfx); gfx.DrawString(Cabecalho.ToUpper(), BoundingBox, Estilo.FonteBlocoCabecalho, AlinhamentoHorizontal.Esquerda, AlinhamentoVertical.Base ); } public override float Height { get => MargemSuperior + Estilo.FonteBlocoCabecalho.AlturaLinha; set => throw new NotSupportedException(); } public override bool PossuiContono => false; } }
32.419355
146
0.657711
[ "MIT" ]
faironsp/DanfeSharp
DanfeSharp/Elementos/CabecalhoBloco.cs
1,008
C#
/* Licensed under the MIT/X11 license. * Copyright (c) 2016-2018 jointly owned by eBestow Technocracy India Pvt. Ltd. & M&M Info-Tech UK Ltd. * This notice may not be removed from any source distribution. * See license.txt for detailed licensing details. */ // Author: Manan Adhvaryu. #if Window using System; using System.Runtime.InteropServices; using System.Text; using MnM.GWS.SDL; namespace MnM.GWS { #if HideGWSObjects partial class NativeFactory { #endif #if DevSupport public #else internal #endif sealed class SdlWindow : _DesktopWindow, IDesktopWindow { #region VARIABLES const int defaultWidth = 300; const int defaultHeight = 300; IntPtr handle; WindowFlags windowFlags; VectorF scale; // private Icon icon; //RendererFlags renderFlags; IntPtr sdlCursor = IntPtr.Zero; string title; bool fullScreen; bool isSingleThreaded; char[] DecodeTextBuffer = new char[32]; float opacity = 1f; ISound sound; WindowState windowState, pWindowState; WindowBorder windowBorder = WindowBorder.Resizable; #endregion #region CONSTRUCTORS public SdlWindow(string title = null, int? width = null, int? height = null, int? x = null, int? y = null, GwsWindowFlags? flags = null, IScreen display = null, RendererFlags? renderFlags = null) : base(title, width, height, x, y, flags, display, renderFlags) { } public SdlWindow(IExternalTarget control) : base(control) { } protected sealed override bool Initialize(string title = null, int? width = null, int? height = null, int? x = null, int? y = null, GwsWindowFlags? flags = null, IScreen display = null, IExternalTarget externalWindow = null, RendererFlags? renderFlags = null) { sound = Factory.newWavPlayer(); mouseState.SetIsConnected(true); keyState.SetIsConnected(true); pMouseState.SetIsConnected(true); base.Screen = display ?? Factory.AvailableScreens.Primary; this.title = title ?? "MnM Window"; var gwsWindowFlags = flags ?? 0; windowFlags = GetFlags(gwsWindowFlags); isSingleThreaded = (gwsWindowFlags & GwsWindowFlags.MultiThread) == GwsWindowFlags.MultiThread; NativeFactory.DisableScreenSaverEx(); try { if ((windowFlags & WindowFlags.Shown) != WindowFlags.Shown) windowFlags |= WindowFlags.Hidden; if ((windowFlags & WindowFlags.NoBorders) == WindowFlags.NoBorders) windowFlags |= WindowFlags.Resizable; //windowFlags |= WindowFlags.Maximized; if (externalWindow != null) { handle = NativeFactory.CreateWindowFrom(externalWindow.Handle); } else { int px = Screen.Bounds.X + x ?? 0; int py = Screen.Bounds.Y + y ?? 0; int wd = width ?? defaultWidth; int ht = height ?? defaultHeight; if ((windowFlags & WindowFlags.FullScreen) == WindowFlags.FullScreen || (windowFlags & WindowFlags.FullScreenDesktop) == WindowFlags.FullScreenDesktop || (windowFlags & WindowFlags.Maximized) == WindowFlags.Maximized) { windowFlags = windowFlags & ~WindowFlags.FullScreen; windowFlags = windowFlags & ~WindowFlags.FullScreenDesktop; windowFlags = windowFlags & ~WindowFlags.Resizable; windowFlags = windowFlags & ~WindowFlags.Maximized; px = 0; py = 0; wd = Screen.Width; ht = Screen.Height; fullScreen = true; } else { px = (Screen.Bounds.W - wd) / 2 - px / 2; py = (Screen.Bounds.H - ht) / 2 - py / 2; } handle = NativeFactory.CreateWindow(title, px, py, wd, ht, (int)windowFlags); } if ((windowFlags & WindowFlags.Shown) == WindowFlags.Shown) IsVisible = true; else IsVisible = false; NativeFactory.GetWindowSize(Handle, out int w, out int h); NativeFactory.GetWindowPosition(Handle, out int _x, out int _y); CopyBounds(_x, _y, w, h); RendererFlags = renderFlags ?? RendererFlags.Accelarated; //NativeFactory.SetHint("DL_FRAMEBUFFER_ACCELERATION", "1"); return true; } catch { return false; } } protected override void GetTypeName(out string typeName) => typeName = "Window"; #endregion #region PROPERTIES public sealed override IntPtr Handle => handle; public override float Transparency { get => 1f - opacity; set { opacity = 1f - value; NativeFactory.SetWindowOpacity(Handle, opacity); } } public override WindowState WindowState => windowState; public override WindowBorder WindowBorder => windowBorder; public override string Text { get { if (Valid) return title + ""; return string.Empty; } set { if (Valid) { NativeFactory.SetWindowTitle(Handle, value); title = value; } } } public override VectorF Scale { get => scale; set { var renderer = NativeFactory.GetRenderer(Handle); NativeFactory.RenderSetScale(renderer, value.X, value.Y); scale = value; } } public override bool CursorVisible { get => cursorVisible; set { if (Valid && value != cursorVisible) { grabCursor(!value); cursorVisible = value; } } } public override uint PixelFormat => NativeFactory.pixelFormat; public CursorType Cursor { get; set; } public string ToolTipText { get; set; } public object Tag { get; set; } public override ISound Sound => sound; public override bool LosingFocus => false; #endregion #region FOCUS public bool Has(Vector p) { if (Transparency >= 1f) return false; if (!Enabled) return false; return Bounds.Contains(p.X, p.Y); } public override void BringToFront() { if (!Enabled || !Visible) return; var window = Application.GetWindow<IDesktopWindow>((x) => x.Focused); NativeFactory.RaiseWindow(Handle); if (window != null) { if (!window.Equals(this)) window.Focus(); } } public override void SendToBack() { var b = Bounds; var window = Application.GetWindow<IDesktopWindow>((x) => x.Bounds.Intersects(b)); window?.BringToFront(); } public override bool Focus() { if (!Enabled || !Visible) return false; NativeFactory.RaiseWindow(Handle); return true; } #endregion #region CREATE GL CONTEXT //public GLContext CreateGLContext() => // GLContext.Create(this); #endregion #region SHOW - HIDE public override void Show() { IsVisible = true; windowFlags |= WindowFlags.Shown; windowFlags = windowFlags & ~WindowFlags.Hidden; if (fullScreen) NativeFactory.MaximizeWindow(Handle); else NativeFactory.ShowWindow(Handle); } public override void Hide() { NativeFactory.HideWindow(Handle); windowFlags |= WindowFlags.Hidden; windowFlags = windowFlags & ~WindowFlags.Shown; IsVisible = false; } #endregion #region CLOSE protected override void OnClosed(IEventArgs e) { sound?.Dispose(); if (Handle != IntPtr.Zero) { cursorVisible = true; var renderer = NativeFactory.GetRenderer(Handle); NativeFactory.DestroyRenderer(renderer); NativeFactory.DestroyWindow(Handle); } handle = IntPtr.Zero; base.OnClosed(e); } #endregion #region RESIZE public override void Resize(int w, int h) { if (IsDisposed || (w == Width && h == Height) || (w == 0 && h == 0)) return; NativeFactory.SetWindowSize(Handle, w, h); base.Resize(w, h); } #endregion #region PRIVATE METHODS void grabCursor(bool grab) { NativeFactory.ShowCursor(!grab ? 0 : 1); NativeFactory.SetWindowGrab(Handle, grab); NativeFactory.SetRelativeMouseMode(grab); if (!grab) { // Move the cursor to the current position // order to avoid a sudden jump when it // becomes visible again float scale = Width / (float)Height; NativeFactory.WarpMouseInWindow(Handle, (int)Math.Round(mouseState.X / scale), (int)Math.Round(mouseState.Y / scale)); } } #endregion #region CURSOR public sealed override void SetCursor(int x, int y, bool silent = true) { NativeFactory.ShowCursor(1); NativeFactory.SetCursorPosition(x + X, y + Y); base.SetCursor(x, y, silent); } public override void ShowCursor() => NativeFactory.ShowCursor(1); public override void HideCursor() => NativeFactory.ShowCursor(0); public override void ContainMouse(bool flag) => NativeFactory.SetWindowGrab(Handle, flag); #endregion #region CHANGE public override void ChangeScreen(int screenIndex) { } public override void ChangeState(WindowState value) { if (windowState == value || !Valid) return; switch (value) { case WindowState.Maximized: NativeFactory.MaximizeWindow(Handle); windowState = WindowState.Maximized; break; case WindowState.Minimized: NativeFactory.MinimizeWindow(Handle); windowState = WindowState.Minimized; break; case WindowState.Normal: NativeFactory.RestoreWindow(Handle); break; } if (!CursorVisible) grabCursor(true); OnWindowStateChanged(Factory.EventArgs); } public override void ChangeBorder(WindowBorder value) { if (WindowBorder == value || !Valid) return; switch (value) { case WindowBorder.Resizable: NativeFactory.SetWindowBordered(Handle, true); windowBorder = WindowBorder.Resizable; break; case WindowBorder.Hidden: NativeFactory.SetWindowBordered(Handle, false); windowBorder = WindowBorder.Hidden; break; case WindowBorder.Fixed: break; } OnWindowBorderChanged(Factory.EventArgs); } public override void Move(int x, int y) { if (!Valid) return; X = x; Y = y; NativeFactory.SetWindowPosition(Handle, Area.X, Area.Y); } #endregion #region EVENT ARGS readonly MouseEventArgs MouseDownArgs = new MouseEventArgs(); readonly MouseEventArgs MouseUpArgs = new MouseEventArgs(); readonly MouseEventArgs MouseMoveArgs = new MouseEventArgs(); readonly MouseEventArgs MouseWheelArgs = new MouseEventArgs(); readonly KeyEventArgs KeyDownArgs = new KeyEventArgs(); readonly KeyEventArgs KeyUpArgs = new KeyEventArgs(); readonly KeyPressEventArgs KeyPressArgs = new KeyPressEventArgs((char)0); readonly TextInputEventArgs TextInputEventArgs = new TextInputEventArgs(); readonly FileDropEventArgs FileDropArgs = new FileDropEventArgs(); Mouse mouseState = new Mouse(); Keyboard keyState = new Keyboard(); Mouse pMouseState = new Mouse(); #endregion #region INPUT PROCESSING public bool CanProcessEvent => !IsDisposed && Visible && Enabled && Valid; protected override IEventArgs ParseEvent(IEvent @event) { if (IsDisposed || !Visible || !Enabled || !Valid) return null; if (!(@event is Event)) return null; Event ev = (Event)@event; switch (ev.Type) { case EventType.WINDOWEVENT: return processWindowEvent(ev.Window); case EventType.TEXTINPUT: return processTextInputEvent(ev.TextInputEvent); case EventType.KEYDOWN: case EventType.KEYUP: return processKeyEvent(ev); case EventType.MOUSEBUTTONDOWN: case EventType.MOUSEBUTTONUP: return processMouseButtonEvent(ev.MouseButtonEvent); case EventType.MOUSEMOTION: return processMouseMotionEvent(ev.MouseMotionEvent); case EventType.MOUSEWHEEL: return processMouseWheelEvent(ev.MouseWheelEvent); case EventType.DROPFILE: var e = processDropEvent(ev.DropEvent); NativeFactory.Free(ev.DropEvent.File); return e; default: return null; } } IEventArgs processWindowEvent(WindowEvent e) { switch ((WindowEvents)e.Event) { case WindowEvents.Close: Close(); return null; case WindowEvents.MouseEnter: return MouseUpArgs; case WindowEvents.MouseLeave: return MouseUpArgs; case WindowEvents.Exposed: return null; case WindowEvents.GotFocus: return CancelArgs; case WindowEvents.LostFocus: return CancelArgs; case WindowEvents.Hidden: return Factory.EventArgs; case WindowEvents.Shown: return Factory.EventArgs; case WindowEvents.Moved: NativeFactory.GetWindowPosition(Handle, out int x, out int y); X = x; Y = y; return Factory.EventArgs; case WindowEvents.Resized: var sizeArg = new GwsSizeEventArgs(e.Data1, e.Data2); return sizeArg; case WindowEvents.Maximized: windowState = WindowState.Maximized; return Factory.EventArgs; case WindowEvents.MiniMized: pWindowState = windowState; windowState = WindowState.Minimized; return Factory.EventArgs; case WindowEvents.Restored: windowState = pWindowState; return Factory.EventArgs; default: return null; } } IEventArgs processKeyEvent(Event ev) { bool keyPressed = ev.KeyboardEvent.State == InputState.Pressed; var key = (SdlKeys)ev.KeyboardEvent.Keysym.Scancode; if (keyPressed) { keyState.SetKeyState(key, true); var e = KeyDownArgs; e.Keyboard = keyState; e.SdlKeyCode = key; e.IsRepeat = ev.KeyboardEvent.Repeat > 0; return e; } else { keyState.SetKeyState(key, false); var e = KeyUpArgs; e.Keyboard = keyState; e.SdlKeyCode = key; e.IsRepeat = false; return e; } } unsafe IEventArgs processTextInputEvent(TextInputEvent ev) { // Calculate the length of the typed text string int length; for (length = 0; length < TextInputEvent.TextSize && ev.Text[length] != '\0'; length++) { } // Make sure we have enough space to decode this string int decoded_length = Encoding.UTF8.GetCharCount(ev.Text, length); if (DecodeTextBuffer.Length < decoded_length) { Array.Resize( ref DecodeTextBuffer, 2 * Math.Max(decoded_length, DecodeTextBuffer.Length)); } // Decode the string from UTF8 to .Net UTF16 fixed (char* pBuffer = DecodeTextBuffer) { decoded_length = System.Text.Encoding.UTF8.GetChars( ev.Text, length, pBuffer, DecodeTextBuffer.Length); } TextInputEventArgs.Characters = new char[decoded_length]; for (int i = 0; i < decoded_length; i++) { TextInputEventArgs.Characters[i] = DecodeTextBuffer[i]; } return TextInputEventArgs; } IEventArgs processMouseButtonEvent(MouseButtonEvent ev) { MouseButton button = MouseEventArgs.GetButton((int)ev.Button); if (ev.Type == EventType.MOUSEBUTTONDOWN) { mouseState[button] = true; var e = MouseDownArgs; e.button = button; e.IsPressed = true; e.Mouse = mouseState; e.Status = MouseState.Down; return e; } else { mouseState[button] = false; var e = MouseUpArgs; e.button = button; e.IsPressed = false; e.Mouse = mouseState; e.Status = MouseState.Up; return e; } } IEventArgs processMouseMotionEvent(MouseMotionEvent ev) { //float scale = w / (float)h; var x = ev.X - 0;// (int)Math.Round(ev.X);// * scale); var y = ev.Y - 0;// (int)Math.Round(ev.Y);// * scale); //GWS.Windows.MouseScale = scale; mouseState.X = x; mouseState.Y = y; var e = MouseMoveArgs; e.Mouse = mouseState; e.Status = MouseState.Move; if((ev.State & ButtonFlags.Left)== ButtonFlags.Left) { e.button = MouseButton.Left; } else if ((ev.State & ButtonFlags.Right) == ButtonFlags.Right) { e.button = MouseButton.Right; } else if ((ev.State & ButtonFlags.Middle) == ButtonFlags.Middle) { e.button = MouseButton.Right; } if (mouseState.IsButtonDown(e.button)) e.Status |= MouseState.Down; else e.button = 0; pMouseState = mouseState; return (e); } IEventArgs processMouseWheelEvent(MouseWheelEvent ev) { mouseState.SetScrollRelative(ev.X, ev.Y); var e = MouseWheelArgs; e.Mouse = mouseState; e.Delta = ev.Y; e.Status = MouseState.Wheel; if (ev.X == 0 && ev.Y == 0) return null; pMouseState = mouseState; return e; } IEventArgs processDropEvent(DropEvent ev) { var e = FileDropArgs; FileDropArgs.FileName = Marshal.PtrToStringUni(ev.File); return null; //OnFileDrop(e); } #endregion #region MISC /// <summary> /// Call this method to simulate KeyDown/KeyUp events /// on platforms that do not generate key events for /// modifier flags (e.g. Mac/Cocoa). /// Note: this method does not distinguish between the /// left and right variants of modifier keys. /// </summary> /// <param name="mods">Mods.</param> SdlKeys updateModifierFlags(SdlKeyModifiers mods, out bool modifierFound) { bool alt = (mods & SdlKeyModifiers.Alt) != 0; bool control = (mods & SdlKeyModifiers.Control) != 0; bool shift = (mods & SdlKeyModifiers.Shift) != 0; modifierFound = alt || control || shift; if (alt) { return SdlKeys.AltLeft; } if (control) { return (SdlKeys.ControlLeft); } if (shift) { return (SdlKeys.ShiftLeft); } return 0; } static WindowFlags GetFlags(GwsWindowFlags flags) { WindowFlags flag = WindowFlags.Default; if ((flags & GwsWindowFlags.Foreign) == GwsWindowFlags.Foreign) flag |= WindowFlags.Foreign; if ((flags & GwsWindowFlags.FullScreen) == GwsWindowFlags.FullScreen) flag |= WindowFlags.FullScreen; if ((flags & GwsWindowFlags.FullScreenDesktop) == GwsWindowFlags.FullScreenDesktop) flag |= WindowFlags.FullScreenDesktop; if ((flags & GwsWindowFlags.GrabInput) == GwsWindowFlags.GrabInput) flag |= WindowFlags.GrabInput; if ((flags & GwsWindowFlags.Hidden) == GwsWindowFlags.Hidden) flag |= WindowFlags.Hidden; if ((flags & GwsWindowFlags.HighDPI) == GwsWindowFlags.HighDPI) flag |= WindowFlags.HighDPI; if ((flags & GwsWindowFlags.InputFocus) == GwsWindowFlags.InputFocus) flag |= WindowFlags.InputFocus; if ((flags & GwsWindowFlags.Maximized) == GwsWindowFlags.Maximized) flag |= WindowFlags.Maximized; if ((flags & GwsWindowFlags.Minimized) == GwsWindowFlags.Minimized) flag |= WindowFlags.Minimized; if ((flags & GwsWindowFlags.MouseFocus) == GwsWindowFlags.MouseFocus) flag |= WindowFlags.MouseFocus; if ((flags & GwsWindowFlags.NoBorders) == GwsWindowFlags.NoBorders) flag |= WindowFlags.NoBorders; if ((flags & GwsWindowFlags.OpenGL) == GwsWindowFlags.OpenGL) flag |= WindowFlags.OpenGL; if ((flags & GwsWindowFlags.Resizable) == GwsWindowFlags.Resizable) flag |= WindowFlags.Resizable; if ((flags & GwsWindowFlags.Shown) == GwsWindowFlags.Shown) flag |= WindowFlags.Shown; return flag; } #endregion } #if HideGWSObjects } #endif } #endif
37.21547
138
0.467117
[ "MIT" ]
MnMInfoTech/GWS
GWSSDL/SdlWindow.cs
26,946
C#
using System.Collections.Generic; using Tweetinvi.Models; namespace Tweetinvi.Core.QueryGenerators { public interface IFriendshipQueryGenerator { string GetUserIdsRequestingFriendshipQuery(); string GetUserIdsYouRequestedToFollowQuery(); string GetUserIdsWhoseRetweetsAreMutedQuery(); // Get Existing Friendship string GetRelationshipDetailsQuery(IUserIdentifier sourceUserIdentifier, IUserIdentifier targetUserIdentifier); // Lookup Relationship State string GetMultipleRelationshipsQuery(IEnumerable<IUserIdentifier> users); string GetMultipleRelationshipsQuery(IEnumerable<long> userIds); string GetMultipleRelationshipsQuery(IEnumerable<string> screenNames); // Create Friendship string GetCreateFriendshipWithQuery(IUserIdentifier user); // Destroy Friendship string GetDestroyFriendshipWithQuery(IUserIdentifier user); // Update Friendship Authorization string GetUpdateRelationshipAuthorizationsWithQuery(IUserIdentifier user, IFriendshipAuthorizations friendshipAuthorizations); } }
38.931034
134
0.770593
[ "MIT" ]
247GradLabs/tweetinvi
Tweetinvi.Core/Core/QueryGenerators/IFriendshipQueryGenerator.cs
1,131
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.Collections.Generic; using System.Linq; using Roslyn.Utilities; namespace StarkPlatform.CodeAnalysis.Shared.Extensions { internal static class SyntaxNodeOrTokenExtensions { public static IEnumerable<SyntaxNodeOrToken> DepthFirstTraversal(this SyntaxNodeOrToken node) { var stack = new Stack<SyntaxNodeOrToken>(); stack.Push(node); while (!stack.IsEmpty()) { var current = stack.Pop(); yield return current; if (current.IsNode) { foreach (var child in current.ChildNodesAndTokens().Reverse()) { stack.Push(child); } } } } public static SyntaxTrivia[] GetTrivia(params SyntaxNodeOrToken[] nodesOrTokens) => nodesOrTokens.SelectMany(nodeOrToken => nodeOrToken.GetLeadingTrivia().Concat(nodeOrToken.GetTrailingTrivia())).ToArray(); } }
33.138889
161
0.601006
[ "Apache-2.0" ]
stark-lang/stark-roslyn
src/Workspaces/Core/Portable/Shared/Extensions/SyntaxNodeOrTokenExtensions.cs
1,195
C#
using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Runtime.InteropServices.WindowsRuntime; using Windows.ApplicationModel; using Windows.ApplicationModel.Activation; using Windows.Foundation; using Windows.Foundation.Collections; using Windows.UI.Xaml; using Windows.UI.Xaml.Controls; using Windows.UI.Xaml.Controls.Primitives; using Windows.UI.Xaml.Data; using Windows.UI.Xaml.Input; using Windows.UI.Xaml.Media; using Windows.UI.Xaml.Navigation; namespace BlackCat.UWP { /// <summary> /// Provides application-specific behavior to supplement the default Application class. /// </summary> sealed partial class App : Application { /// <summary> /// Initializes the singleton application object. This is the first line of authored code /// executed, and as such is the logical equivalent of main() or WinMain(). /// </summary> public App() { this.InitializeComponent(); this.Suspending += OnSuspending; } /// <summary> /// Invoked when the application is launched normally by the end user. Other entry points /// will be used such as when the application is launched to open a specific file. /// </summary> /// <param name="e">Details about the launch request and process.</param> protected override void OnLaunched(LaunchActivatedEventArgs e) { #if DEBUG if (System.Diagnostics.Debugger.IsAttached) { this.DebugSettings.EnableFrameRateCounter = true; } #endif Frame rootFrame = Window.Current.Content as Frame; // Do not repeat app initialization when the Window already has content, // just ensure that the window is active if (rootFrame == null) { // Create a Frame to act as the navigation context and navigate to the first page rootFrame = new Frame(); rootFrame.NavigationFailed += OnNavigationFailed; Xamarin.Forms.Forms.Init(e); if (e.PreviousExecutionState == ApplicationExecutionState.Terminated) { //TODO: Load state from previously suspended application } // Place the frame in the current Window Window.Current.Content = rootFrame; } if (rootFrame.Content == null) { // When the navigation stack isn't restored navigate to the first page, // configuring the new page by passing required information as a navigation // parameter rootFrame.Navigate(typeof(MainPage), e.Arguments); } // Ensure the current window is active Window.Current.Activate(); } /// <summary> /// Invoked when Navigation to a certain page fails /// </summary> /// <param name="sender">The Frame which failed navigation</param> /// <param name="e">Details about the navigation failure</param> void OnNavigationFailed(object sender, NavigationFailedEventArgs e) { throw new Exception("Failed to load Page " + e.SourcePageType.FullName); } /// <summary> /// Invoked when application execution is being suspended. Application state is saved /// without knowing whether the application will be terminated or resumed with the contents /// of memory still intact. /// </summary> /// <param name="sender">The source of the suspend request.</param> /// <param name="e">Details about the suspend request.</param> private void OnSuspending(object sender, SuspendingEventArgs e) { var deferral = e.SuspendingOperation.GetDeferral(); //TODO: Save application state and stop any background activity deferral.Complete(); } } }
37.287037
99
0.620313
[ "Apache-2.0" ]
DLozanoNavas/xamarin-forms-book-samples
Chapter04/BlackCat/BlackCat/BlackCat.UWP/App.xaml.cs
4,027
C#
using System; namespace TramsDataApi.DatabaseModels { public partial class Sponsor { public string PRid { get; set; } public string Rid { get; set; } public string SponsorId { get; set; } public string SponsorsSponsorId { get; set; } public string SponsorsSponsorName { get; set; } public string SponsorsPreviousOrAlternativeName { get; set; } public string SponsorsCoSponsorOrEducationalPartner { get; set; } public string SponsorsSponsorStatus { get; set; } public string SponsorsSponsorCoordinator { get; set; } public string SponsorsLeadContactForSponsor { get; set; } public string SponsorsLeadRscRegion { get; set; } public string LeadRscRegion { get; set; } public string SponsorsKs2MatQualityAssessment { get; set; } public string SponsorsKs4MatQualityAssessment { get; set; } public string SponsorsOtherMatQualityAssessment { get; set; } public string SponsorsOtherMatQualityAssessmentType { get; set; } public string SponsorsOverallCapacityForTheAcademicYear { get; set; } public string SponsorsSponsorRestriction { get; set; } public DateTime? SponsorsSponsorPausedExitedDate { get; set; } public DateTime? SponsorsPauseReviewDate { get; set; } public string SponsorsLinkToWorkplaces { get; set; } public bool? SponsorsLoadOpenAcademiesWithThisSponsor { get; set; } public bool? SponsorsLoadPipelineAcademiesProvisionallyWithThisSponsor { get; set; } public bool? SponsorsLoadPrePipelineAcademiesProvisionallyWithThisSponsor { get; set; } public bool? SponsorsLoadOpenAcademiesProvisionallyWithThisSponsorThroughReSponsoring { get; set; } public string SponsorContactDetailsContactName { get; set; } public string SponsorContactDetailsContactPosition { get; set; } public string SponsorContactDetailsContactPhone { get; set; } public string SponsorContactDetailsContactEmail { get; set; } public string SponsorContactDetailsContactAddressLine1 { get; set; } public string SponsorContactDetailsContactAddressLine2 { get; set; } public string SponsorContactDetailsContactAddressLine3 { get; set; } public string SponsorContactDetailsContactTown { get; set; } public string SponsorContactDetailsContactCounty { get; set; } public string SponsorContactDetailsContactPostcode { get; set; } public string SponsorContactDetailsContactLa { get; set; } public string SponsorCharacteristicsSponsorType { get; set; } public string SponsorCharacteristicsSecondOrderSponsorType { get; set; } public string SponsorCharacteristicsSponsorEducationalInstitutionCharacteristic { get; set; } public string SponsorCharacteristicsSponsorExpertisePrimary { get; set; } public string SponsorCharacteristicsSponsorExpertisePru { get; set; } public string SponsorCharacteristicsSponsorExpertiseSecondary { get; set; } public string SponsorCharacteristicsSponsorExpertiseSpecial { get; set; } public string ApprovalSponsorStatus { get; set; } public DateTime? ApprovalWithdrawnDate { get; set; } public string ApprovalWithdrawalLedBy { get; set; } public DateTime? ApprovalLastContactDate { get; set; } public DateTime? ApprovalExpressionOfInterestDate { get; set; } public DateTime? ApprovalApplicationDate { get; set; } public DateTime? ApprovalApplicationApprovedDate { get; set; } public DateTime? ApprovalEfaDueDiligenceCheckDateSent { get; set; } public DateTime? ApprovalEfaDueDiligenceCheckDateCompleted { get; set; } public string ApprovalEfaDueDiligenceCheckStatus { get; set; } public string ApprovalEfaComments { get; set; } public string ApprovalDueDiligenceCheck { get; set; } public string ApprovalDueDiligenceComments { get; set; } public string ApprovalSponsorRecruitmentEventAttendedIfApplicable { get; set; } public DateTime? ManagementCapacityAndAssessmentReviewDate { get; set; } public string ManagementCapacityAndGradeAssessmentComments { get; set; } public string ManagementSponsorCoordinatorComments { get; set; } public string ManagementEngagementTypeEastOfEnglandAndNorthEastLondon { get; set; } public string ManagementCapacityEastOfEnglandAndNorthEastLondon { get; set; } public string ManagementEngagementTypeSouthEastAndSouthLondon { get; set; } public string ManagementCapacitySouthEastAndSouthLondon { get; set; } public string ManagementEngagementTypeNorthWestLondonAndSouthCentral { get; set; } public string ManagementCapacityNorthWestLondonAndSouthCentral { get; set; } public string ManagementEngagementTypeSouthWest { get; set; } public string ManagementCapacitySouthWest { get; set; } public string ManagementEngagementTypeNorth { get; set; } public string ManagementCapacityNorth { get; set; } public string ManagementEngagementTypeEastMidlandsAndHumber { get; set; } public string ManagementCapacityEastMidlandsAndHumber { get; set; } public string ManagementEngagementTypeWestMidlands { get; set; } public string ManagementCapacityWestMidlands { get; set; } public string ManagementEngagementTypeLancashireAndWestYorkshire { get; set; } public string ManagementCapacityLancashireAndWestYorkshire { get; set; } public string ManagementSponsorMeetingsWithMinistersDate { get; set; } public string ManagementSponsorMeetingsWithRscDate { get; set; } public string ManagementPriorityArea { get; set; } public string ManagementLocalAuthorityS { get; set; } public string LocalAuthoritiesActive { get; set; } public string LocalAuthoritiesProspective { get; set; } public string SponsorTemplateInformationSponsorOverview { get; set; } public string SponsorTemplateInformationKeyPeople { get; set; } public string SponsorTemplateInformationFinance { get; set; } public string SponsorTemplateInformationFuturePlans { get; set; } public string SponsorTemplateInformationIssues { get; set; } public string SponsorTemplateInformationGovernanceAndTrustBoardStructuresAndAccountabilityFramework { get; set; } public string SponsorTemplateInformationSchoolImprovementStrategy { get; set; } public string SponsorTemplateInformationCompanyNumber { get; set; } } }
66.757576
121
0.734302
[ "MIT" ]
DFE-Digital/trams-data-api
TramsDataApi/DatabaseModels/Sponsor.cs
6,611
C#
using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Metadata.Builders; using VideoApi.Domain; namespace VideoApi.DAL.Mappings { public class ConferenceStatusMap : IEntityTypeConfiguration<ConferenceStatus> { public void Configure(EntityTypeBuilder<ConferenceStatus> builder) { builder.ToTable(nameof(ConferenceStatus)); builder.HasKey(x => x.Id); builder.Property(x => x.ConferenceState); builder.Property(x => x.TimeStamp); } } }
29.833333
81
0.687151
[ "MIT" ]
hmcts/vh-video-api
VideoApi/VideoApi.DAL/Mappings/ConferenceStatusMap.cs
537
C#
using System; using System.Collections.Generic; using System.Linq; using System.Web; using System.Web.Mvc; using System.Web.Routing; namespace BoFramework.Northwind.MvcWebUI { public class MvcApplication : System.Web.HttpApplication { protected void Application_Start() { AreaRegistration.RegisterAllAreas(); RouteConfig.RegisterRoutes(RouteTable.Routes); } } }
22.263158
60
0.699764
[ "MIT" ]
berkayozturkk/BoFramework
BoFramework.Northwind.MvcWebUI/Global.asax.cs
423
C#
using System; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using StarWars.Data.EntityFramework; namespace StarWars.Data.EntityFramework.Migrations { [DbContext(typeof(StarWarsContext))] [Migration("20170215075510_Inital")] partial class Inital { protected override void BuildTargetModel(ModelBuilder modelBuilder) { modelBuilder .HasAnnotation("ProductVersion", "1.1.0-rtm-22752") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("StarWars.Core.Models.Droid", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name"); b.HasKey("Id"); b.ToTable("Droids"); }); } } }
30.617647
117
0.6244
[ "MIT" ]
Alexandre-Nourissier/StarWars
StarWars.Data/EntityFramework/Migrations/20170215075510_Inital.Designer.cs
1,043
C#
// // MenuItemBackend.cs // // Author: // Carlos Alberto Cortez <calberto.cortez@gmail.com> // Eric Maupin <ermau@xamarin.com> // // Copyright (c) 2011 Carlos Alberto Cortez // Copyright (c) 2012 Xamarin, Inc. // // 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.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using SWC = System.Windows.Controls; using SWMI = System.Windows.Media.Imaging; using Xwt.Backends; namespace Xwt.WPFBackend { public class MenuItemBackend : Backend, IMenuItemBackend { UIElement item; SWC.MenuItem menuItem; MenuBackend subMenu; MenuItemType type; IMenuItemEventSink eventSink; string label; bool useMnemonic; public MenuItemBackend () : this (new SWC.MenuItem()) { } protected MenuItemBackend (UIElement item) { this.item = item; this.menuItem = item as SWC.MenuItem; useMnemonic = true; } public void Initialize (IMenuItemEventSink eventSink) { this.eventSink = eventSink; } public object Item { get { return this.item; } } public SWC.MenuItem MenuItem { get { return this.menuItem; } } public IMenuItemEventSink EventSink { get { return eventSink; } } public bool Checked { get { if (this.menuItem == null) return false; return this.menuItem.IsCheckable && this.menuItem.IsChecked; } set { if (this.menuItem == null || !this.menuItem.IsCheckable) return; this.menuItem.IsChecked = value; } } public string Label { get { return label; } set { label = value; if (this.menuItem != null) menuItem.Header = UseMnemonic ? value : value.Replace ("_", "__"); } } public bool UseMnemonic { get { return useMnemonic; } set { useMnemonic = value; Label = label; } } public bool Sensitive { get { return this.item.IsEnabled; } set { this.item.IsEnabled = value; } } public bool Visible { get { return this.item.IsVisible; } set { this.item.Visibility = (value) ? Visibility.Visible : Visibility.Collapsed; } } public void SetImage (ImageDescription imageBackend) { if (imageBackend.IsNull) this.menuItem.Icon = null; else this.menuItem.Icon = new ImageBox (Context) { ImageSource = imageBackend }; } public void SetSubmenu (IMenuBackend menu) { if (menu == null) { this.menuItem.Items.Clear (); if (subMenu != null) { subMenu.RemoveFromParentItem (); subMenu = null; } return; } var menuBackend = (MenuBackend)menu; menuBackend.RemoveFromParentItem (); foreach (var itemBackend in menuBackend.Items) this.menuItem.Items.Add (itemBackend.Item); menuBackend.ParentItem = this; subMenu = menuBackend; } public void SetType (MenuItemType type) { switch (type) { case MenuItemType.RadioButton: case MenuItemType.CheckBox: this.menuItem.IsCheckable = true; break; case MenuItemType.Normal: this.menuItem.IsCheckable = false; break; } this.type = type; } internal void SetFont (FontData font) { MenuItem.FontFamily = font.Family; MenuItem.FontSize = font.GetDeviceIndependentPixelSize(MenuItem); MenuItem.FontStyle = font.Style; MenuItem.FontWeight = font.Weight; MenuItem.FontStretch = font.Stretch; } public override void EnableEvent (object eventId) { if (menuItem == null) return; if (eventId is MenuItemEvent) { switch ((MenuItemEvent)eventId) { case MenuItemEvent.Clicked: this.menuItem.Click += MenuItemClickHandler; break; } } } public override void DisableEvent (object eventId) { if (menuItem == null) return; if (eventId is MenuItemEvent) { switch ((MenuItemEvent)eventId) { case MenuItemEvent.Clicked: this.menuItem.Click -= MenuItemClickHandler; break; } } } void MenuItemClickHandler (object sender, EventArgs args) { Context.InvokeUserCode (eventSink.OnClicked); } } }
25.264423
87
0.661085
[ "MIT" ]
UPBIoT/renode-iot
lib/termsharp/xwt/Xwt.WPF/Xwt.WPFBackend/MenuItemBackend.cs
5,257
C#
using System.Text; using ORA.API; using ORA.API.Encryption; using Xunit; using FluentAssertions; using ORA.Core.Encryption; namespace ORA.Core.Tests.Encryption { public class CipherTests : IClassFixture<CoreInitializationFixture> { [Fact] public void RsaCipherTests() { ICipher c = Ora.GetCipher(); byte[] message = Encoding.ASCII.GetBytes("Hello World"); c.Decrypt(c.Encrypt(message)).Should().Equal(message); if (!(c is RsaCipher)) return; ICipher cipher = new RsaCipher(((RsaCipher) c).GetPublicKey(), ((RsaCipher) c).GetPrivateKey()); cipher.Decrypt(c.Encrypt(message)).Should().Equal(message); } } }
28.407407
109
0.597132
[ "MIT" ]
Crab-Wave/ora
ORA.Core.Tests/Encryption/CipherTests.cs
743
C#
// This file is part of Silk.NET. // // You may modify and distribute Silk.NET under the terms // of the MIT license. See the LICENSE file for details. using System; namespace Silk.NET.Core.Attributes { /// <summary> /// An attribute specifying an inject point to be injected by SilkTouch. /// </summary> /// <remarks>See SilkTouch documentation.</remarks> /// <seealso cref="SilkTouchStage"/> [AttributeUsage(AttributeTargets.Method, AllowMultiple = true)] public class InjectAttribute : Attribute { /// <summary> /// Initializes a new instance of the <see cref="InjectAttribute"/> class. /// </summary> /// <param name="silkTouchStage">The stage at which to inject.</param> /// <param name="code">The code to inject.</param> public InjectAttribute(SilkTouchStage silkTouchStage, string code) { } } /// <summary> /// An enum indicating where to inject code to SilkTouch. DO NOT RELY ON NUMERIC VALUES. /// </summary> /// <remarks>See SilkTouch documentation.</remarks> /// <seealso cref="InjectAttribute"/> public enum SilkTouchStage { // NOTE: These ARE IN ORDER. SilkTouch verifies correct ordering via the oder they are typed here. /// <summary> /// No stage. Default value. /// </summary> None = 0, /// <summary> /// The start of the pipeline. /// </summary> Begin, /// <summary> /// After basic values have been initialized. /// </summary> PostInit, /// <summary> /// After pinning occurs. /// </summary> /// <remarks>Currently there is no PostRelease or similar (that would occur after pins have been released), since SilkTouch currently never closes blocks.</remarks> PostPin, /// <summary> /// Just before loading. /// </summary> PreLoad, /// <summary> /// Just after loading. /// </summary> PostLoad, /// <summary> /// The end of the pipeline. /// </summary> End } }
32.530303
172
0.582673
[ "MIT" ]
ThomasMiz/Silk.NET
src/Core/Silk.NET.Core/Attributes/InjectAttribute.cs
2,149
C#
// <copyright file="DelimitedReaderTests.cs" company="Math.NET"> // Math.NET Numerics, part of the Math.NET Project // http://numerics.mathdotnet.com // http://github.com/mathnet/mathnet-numerics // http://mathnetnumerics.codeplex.com // // Copyright (c) 2009-2013 Math.NET // // 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. // </copyright> using System; using System.Globalization; using System.IO; using System.Numerics; using System.Text; using NUnit.Framework; using MathNet.Numerics.Data.Text; namespace MathNet.Numerics.Data.UnitTests.Text { /// <summary> /// Delimited reader tests. /// </summary> [TestFixture] public class DelimitedReaderTests { /// <summary> /// Can parse comma delimited data. /// </summary> [Test] public void CanParseCommaDelimitedData() { var data = "a,b,c" + Environment.NewLine + "1" + Environment.NewLine + "\"2.2\",0.3e1" + Environment.NewLine + "'4',5,6" + Environment.NewLine; var reader = new DelimitedReader { Delimiter = ",", HasHeaderRow = true, FormatProvider = CultureInfo.InvariantCulture }; var matrix = reader.ReadMatrix<double>(new MemoryStream(Encoding.UTF8.GetBytes(data))); Assert.AreEqual(3, matrix.RowCount); Assert.AreEqual(3, matrix.ColumnCount); Assert.AreEqual(1.0, matrix[0, 0]); Assert.AreEqual(0.0, matrix[0, 1]); Assert.AreEqual(0.0, matrix[0, 2]); Assert.AreEqual(2.2, matrix[1, 0]); Assert.AreEqual(3.0, matrix[1, 1]); Assert.AreEqual(0.0, matrix[1, 2]); Assert.AreEqual(4.0, matrix[2, 0]); Assert.AreEqual(5.0, matrix[2, 1]); Assert.AreEqual(6.0, matrix[2, 2]); } /// <summary> /// Can parse tab delimited data. /// </summary> [Test] public void CanParseTabDelimitedData() { var data = "1" + Environment.NewLine + "\"2.2\"\t\t0.3e1" + Environment.NewLine + "'4'\t5\t6"; var matrix = DelimitedReader.ReadStream<float>(new MemoryStream(Encoding.UTF8.GetBytes(data)), delimiter: "\t", formatProvider: CultureInfo.InvariantCulture); Assert.AreEqual(3, matrix.RowCount); Assert.AreEqual(3, matrix.ColumnCount); Assert.AreEqual(1.0f, matrix[0, 0]); Assert.AreEqual(0.0f, matrix[0, 1]); Assert.AreEqual(0.0f, matrix[0, 2]); Assert.AreEqual(2.2f, matrix[1, 0]); Assert.AreEqual(3.0f, matrix[1, 1]); Assert.AreEqual(0.0f, matrix[1, 2]); Assert.AreEqual(4.0f, matrix[2, 0]); Assert.AreEqual(5.0f, matrix[2, 1]); Assert.AreEqual(6.0f, matrix[2, 2]); } /// <summary> /// Can parse white space delimited data. /// </summary> [Test] public void CanParseWhiteSpaceDelimitedData() { var data = "1" + Environment.NewLine + "\"2.2\" 0.3e1" + Environment.NewLine + "'4' 5 6" + Environment.NewLine; var reader = new DelimitedReader { FormatProvider = CultureInfo.InvariantCulture }; var matrix = reader.ReadMatrix<float>(new MemoryStream(Encoding.UTF8.GetBytes(data))); Assert.AreEqual(3, matrix.RowCount); Assert.AreEqual(3, matrix.ColumnCount); Assert.AreEqual(1.0f, matrix[0, 0]); Assert.AreEqual(0.0f, matrix[0, 1]); Assert.AreEqual(0.0f, matrix[0, 2]); Assert.AreEqual(2.2f, matrix[1, 0]); Assert.AreEqual(3.0f, matrix[1, 1]); Assert.AreEqual(0.0f, matrix[1, 2]); Assert.AreEqual(4.0f, matrix[2, 0]); Assert.AreEqual(5.0f, matrix[2, 1]); Assert.AreEqual(6.0f, matrix[2, 2]); } /// <summary> /// Can parse period delimited data. /// </summary> [Test] public void CanParsePeriodDelimitedData() { var data = "a.b.c" + Environment.NewLine + "1" + Environment.NewLine + "\"2,2\".0,3e1" + Environment.NewLine + "'4,0'.5,0.6,0" + Environment.NewLine; var reader = new DelimitedReader { Delimiter = ".", HasHeaderRow = true, FormatProvider = new CultureInfo("tr-TR") }; var matrix = reader.ReadMatrix<double>(new MemoryStream(Encoding.UTF8.GetBytes(data))); Assert.AreEqual(3, matrix.RowCount); Assert.AreEqual(3, matrix.ColumnCount); Assert.AreEqual(1.0, matrix[0, 0]); Assert.AreEqual(0.0, matrix[0, 1]); Assert.AreEqual(0.0, matrix[0, 2]); Assert.AreEqual(2.2, matrix[1, 0]); Assert.AreEqual(3.0, matrix[1, 1]); Assert.AreEqual(0.0, matrix[1, 2]); Assert.AreEqual(4.0, matrix[2, 0]); Assert.AreEqual(5.0, matrix[2, 1]); Assert.AreEqual(6.0, matrix[2, 2]); } /// <summary> /// Can parse comma delimited complex data. /// </summary> [Test] public void CanParseComplexCommaDelimitedData() { var data = "a,b,c" + Environment.NewLine + "(1,2)" + Environment.NewLine + "\"2.2\",0.3e1" + Environment.NewLine + "'(4,-5)',5,6" + Environment.NewLine; var matrix = DelimitedReader.Read<Complex>(new StringReader(data), delimiter: ",", hasHeaders: true, formatProvider: CultureInfo.InvariantCulture); Assert.AreEqual(3, matrix.RowCount); Assert.AreEqual(3, matrix.ColumnCount); Assert.AreEqual(1.0, matrix[0, 0].Real); Assert.AreEqual(2.0, matrix[0, 0].Imaginary); Assert.AreEqual((Complex) 0.0, matrix[0, 1]); Assert.AreEqual((Complex) 0.0, matrix[0, 2]); Assert.AreEqual((Complex) 2.2, matrix[1, 0]); Assert.AreEqual((Complex) 3.0, matrix[1, 1]); Assert.AreEqual((Complex) 0.0, matrix[1, 2]); Assert.AreEqual(4.0, matrix[2, 0].Real); Assert.AreEqual(-5.0, matrix[2, 0].Imaginary); Assert.AreEqual((Complex) 5.0, matrix[2, 1]); Assert.AreEqual((Complex) 6.0, matrix[2, 2]); } /// <summary> /// Can parse comma delimited complex data. /// </summary> [Test] public void CanParseComplex32CommaDelimitedData() { var data = "a,b,c" + Environment.NewLine + "(1,2)" + Environment.NewLine + "\"2.2\",0.3e1" + Environment.NewLine + "'(4,-5)',5,6" + Environment.NewLine; var reader = new DelimitedReader { Delimiter = ",", HasHeaderRow = true, FormatProvider = CultureInfo.InvariantCulture }; var matrix = reader.ReadMatrix<Complex32>(new MemoryStream(Encoding.UTF8.GetBytes(data))); Assert.AreEqual(3, matrix.RowCount); Assert.AreEqual(3, matrix.ColumnCount); Assert.AreEqual(1.0f, matrix[0, 0].Real); Assert.AreEqual(2.0f, matrix[0, 0].Imaginary); Assert.AreEqual((Complex32)0.0f, matrix[0, 1]); Assert.AreEqual((Complex32)0.0f, matrix[0, 2]); Assert.AreEqual((Complex32)2.2f, matrix[1, 0]); Assert.AreEqual((Complex32)3.0f, matrix[1, 1]); Assert.AreEqual((Complex32)0.0f, matrix[1, 2]); Assert.AreEqual(4.0f, matrix[2, 0].Real); Assert.AreEqual(-5.0f, matrix[2, 0].Imaginary); Assert.AreEqual((Complex32)5.0f, matrix[2, 1]); Assert.AreEqual((Complex32)6.0f, matrix[2, 2]); } /// <summary> /// Can parse comma delimited sparse data. /// </summary> [Test] public void CanParseSparseCommaDelimitedData() { var data = "a,b,c" + Environment.NewLine + "1" + Environment.NewLine + "\"2.2\",0.3e1" + Environment.NewLine + "'4',0,6" + Environment.NewLine; var matrix = DelimitedReader.Read<double>(new StringReader(data), true, ",", true, CultureInfo.InvariantCulture); Assert.IsTrue(matrix is LinearAlgebra.Double.SparseMatrix); Assert.AreEqual(3, matrix.RowCount); Assert.AreEqual(3, matrix.ColumnCount); Assert.AreEqual(1.0, matrix[0, 0]); Assert.AreEqual(0.0, matrix[0, 1]); Assert.AreEqual(0.0, matrix[0, 2]); Assert.AreEqual(2.2, matrix[1, 0]); Assert.AreEqual(3.0, matrix[1, 1]); Assert.AreEqual(0.0, matrix[1, 2]); Assert.AreEqual(4.0, matrix[2, 0]); Assert.AreEqual(0.0, matrix[2, 1]); Assert.AreEqual(6.0, matrix[2, 2]); } } }
41.178571
170
0.551412
[ "MIT" ]
artu001/mathnet-numerics-data
src/UnitTests/Text/DelimitedReaderTests.cs
10,377
C#
//------------------------------------------------------------------------------ // <auto-generated> // This code was generated by a tool. // Runtime Version:4.0.30319.42000 // // Changes to this file may cause incorrect behavior and will be lost if // the code is regenerated. // </auto-generated> //------------------------------------------------------------------------------ namespace ThumbnailSharp.Gui.Properties { [global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()] [global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "15.3.0.0")] internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase { private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings()))); public static Settings Default { get { return defaultInstance; } } } }
39.740741
151
0.583411
[ "MIT" ]
mirzaevolution/ThumbnailSharp.Client
ThumbnailSharp.Gui/Properties/Settings.Designer.cs
1,075
C#
using Modelo; using System; using System.Data; using System.Data.SqlClient; namespace DAL { public class DAO_ItensVenda { private DAO_Conexao conexao; public DAO_ItensVenda(DAO_Conexao con) { this.conexao = con; } //METODO INCLUIR public void Incluir(Model_ItensVenda modelo) { SqlCommand cmd = new SqlCommand(); cmd.Connection = conexao.ObjetoConexao; cmd.CommandText = "insert into ItensVenda (id_itensVenda, quantidade, valor, id_venda, id_produto)" + "values (@id_itensVenda, @quantidade, @valor, @id_venda, @id_produto)"; cmd.Parameters.AddWithValue("@id_itensVenda", modelo.IdItensVenda); cmd.Parameters.AddWithValue("@quantidade", modelo.Quantidade); cmd.Parameters.AddWithValue("@valor", modelo.Valor); cmd.Parameters.AddWithValue("@id_venda", modelo.IdVendaItensVendas); cmd.Parameters.AddWithValue("@id_produto", modelo.IdProdutoItensVenda); conexao.Conectar(); cmd.ExecuteNonQuery(); conexao.Desconectar(); } //METODO ALTERAR public void Alterar(Model_ItensVenda modelo) { SqlCommand cmd = new SqlCommand(); cmd.Connection = conexao.ObjetoConexao; cmd.CommandText = "UPDATE ItensVenda set quantidade = @quantidade, " + "valor = @valor where id_itensVenda = @id_itensVenda and id_venda = @id_venda and id_produto = @id_produto"; cmd.Parameters.AddWithValue("@id_itensVenda", modelo.IdItensVenda); cmd.Parameters.AddWithValue("@quantidade", modelo.Quantidade); cmd.Parameters.AddWithValue("@valor", modelo.Valor); cmd.Parameters.AddWithValue("@id_venda", modelo.IdVendaItensVendas); cmd.Parameters.AddWithValue("@id_produto", modelo.IdProdutoItensVenda); conexao.Conectar(); cmd.ExecuteNonQuery(); conexao.Desconectar(); } //METODO CARREGA MODELO public Model_ItensVenda CarregaModeloItensVenda(int idItensVenda, int idVenda, int idProduto) { Model_ItensVenda modelo = new Model_ItensVenda(); SqlCommand cmd = new SqlCommand(); cmd.Connection = conexao.ObjetoConexao; cmd.CommandText = "select * from ItensVenda where id_itensVenda = @id_itensVenda and id_Venda = @id_Venda and id_produto = @id_produto"; cmd.Parameters.AddWithValue("@id_itensVenda", idItensVenda); cmd.Parameters.AddWithValue("@id_Venda", idVenda); cmd.Parameters.AddWithValue("@id_produto", idProduto); conexao.Conectar(); SqlDataReader registro = cmd.ExecuteReader(); //SE EXITIR ALGUMA LINHA EXECUTAR if (registro.HasRows) { registro.Read(); modelo.IdItensVenda = idItensVenda; modelo.Quantidade = Convert.ToDouble(registro["quantidade"]); modelo.Valor = Convert.ToDouble(registro["valor"]); modelo.IdVendaItensVendas = idVenda; modelo.IdProdutoItensVenda = idProduto; } conexao.Desconectar(); return modelo; } //METODO EXCLUIR public void Excluir(Model_ItensVenda modelo) { SqlCommand cmd = new SqlCommand(); cmd.Connection = conexao.ObjetoConexao; cmd.CommandText = "delete from ItensVenda where id_itensVenda = @id_itensVenda and id_venda = @id_venda and id_produto = @id_produto"; cmd.Parameters.AddWithValue("@id_itensCompra", modelo.IdItensVenda); cmd.Parameters.AddWithValue("@id_venda", modelo.IdVendaItensVendas); cmd.Parameters.AddWithValue("@id_produto", modelo.IdProdutoItensVenda); conexao.Conectar(); cmd.ExecuteNonQuery(); conexao.Desconectar(); } //METODO EXCLUIR todos public void ExcluirTodosItens(int idVenda) { SqlCommand cmd = new SqlCommand(); cmd.Connection = conexao.ObjetoConexao; cmd.CommandText = "delete from ItensVenda where id_venda = @id_venda"; cmd.Parameters.AddWithValue("@id_venda", idVenda); conexao.Conectar(); cmd.ExecuteNonQuery(); conexao.Desconectar(); } //METODO LOCALIZAR public DataTable Localizar(int idVenda) { DataTable dt = new DataTable(); SqlDataAdapter da = default(SqlDataAdapter); da = new SqlDataAdapter("Select i.id_itensVenda, p.nome , i.quantidade, i.valor, i.id_venda, " + "i.id_produto from ItensVenda as i INNER JOIN Produto as p on p.id_produto = i.id_produto where i.id_venda = " + idVenda.ToString(), conexao.StringConexao); da.Fill(dt); return dt; } } }
42.364407
172
0.614923
[ "MIT" ]
lucasestevan/SistemaVendasC-
SistemaVendas/DAL/DAO_ItensVenda.cs
5,001
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 securityhub-2018-10-26.normal.json service model. */ using System; using System.Collections.Generic; using System.Xml.Serialization; using System.Text; using System.IO; using System.Net; using Amazon.Runtime; using Amazon.Runtime.Internal; namespace Amazon.SecurityHub.Model { /// <summary> /// A processor feature. /// </summary> public partial class AwsRdsDbProcessorFeature { private string _name; private string _value; /// <summary> /// Gets and sets the property Name. /// <para> /// The name of the processor feature. /// </para> /// </summary> public string Name { get { return this._name; } set { this._name = value; } } // Check to see if Name property is set internal bool IsSetName() { return this._name != null; } /// <summary> /// Gets and sets the property Value. /// <para> /// The value of the processor feature. /// </para> /// </summary> public string Value { get { return this._value; } set { this._value = value; } } // Check to see if Value property is set internal bool IsSetValue() { return this._value != null; } } }
26.486842
109
0.596622
[ "Apache-2.0" ]
ChristopherButtars/aws-sdk-net
sdk/src/Services/SecurityHub/Generated/Model/AwsRdsDbProcessorFeature.cs
2,013
C#
using System; namespace RuntimeEvents { /// <summary> /// Define a processor class that can be used to process the rendering of Parameter Attribute. This attribute should be attached to /// a /*INSERT HERE*/ class object /// </summary> [AttributeUsage(AttributeTargets.Class, AllowMultiple = false, Inherited = true)] public sealed class CustomParameterDrawerAttribute : Attribute { /*----------Properties----------*/ //PUBLIC /// <summary> /// The value type that the attached class will be used to process /// </summary> public Type DrawerType { get; private set; } /// <summary> /// Flags if children of the supplied type should also be handled by this drawer /// </summary> public bool HandleChildren { get; private set; } /*----------Functions----------*/ //PUBLIC /// <summary> /// Initialise this object with it's base values /// </summary> /// <param name="drawerType">The type object defining the value type that the attached drawer is responsible for</param> /// <param name="handleChildren">Flags if child classes of the drawer type should be handled by this drawer</param> public CustomParameterDrawerAttribute(Type drawerType, bool handleChildren = false) { DrawerType = drawerType; HandleChildren = handleChildren; } /// <summary> /// Override the default behaviour to base the hash code of the attribute off of the stored values /// </summary> /// <returns>Returns a combined hash to reflect the assigned values</returns> public override int GetHashCode() { unchecked { int hash = 17; hash = hash * 31 + DrawerType.GetHashCode(); hash = hash * 31 + HandleChildren.GetHashCode(); return hash; } } } }
41.956522
153
0.605699
[ "MIT" ]
MitchCroft/RuntimeEvent
RuntimeEvents/Assets/Plugins/RuntimeEvents/Attributes/CustomParameterDrawerAttribute.cs
1,930
C#
using RehabKiosk.Controls; using System; using System.Collections.Generic; using System.ComponentModel; using System.Linq; using System.Text; using System.Threading.Tasks; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Animation; using System.Windows.Media.Imaging; using System.Windows.Navigation; using System.Windows.Shapes; namespace RehabKiosk { /// <summary> /// Interaction logic for PopupMessageBox.xaml /// </summary> public partial class PopupMessageBox : UserControl, INotifyPropertyChanged, IInfoPopupChild { public class ActionEventArgs { public object Context { get; set; } public Results Result { get; set; } public int PromptIdentifier { get; set; } } public enum ButtonTypes { OK, YESNO }; public enum IconTypes { NONE, QUESTION, EXCLAMATION, INFO }; public enum Results { OK, YES, NO }; public event EventHandler<ActionEventArgs> PopupMessageBoxActionEvent; public event EventHandler CloseRequestEvent; #region NotifyProperty public event PropertyChangedEventHandler PropertyChanged; private void NotifyPropertyChanged(params string[] propertyNames) { foreach (var propertyName in propertyNames) NotifyPropertyChanged(propertyName); } private void NotifyPropertyChanged(string propertyName) { PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName)); } #endregion public PopupMessageBox(Popup popupHost, int promptIdentifier, object context, string msg, ButtonTypes type, IconTypes icon) { InitializeComponent(); DataContext = this; FontSize = IconFontSize = 20; PopupHost = popupHost; PromptIdentifier = promptIdentifier; Context = context; MessageText = msg; ButtonType = type; IconType = icon; } private void PopupMessageBox_Loaded(object sender, RoutedEventArgs e) { this.PreviewKeyDown += new KeyEventHandler(HandleEscapeKey); if (ButtonType == ButtonTypes.OK) OKButton.Focus(); else YesButton.Focus(); } private void PopupMessageBox_Unloaded(object sender, RoutedEventArgs e) { this.PreviewKeyDown -= new KeyEventHandler(HandleEscapeKey); } private string _messageText; public string MessageText { get { return _messageText; } set { _messageText = value; NotifyPropertyChanged("MessageText"); } } private IconTypes _iconType = IconTypes.NONE; public IconTypes IconType { get { return _iconType; } set { _iconType = value; NotifyPropertyChanged("IconType"); } } private double _iconFontSize = 12; public double IconFontSize { get { return _iconFontSize; } set { _iconFontSize = value; NotifyPropertyChanged("IconFontSize"); } } private ButtonTypes _buttonType = ButtonTypes.OK; public ButtonTypes ButtonType { get { return _buttonType; } set { _buttonType = value; NotifyPropertyChanged("ButtonType"); } } public Popup PopupHost { get; set; } public int PromptIdentifier { get; set; } public object Context { get; set; } private void HandleEscapeKey(object sender, KeyEventArgs e) { if (e.Key == Key.Escape) { if (ButtonType == ButtonTypes.OK) OkButton_Click(null, null); else NoButton_Click(null, null); } else { if (ButtonType == ButtonTypes.OK) { if (e.Key == Key.O) OkButton_Click(null, null); } else { if (e.Key == Key.Y) YesButton_Click(null, null); else if (e.Key == Key.N) NoButton_Click(null, null); } } } private void OkButton_Click(object sender, RoutedEventArgs e) { if(PopupHost != null) PopupHost.IsOpen = false; else CloseRequestEvent?.Invoke(this, null); PopupMessageBoxActionEvent?.Invoke(this, new ActionEventArgs() { Result = Results.OK, PromptIdentifier = this.PromptIdentifier, Context = this.Context }); } private void YesButton_Click(object sender, RoutedEventArgs e) { if (PopupHost != null) PopupHost.IsOpen = false; else CloseRequestEvent?.Invoke(this, null); PopupMessageBoxActionEvent?.Invoke(this, new ActionEventArgs() { Result = Results.YES, PromptIdentifier = this.PromptIdentifier, Context = this.Context }); } private void NoButton_Click(object sender, RoutedEventArgs e) { if (PopupHost != null) PopupHost.IsOpen = false; else CloseRequestEvent?.Invoke(this, null); PopupMessageBoxActionEvent?.Invoke(this, new ActionEventArgs() { Result = Results.NO, PromptIdentifier = this.PromptIdentifier, Context = this.Context }); } } }
27.088106
167
0.548057
[ "MIT" ]
SiliconSquared/ChildrensRehab
Views/PopupMessageBox.xaml.cs
6,151
C#
using System; using InvertedTomato.IO.Buffers; namespace InvertedTomato { public static class ULongBufferExtensions { public static void Seed(this Buffer<UInt64> target, UInt64 start, UInt64 end) { for (var i = start; i <= end; i++) { target.Enqueue(i); } } } }
23.25
81
0.691756
[ "MIT" ]
invertedtomato/integer-compression
Test/ULongBufferExtensions.cs
281
C#
using DocuSign.eSign.Client; using System.Collections.Generic; namespace SdkTests { class TestConfig { public string Username { get; set; } public string Password { get; set; } public string IntegratorKey { get; set; } public string Host { get; set; } public ApiClient ApiClient { get; set; } //public Configuration Configuration { get; set; } public string AccountId { get; set; } public string RecipientEmail { get; set; } public string RecipientName { get; set; } public string TemplateRoleName { get; set; } public string TemplateId { get; set; } public string EnvelopeId { get; set; } public string ReturnUrl { get; set; } public string UserId { get; set; } public string OAuthBasePath { get; set; } public string PrivateKeyFilename { get; set; } public int ExpiresInHours { get; set; } public List<string> EnvelopeIdsList { get; set; } public string IntegratorKeyNoConsent { get; set; } public string PrivateKeyNoConsentFilename { get; set; } public string BrandLogo { get; set; } public string BrandId { get; set; } public TestConfig(string username = null, string password = null, string integratorKey = null, string host = null, string recipientEmail = null, string recipientName = null, string templateRoleName = null, string templateId = null, string returnUrl = null) { this.Host = (host != null) ? host : "https://demo.docusign.net/restapi"; this.Username = (username != null) ? username : "node_sdk@mailinator.com"; this.Password = (password != null) ? password : "qweqweasdasd"; this.IntegratorKey = (integratorKey != null) ? integratorKey : "ae30ea4e-3959-4d1c-b867-fcb57d2dc4df"; this.RecipientEmail = (recipientEmail != null) ? recipientEmail : "node_sdk@mailinator.com"; this.RecipientName = (recipientName != null) ? recipientName : "Pat Developer"; this.TemplateRoleName = (templateRoleName != null) ? templateRoleName : "bob"; this.TemplateId = (templateId != null) ? templateId : "cf2a46c2-8d6e-4258-9d62-752547b1a419"; this.ReturnUrl = (returnUrl != null) ? returnUrl : "https://www.docusign.com/devcenter"; this.UserId = "fcc5726c-cd73-4844-b580-40bbbe6ca126"; this.OAuthBasePath = "account-d.docusign.com"; this.PrivateKeyFilename = "../../docs/private.pem"; this.ExpiresInHours = 1; this.EnvelopeIdsList = new List<string>(); this.IntegratorKeyNoConsent = "66750331-ee4b-4ab8-b8ee-6c1a413a6096"; this.PrivateKeyNoConsentFilename = "../../docs/privateKeyConsentReq.pem"; this.BrandLogo = "iVBORw0KGgoAAAANSUhEUgAAASgAAACrCAMAAADiivHpAAAAh1BMVEX////u7u4AAADt7e339/f09PT5+fnx8fH8/PxhYWFoaGjk5OTq6uq0tLQyMjLm5ua8vLzLy8t1dXWfn5+srKwTExNYWFhGRkbU1NQdHR3a2trGxsbd3d2Kioqjo6NTU1NtbW0mJiaGhoaSkpJ+fn4iIiItLS0XFxc8PDxMTEw5OTlDQ0MLCwtHmVpDAAAU9klEQVR4nO1di3aqOhAlkpcVKz5qra9a7enr9P+/7xJIYCYECIpVz23WumvdHOnOZBMmM5NJEgRp4USVUKYVGaYVnv2UVWhWSR8jLKuItCKyCst+yio0g/PEdsEJCMdawZ1H1OCXqF+ifom6FaKcPfu/EBX6tY57FsLWQ9h6CFtvwtZwJKmFoZOoVnDOd1oWNWwnasDTQllaUIVmNc+KC6E9HJeSrcfjNZOS1sO1w6Yni+ogPoTEh0eNkcqXGrpeKi8qo8PfXlr+HkYpXFj5oZbhThI1bML2/ZQbWiewddKsJpxEje56oNyNDBzCvoyoV0QUY/ueVfaC/RJlwTExtWlS5UDYL1FgUhZs+Obiqdd7GTJxHUSFaclnaFXMDJ1W8tbTYlpPi2k9Lab1tFAIxyBc3jqEo+NPN02qfI4pwq6GO11UV8+NqDItXKhCdIWkFZ79llVoWgmyxxioCJFVGKhI2gSXVYK0Qkc7NIYm2+0Eja/dIMEjggQXFDVj+tgJv3r0k/rRD7BZtEE0xdkv8Qv8103ETrRNyqK2NTj1E6RF6x36eoLNHiAjU6MzKFbu31vBrsOFuUzrNL6HdLyOWOHrsegV/nYf05sjqjOnePQMqegvqUBOMVv24e/Pg2sgqs2HT6o9zTZeBEUj5mPBhQ0n6OIRjTh6IVHTKtD9goN5BVdo9lxWYVmFlSsCwclquEBukQ4aBoEDLunmEOmwrQx+XNTspxo7qmyckM7sqGD4DvuvDHAMJ80YYeQAn3wYSgdcV3YUEtWyo3w/5U7N3SX6onYDVhrwsoBjgwl8+u/yR0W9pAtDkIH5udZTRBVRiQgDpPXvyP+DKPQpPa3Sb6WeqARuhQzQg/zXiWJ0CDvcm1XAYaJS7Bn6wyGeI3+AqDbK/FQNKSj2TF4lhAsgnIRwGhuZEy8xFT+qzGGwWHAQLEYVRqX6f+moMAke05USnEgqMlhjAzMK1A9ecEI9GUQoAvq8DpIpvEFU5sCmtaK64fIlBjhcW1nmoe/oLxmYOTaD2HAVpnipBm7xgUYk03/UUlQo3bU5xVYE8yEG2P7reol8MTLApmkE9Fp9vbathyqCiQ3MUxZA0az5PmSJe3KlRLV1igUd/4WdSwzMU4iyDNCPMf1Joho8TY9ZFLUOP/xgjXTw5yKZrlzYAmIziG3pkcRXxgboMuhIVF8dRSSsZE9IckzroMJRBPMtVrEUMwQQdjVRCFtJJzgOZG14or7kKaKinkvYc0PUee0oYa1CTRnExnABhHPZUUhUtv1GwEKceXGhFfEtzV3BYrRK8DpiVWOkFs65XMWiPR6qBvsoUZtp8CXqGL9gUY5g1iypN7gw5XU9ipXf8+IEUWtoOLuvJ5CB+ThOlVOXRBFhLQi+ihskSiLl9BRb6rkTolQl/oNUlbyUU0yghvSOcHJb/sAVkkRwpKUyL+C21hvhJexOFrVp94UHYxTBnEQBZR5/l+Zs6S4pT9SrscRpjZAB+jgO/P6yXQkQ8YGLeAKIzyr5CC0Rn44/gnTsfEkJfKmkhG0mfEqW49l0ethsDtPpbLwktMaYKOCUVp/DFu8yKZCorjFSfCqV2IWohihSVhPH+gUxFPptjLVOJbZYbR7RgkviOf/drESBXeNmyGCMDNA4sT99lW8T9tmIQkp8Fni4RzyItpXpLI/byEhXLyoKnU79k4TOSFStUwwjthvugc3E8LlXWz6HaeZdU2ckDCvMLjSifA1YsQSqYl2JXfh6LDx8l5gple9DlHjS9aJK7H2vRYOonkQRiyiHMkczNIWVag0pclXxMabNM7QQBxcvrnIw3ayZdwiI59yzxgk/I6qp555OcbUdRVxdzxVFrF5xg3FC+OrBzYpzVMU8nciq4VJR86lk2CBqo1Ns0drtp6xD2t9R1notNhuVNHh/M1ytFovlYrWa7fv2r58DlhgDTaISTf5Hg6gXdYpHuksLj9Y5XuHr3cUZuzpvUJXBzFLzMy6aRV3oh0e1ol7W19N93wXNRDG0rt6PmX4MwCm/LdqidZe7NMOlTtTkj3bg27tSonS8YIUCmC5sPoIG4n5AhbVWVmSz8DH8Bt8G3AGHw1ur7NHXbokqK3NyvDLX73Jd6Wka7DXo+4ElqqfKKU6UkuBL6KEsHXBIVL4G47qdMneJapS5Yz+R754mvKCqVlO1HROVfsHYAbC25spjLsPhSrB6Kv5iEdSLyiP9mQY1onpUMHYAxoiPHVXraTL9kTAEV7KjxLjo9ZATp21iha2FABGCFQtrYzxM6z1WZ0y0tqN0Z0jpUz7C16M5UQRqNAtbLPIuf46Y77oeB772gtWJmhNFvZRvnagA++eJEuvcZ9kwBdGcypBW2CDX/99rcRNEVTrFPkQRkvd3Vl4pFkK3yoWwiEoayq2q+5DcAlEnjSiWO65xaXGLhovZYdKfz/uT6XDAmLAXoPK/vWOXIspXmZdm0ZbKvIhwxzZcNOsj1+9rs6AFdgaXW6lTJGpXyrzGfw9QOrYjN9s3HVtVzBsf8So4lhsGW46w+RIFvnX5jNWwyjPHeVyY6WNWJSrXjtRdYIsqHZXqrHTc8273S2miBtAyR9jMrDpseAFHCV3e9dzlS2UgmvVUaHc+hZWiDgxRdaK2jkjWax3SzoVxEQWxmfnw5iyHk4nirotK9QeMqpZwssfdsjLZlTcQdQ2+XhNRJrrwQOAAHaHsqXJJvVsUa/ha1Pl6t09UnsW5gNPiuNdUNlbu5qxW1B8hKnQ84UVUtY4qsIVxhSdwSR2tbj1PV+tRFI2WqykMRaG1qD2tF7WJqCP3YrXT/SfNetwMKFZgQ57etkIZWoKpv0lk37p2rquk6fr9UtWznmsKbNyLZWY9M0a6tKOo246iuq9TZl5qxAqenoZpuKVwigljsyfMUu/PKpWOFGE+1axx7f8Vp1hPeU8kz+EEq1t7nO5iFptQ6lBqZqok41V/N5lMdtkqNJvcTVT5d1yYezOgcmyRf1wrgy0sbPBpToSGE3oKHKaicu1k/ytE5dG6qMDOx0uieKrCLObPPsY5nEVU9n0+XB9Rx0UPgn324yvNsQcFTzYciEdlc+WMFhmflyQKzv41ROG4iKrBDSbAKYat6xlab6xaiBzbrOtlY4VAuAw768wi0WBqL20Oh4miVUQlItUcjNV2L0x1sNgzgA6C3O6Yefac1J/QV2AQqLE0N0F9zJyvBiBMnohqFNeMq+cCQ5QrZu4KwTeGyZ0x8/LH5L1fqp1TrOe8g3mpIdcm5b10DGeYwwkrWeqbXpCaZUemZEP1PTAxv26c4rOeSFZnmevfFqb13E4fuzLNKpJdw15TmTRGD67d19O2IzetMx0y+DTYXlnBjUS93jpRWsM+561zbVat2hDVPKJeLxA96NQp1pp7b7DNl/ftnnLPSFTbbJaWIwpW8CYkvxGlZ/SZwRax6Rje4ITeup2fdwRRldhHbVo7v1NsjkQcC+NpahU1FD4rxTlcI1E7xrXzfZtOscnyiYjB1v+wFH4rxRmcfL9XRduuL1+q8qUpSisvr+x6XJgjiArNTyQnSvdPtN0qG1Au9WcbqwoPst0k72mFsyvy9Y4ZUVSvoLCcqMznf+Kt9xT/204xy8zwB5oTlT16T2+MKE9L/2inmGUO8DvNsbVioSDtB8AJaJvYm9Y8iap1ilsfENHpDiRNVFje3hRkn963MD9pol6OEcDoqJlMkQxR+leubYh+t30rf0wnHNNd4xSbdQeDzfWGvqDZ4MQbQlTFOMWZi5whPUjdiQ5Wisvj7+dcGG0NDEzrVMcOiLszVZb5YTrdbmc6MrpTla0+yfN7qyrb1a37evvsp4Vpnb3m/9CGqF5Tufnogd51NcyJ0vGpaXD7TnGnRGm1cjCtm0zOj1shCnlvpx7TbREFsfXybd+0Hprl0IG3u6USxtsTVSFq65M0dNcJJD6roGFx8nKVDrm9kfylaiU1oQiOFXDFITY5nGwkatKdr1eIWpSzWuYpgrY4e2leU4ptsqjNPgcvp7iRqDtElMcx3WVRL7sAynQe2LY4QkwHh3dBE1GgM6vxKo5jHaI5pJVVdobXw2KcVOKxuB5f7yiihNbmc5pjm+3H4yaiRJaPnlWkEDR3YVQyjsxdmDTt5Mad4uRHTcugWADV//JN64mSb49LemNOMSYqhK2HkCiHMWGmRPXtWRtrHzNsCAedYpUgOwnZyU7xCYsB6rfatd92q6vSROdcCFL37ovnCGZnbW+ujhhxL9ZKs19hKvODM82+mFmgnss/PdOqnmD7skJUr1Vvu7NN3uBpTnEIsfVKd+rFZNj5P/UeI+F2ikWUZ2/er9T2xxRO67ttlginiTJZHMc5xWGJBhTj+clkV6pT7ud562GR6/s+Ztn6OCAq+Y+O4WaG+ZplcDEiSudH8X8lKzjfprcAsbMio+4VrVBl2Pgw2KRsdFIil2EURXqXJpckqUTiXyEqtzkfoc0HtiykJwWCEcUcefrfM9kk6u0TZUypZLYC2HBr9d0wlEydCcVkNCyde6Bpbjoh/wadYntHsxlSPQbh8Of1/dnf7fqf6MCW+zV6Js3lrL5z4QSnGC2XWk5xUxq5bzq2qnA9CAR3w+X5mP0AwEnnhXFwnDEq8Rln02TSrhSVC90IrxHVI4Ee78UKKj+mtvlWpCk1Uf2/2Ws2g9hy/dWrKUP13SduCzyW+UUHAGs3Ntr7lUOnU+xrcOonSAuiTtgBykxPlwCbWQf6obITWk1Y957MZZWo1+PrnbJVNk8bjzA2cx8j1V/CnoVwiqwU9XqIOmXzdT7JPYkAjKjkR26fWNN72S9hzxRcvmdvHlyIqDY6qnIWrXWKNXZktre8MWuGZnQw3D/rvQxf/elC5Kf/Grh8PP6JTiHqKKcYqft2s15pCmya9VSF5cdD/AlLW7uSyYymB7Ww9EYKe1tvsblxwWqmqcpZT5wy61XbUUcc091gR2XYxe6WMYKDo5+4FheKvbJxnahnWlyoV88Vn/JxlrnBLqa4WdOAB9iy0OTTWlG7tsw1ti9RHbgwOXYxz+9kBVGldb1lcfjwoV7UW/L1mlovmPpe+REFtqhvGkS9BaJ2nkTB41/nA203VxIl0GUwhyZRDVG7bonqVJlrD2VRq8zTP4IHwN6pWy2rVooJozHcop6HWaqVuZ5XJ7WitnaKu4qZKwRzCO00aIpKU3goWa/3HMtAIjj9mAwE3oK9cJ5fhgQyTvah25g5GiPmpZaP0vY6ptsEnN4ZqR5/KjqtsDk6Wrv3OibKciqWqxIbiI9ifBTJJ3XAIVHVQZ06erwyEXaXqKHPITbnO6Zbm3qJUQxWLN3Y0r4xr9d73A/HOiMvseDHs70dVNh6iCqMe9ATfsqXkCZRz0CU2Z/Qm4fMo3XhOnb64f7v3y/X0bifxENUFpqBumcXJ6om8yHfJdzbsqbjotVP+MbKuvIn5o1wIWOFMTu4yIjyNWBpIehLfqd3zQwt+NB1XEapvMyox13q8ELILW0QteXNQIYorMxDrCHBLNpwkQEJgIr+HEBst/ZNdErccO67mhRpYT9Uww3AIc3zzu9cCKEBcerigoKDRo+6gbhZ1mB9uC+Rk5e3Q37ZWaWoakMpukzu60ruriqP/uJjImiAHARrxOaJIbDc3jlCnN/97ZKzmgt0DBzDZ3U9h/lqaI2obXTKOW4aovgSyxl3Ydtwis/ReLqf379/J+X9fr6fJrYCTTOjGoiSAZ/hCy+Z8BPVi6hz+Hp6d4F1paJrxdKCCwv3jlIhzH01rp45RF2iI80mA+Yt6qXvrrIu2r2Lmoiy4arSp12iRuhk9Gdz43jXRNVpyLD1nQuFhlzZVyo6ztXGcAGEc6dPO+YxfHfq/cqFfZRTTKx5p8sdSLBIidfqZuouKuZzhZV/SbzXGb63kctOGwAlQMQ7X2q1U1w54avxR1i0sV+220Yzwxk6rtU58XCM4IuYNqPUGfc0+RrtqDNuvibYmCDWnd7ztRu79Q5QLap1tVekldP13FPcpvUFvkDOnCR7MlHEuhDyb3Hj+PUQ1e7A3Bgd6HcIWQn7CKJYaF8Iefo77YSooy7/TfdkBPjyrd7TTFmDLmyfvTCZqMI6TvEgHXBnIqpGmcNZ1DlDZ61XakhpG6Cr4k5vCOe5wYkTurINzM5EhT23juluIh69VOfZLFkFLeWVxsgA6d3+SIoqOA7hHHdZC9cM4RJVlrG9RLV7jny9ro7prlETeCZ/jZhNlAuujG1d43w/PoOoP+UUE7eaoNgAnTKWE+XtwjCG0xi3aAh0JurP+Xrl1mXpTu8/MRftiBI8RpHjfeS8cfy2iUqxrTu9Hxcq68ifqAW6Zu5uTc8oagVR3W1Cwh9+CFtXFetO7wkDcEEVURk2s24jLt843q2oNjZcDjWLtbJcyRZURfYYF3BB1VHBcLBCUR5Beqe3pA1wgkrrxvGH2CwYV4qqW8Vrv61ExXCBIf58dpQV6bCitr0ZQ5kKzoA9xWulB8GOyiZoZ0f9nFNcZe4yfKf3feNWWWxaTJRp8UOi/pxT7MQW1DJAowK7TFSINsXM1/QnRb0sUQobj5I9ryKK7+Fzb+MLiHpZoqwLTHpbl+PArEQOtbGjO1v7KKIcKs2lIZuUebvlUqTVX9SdQkCZk1DQGK23Z0GCE1LD2s47SJmjVG/HJiTWlI599NUYaps0WkD5XAZ4LxayuXYhL19XdfSFI7aojT1v2C9FTrPiStho9Kv3iMmYiMLgFBOLRJWneAlRL+DClFtPCs78Oehhw63PssC+lKiXJErDobDC92Y1GK02aBVqC7H/x0QFI3szOiqvJl3xaok62tN0t172NIvg7mJeRdN8QT2yWc4uKkE3NppKuuVKHaWdqvu0QtMKyR7joCJlVuGgoqcSC04AOIytZqLVh4umjxUv4AiEO15UcZyohvgG17A7p7hs+Gg4nLqjysPMgd2VyXcDTrGNbeK5oXUgxCaigSywfeH+ORfGJirRF4NNbiu8bAa0YUn9/0qUUCubZDE8TCaH4SI7hey2iWq7uOVPVNEzBHdNRHla+rhnqUtxetg6XykGcI4jnE5ySsqi5srcD9t1dxVt2oREq//oBLhzYp8OV+cUw5fakafpfKltjumuv1+qK1Fdn4rvp3xGF+bEZNcfEfWXqF+ifon6JeqqifoPF133T1SIQtEAAAAASUVORK5CYII="; this.BrandId = "fe0dd2a9-263f-4d2d-ad8b-3c4b9468793b"; //this.Configuration = new Configuration(); } } }
157.636364
7,460
0.874952
[ "MIT" ]
Shyam200408/docusign-csharp-client
test/SdkTests/TestConfig.cs
10,404
C#
using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace AppBlocks.CodeGeneration.Roslyn.Common { internal static class ExpressionSyntaxExtensions { public static ExpressionSyntax Parenthesize( this ExpressionSyntax expression, bool includeElasticTrivia = true) { // a 'ref' expression should never be parenthesized. It fundamentally breaks the code. // This is because, from the language's perspective there is no such thing as a ref // expression. instead, there are constructs like ```return ref expr``` or // ```x ? ref expr1 : ref expr2```, or ```ref int a = ref expr``` in these cases, the // ref's do not belong to the exprs, but instead belong to the parent construct. i.e. // ```return ref``` or ``` ? ref ... : ref ... ``` or ``` ... = ref ...```. For // parsing convenience, and to prevent having to update all these constructs, we settled // on a ref-expression node. But this node isn't a true expression that be operated // on like with everything else. if (expression.IsKind(SyntaxKind.RefExpression)) { return expression; } return ParenthesizeWorker(expression, includeElasticTrivia); } private static ExpressionSyntax ParenthesizeWorker( this ExpressionSyntax expression, bool includeElasticTrivia) { var withoutTrivia = expression.WithoutTrivia(); var parenthesized = includeElasticTrivia ? SyntaxFactory.ParenthesizedExpression(withoutTrivia) : SyntaxFactory.ParenthesizedExpression( SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.OpenParenToken, SyntaxTriviaList.Empty), withoutTrivia, SyntaxFactory.Token(SyntaxTriviaList.Empty, SyntaxKind.CloseParenToken, SyntaxTriviaList.Empty)); return parenthesized.WithTriviaFrom(expression); } } }
41.795455
102
0.740076
[ "MIT" ]
as-ivanov/AppBlocks
src/AppBlocks.CodeGeneration.Roslyn.Common/ExpressionSyntaxExtensions.cs
1,839
C#
#region Using directives using System; using System.Collections.Generic; using System.Linq; using FpML.V5r10.Reporting; using FpML.V5r10.Reporting.ModelFramework; using Orion.Analytics.Interpolations; using Orion.Analytics.Interpolations.Points; using Orion.Analytics.Interpolations.Spaces; #endregion namespace Orion.CurveEngine.PricingStructures.Interpolators { /// <summary> /// The vol surface interpolator /// </summary> public class VolCurveInterpolator : InterpolatedCurve { /// <summary> /// VolSurfaceInterpolator /// </summary> /// <param name="discreteCurve"></param> /// <param name="interpolation"></param> /// <param name="allowExtrapolation"></param> public VolCurveInterpolator(IDiscreteSpace discreteCurve, InterpolationMethod interpolation, bool allowExtrapolation) : base(discreteCurve, InterpolationFactory.Create(interpolation.Value), allowExtrapolation) { } /// <summary> /// Builds a raw volatility surface from basic data types. /// </summary> /// <param name="data"></param> /// <param name="interpolation"></param> /// <param name="allowExtrapolation"></param> /// <param name="baseDate"></param> public VolCurveInterpolator(MultiDimensionalPricingData data, InterpolationMethod interpolation, bool allowExtrapolation, DateTime baseDate) : base(ProcessMultiDimensionalPricingData(data, baseDate), InterpolationFactory.Create(interpolation.Value), allowExtrapolation) { } /// <summary> /// Builds a raw volatility surface from basic data types. /// </summary> /// <param name="timesAndVolatilities">The volatility curve.</param> /// <param name="interpolation">The interpolation function.</param> /// <param name="allowExtrapolation">The extrapolation flag.</param> public VolCurveInterpolator(IList<Tuple<double, double>> timesAndVolatilities, InterpolationMethod interpolation, bool allowExtrapolation) : base(new DiscreteCurve(ProcessTupleListElement1(timesAndVolatilities), ProcessTupleListElement2(timesAndVolatilities)), InterpolationFactory.Create(interpolation.Value), allowExtrapolation) { } internal static double[] ProcessTupleListElement1(IList<Tuple<double, double>> timesAndVolatilities) { return timesAndVolatilities.Select(tuple => tuple.Item1).ToArray(); } internal static double[] ProcessTupleListElement2(IList<Tuple<double, double>> timesAndVolatilities) { return timesAndVolatilities.Select(tuple => tuple.Item2).ToArray(); } internal static DiscreteSurface ProcessMultiDimensionalPricingData(MultiDimensionalPricingData data, DateTime baseDate) { var points = data.point.Select(point => new PricingDataPoint2D(point, baseDate)).Cast<IPoint>().ToList(); var result = new DiscreteSurface(points); return result; } } }
42.861111
203
0.687946
[ "BSD-3-Clause" ]
mmrath/Highlander.Net
FpML.V5r10.Components/CurveEngine/PricingStructures/Interpolators/VolCurveInterpolator.cs
3,086
C#
using System.Linq; using System.Threading.Tasks; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; using Microsoft.EntityFrameworkCore; using Test_Project_Hotel.Data; using Test_Project_Hotel.ViewModels.Workers; using Test_Project_Hotel.Models; using System.Collections.Generic; using Test_Project_Hotel.ViewModels; namespace Test_Project_Hotel.Controllers { [Authorize] public class WorkersController : Controller { HotelContext db; public WorkersController(HotelContext context) { db = context; } public async Task<IActionResult> Index(string fio, int page = 1, WorkerSortState sortOrder = WorkerSortState.FIOAsc) { int pageSize = 5; //фильтрация IQueryable<Worker> workers = db.Workers; if (!string.IsNullOrEmpty(fio)) { workers = workers.Where(p => p.WorkerFIO.Contains(fio)); } // сортировка switch (sortOrder) { case WorkerSortState.FIODesc: workers = workers.OrderByDescending(s => s.WorkerFIO); break; case WorkerSortState.PostAsc: workers = workers.OrderBy(s => s.WorkerPost); break; case WorkerSortState.PostDesc: workers = workers.OrderByDescending(s => s.WorkerPost); break; default: workers = workers.OrderBy(s => s.WorkerFIO); break; } // пагинация var count = await workers.CountAsync(); var items = await workers.Skip((page - 1) * pageSize).Take(pageSize).ToListAsync(); // формируем модель представления WorkersViewModel viewModel = new WorkersViewModel { PageViewModel = new PageViewModel(count, page, pageSize), WorkerSortViewModel = new WorkerSortViewModel(sortOrder), WorkerFilterViewModel = new WorkerFilterViewModel(fio), Workers = items }; return View(viewModel); } public IActionResult Create() { return View(); } [HttpPost] public async Task<IActionResult> Create(CreateWorkerViewModel model) { int er = 0; if (ModelState.IsValid && (er = db.Workers.Count(p => p.WorkerFIO == model.WorkerFIO)) == 0) { Worker worker = new Worker { WorkerFIO = model.WorkerFIO, WorkerPost = model.WorkerPost }; await db.Workers.AddAsync(worker); await db.SaveChangesAsync(); return RedirectToAction("Index"); } if (er != 0) ModelState.AddModelError("WorkerFIO", "Record with the same FIO already exists"); return View(model); } public async Task<IActionResult> Edit(int? id) { if (id != null) { Worker worker = await db.Workers.FirstOrDefaultAsync(t => t.WorkerID == id); if (worker == null) { ErrorViewModel error = new ErrorViewModel { RequestId = "Error! There is no record in the database with the id passed = " + id }; return View("Error", error); } EditWorkerViewModel model = new EditWorkerViewModel { Id = worker.WorkerID, WorkerFIO = worker.WorkerFIO, WorkerPost = worker.WorkerPost }; return View(model); } else { ErrorViewModel error = new ErrorViewModel { RequestId = "Error! Missing id in request parameters" }; return View("Error", error); } } [HttpPost] public async Task<IActionResult> Edit(EditWorkerViewModel model) { int er = 0; Worker worker = await db.Workers.FirstOrDefaultAsync(t => t.WorkerID == model.Id); if (ModelState.IsValid && (model.WorkerFIO == worker.WorkerFIO || (er = db.Workers.Count(p => p.WorkerFIO == model.WorkerFIO)) == 0)) { if (worker == null) { ErrorViewModel error = new ErrorViewModel { RequestId = "Error! Empty model was sent" }; return View("Error", error); } worker.WorkerFIO = model.WorkerFIO; worker.WorkerPost = model.WorkerPost; await db.SaveChangesAsync(); return RedirectToAction("Index"); } if (er != 0) ModelState.AddModelError("WorkerFIO", "Record with the same FIO already exists"); return View(model); } [HttpPost] public async Task<IActionResult> Delete(int id) { Worker worker = await db.Workers.FirstOrDefaultAsync(t => t.WorkerID == id); db.Workers.Remove(worker); await db.SaveChangesAsync(); return RedirectToAction("Index"); } public IActionResult AccessDenied(string returnUrl = null) { ErrorViewModel error = new ErrorViewModel { RequestId = "For admin access only" }; return View("Error", error); } } }
34.866667
145
0.516252
[ "Apache-2.0" ]
Nikan888/CWorkASPNet
Test_Project_Hotel/Controllers/WorkersController.cs
5,812
C#
/******************************************************************* * Copyright(c) * 文件名称: iOSAlbum.cs * 简要描述: * 作者: 千喜 * 邮箱: 2470460089@qq.com ******************************************************************/ namespace AFramework { #if UNITY_IPHONE using System.Runtime.InteropServices; public class iOSAlbum { [DllImport("__Internal")] public static extern void iosOpenAlbum(); [DllImport("__Internal")] public static extern void iosSaveImageToAlbum(string sourcePathP); [DllImport("__Internal")] public static extern void iosSaveVideoToAlbum(string sourcePathP); [DllImport("__Internal")] public static extern void iosGetPhotoPermission(string msgPrefix); [DllImport("__Internal")] public static extern void iosGetRecordPermission(); [DllImport("__Internal")] public static extern void iosGetVideoRecordPermission(); } #endif }
29.71875
74
0.582545
[ "Apache-2.0" ]
webloverand/AFramework
AFramework/Assets/Scripts/AFramework/Runtime/6.Native/iOSAdapter/iOSAlbum.cs
979
C#
/* * convertapi * * Convert API lets you effortlessly convert file formats and types. * * OpenAPI spec version: v1 * * Generated by: https://github.com/swagger-api/swagger-codegen.git */ using System; using System.Linq; using System.IO; using System.Text; using System.Collections; using System.Collections.Generic; using System.Collections.ObjectModel; using System.Runtime.Serialization; using Newtonsoft.Json; using Newtonsoft.Json.Converters; using SwaggerDateConverter = Cloudmersive.APIClient.NETCore.DocumentAndDataConvert.Client.SwaggerDateConverter; namespace Cloudmersive.APIClient.NETCore.DocumentAndDataConvert.Model { /// <summary> /// Result of replacing a string /// </summary> [DataContract] public partial class ReplaceStringSimpleResponse : IEquatable<ReplaceStringSimpleResponse> { /// <summary> /// Initializes a new instance of the <see cref="ReplaceStringSimpleResponse" /> class. /// </summary> /// <param name="successful">True if successful, false otherwise.</param> /// <param name="textContentResult">Result of performing a replace string operation.</param> public ReplaceStringSimpleResponse(bool? successful = default(bool?), string textContentResult = default(string)) { this.Successful = successful; this.TextContentResult = textContentResult; } /// <summary> /// True if successful, false otherwise /// </summary> /// <value>True if successful, false otherwise</value> [DataMember(Name="Successful", EmitDefaultValue=false)] public bool? Successful { get; set; } /// <summary> /// Result of performing a replace string operation /// </summary> /// <value>Result of performing a replace string operation</value> [DataMember(Name="TextContentResult", EmitDefaultValue=false)] public string TextContentResult { get; set; } /// <summary> /// Returns the string presentation of the object /// </summary> /// <returns>String presentation of the object</returns> public override string ToString() { var sb = new StringBuilder(); sb.Append("class ReplaceStringSimpleResponse {\n"); sb.Append(" Successful: ").Append(Successful).Append("\n"); sb.Append(" TextContentResult: ").Append(TextContentResult).Append("\n"); sb.Append("}\n"); return sb.ToString(); } /// <summary> /// Returns the JSON string presentation of the object /// </summary> /// <returns>JSON string presentation of the object</returns> public virtual string ToJson() { return JsonConvert.SerializeObject(this, Formatting.Indented); } /// <summary> /// Returns true if objects are equal /// </summary> /// <param name="input">Object to be compared</param> /// <returns>Boolean</returns> public override bool Equals(object input) { return this.Equals(input as ReplaceStringSimpleResponse); } /// <summary> /// Returns true if ReplaceStringSimpleResponse instances are equal /// </summary> /// <param name="input">Instance of ReplaceStringSimpleResponse to be compared</param> /// <returns>Boolean</returns> public bool Equals(ReplaceStringSimpleResponse input) { if (input == null) return false; return ( this.Successful == input.Successful || (this.Successful != null && this.Successful.Equals(input.Successful)) ) && ( this.TextContentResult == input.TextContentResult || (this.TextContentResult != null && this.TextContentResult.Equals(input.TextContentResult)) ); } /// <summary> /// Gets the hash code /// </summary> /// <returns>Hash code</returns> public override int GetHashCode() { unchecked // Overflow is fine, just wrap { int hashCode = 41; if (this.Successful != null) hashCode = hashCode * 59 + this.Successful.GetHashCode(); if (this.TextContentResult != null) hashCode = hashCode * 59 + this.TextContentResult.GetHashCode(); return hashCode; } } } }
35.572519
121
0.589914
[ "Apache-2.0" ]
Cloudmersive/Cloudmersive.APIClient.NETCore.DocumentAndDataConvert
client/src/Cloudmersive.APIClient.NETCore.DocumentAndDataConvert/Model/ReplaceStringSimpleResponse.cs
4,660
C#
foreach (var file in Directory.GetFiles("c:\\ImgRoute\\Caixa9 D1\\", "*.*")) { var imag = Path.GetFileNameWithoutExtension(file); if (imag.Length == 16) { //("Numero do auto correto"); } else { //("Numero do auto invalido"); } } //https://pt.stackoverflow.com/q/46191/101
27.727273
78
0.593443
[ "MIT" ]
Everton75/estudo
CSharp/IO/GetFilesInDir.cs
305
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; namespace iHospital.Models { public class AppointmentViewModel { public string Id { get; set; } public string PatientFName { get; set; } public string PatientLName { get; set; } public string PatientPhone { get; set; } public string DoctorFName { get; set; } public string DoctorLName { get; set; } public string DoctorPhone { get; set; } public string TimeStart { get; set; } public string TimeEnd { get; set; } public string MedicalProblem { get; set; } public string DateModified { get; set; } } }
26.923077
50
0.637143
[ "MIT" ]
nhatpk/iHospital
iHospital/Models/AppointmentViewModels.cs
702
C#
using LogicMonitor.Api.Attributes; using LogicMonitor.Api.Collectors; using LogicMonitor.Api.Converters; using LogicMonitor.Api.Filters; using LogicMonitor.Api.LogicModules; using LogicMonitor.Api.OpsNotes; using Microsoft.Extensions.Logging; using Microsoft.Extensions.Logging.Abstractions; using Newtonsoft.Json; using Newtonsoft.Json.Linq; using System; using System.Collections.Generic; using System.Diagnostics; using System.IO; using System.Linq; using System.Net; using System.Net.Http; using System.Net.Http.Headers; using System.Reflection; using System.Runtime.Serialization; using System.Text; using System.Text.RegularExpressions; using System.Threading; using System.Threading.Tasks; namespace LogicMonitor.Api { /// <summary> /// The main client for querying the portal. /// </summary> public partial class PortalClient : IDisposable { #region Fields private static readonly HttpMethod PatchHttpMethod = new HttpMethod("PATCH"); private readonly HttpClientHandler _handler; private readonly HttpClient _client; private static readonly JsonConverter[] JsonConverters = { new WidgetConverter(), new ReportConverter(), new FlagsEnumConverter() }; private readonly Cache<string, object> _cache; private readonly string _accessId; private readonly string _accessKey; /// <summary> /// The connected account name /// </summary> public string AccountName { get; } private static readonly Regex V3HackRegex = new Regex("/setting/registry/metadata|/setting/admin|setting/role|/setting/logicmodules/listcore|/setting/(datasources|eventsources|configsources|propertyrules|topologysources|batchjob|function|oid)/(\\d/audit)|/setting/(datasources|eventsources|configsources|propertyrules|topologysources|batchjobs|functions|oids)/importcore"); #endregion Fields #region Properties /// <summary> /// The Cache TimeSpan /// </summary> public TimeSpan CacheTimeSpan { get => _cache.MaxAge; set => _cache.MaxAge = value; } /// <summary> /// Clear the cache /// </summary> public void ClearCache() => _cache.Clear(); /// <summary> /// Whether to use the cache /// </summary> public bool UseCache; private int attemptCount = 1; private readonly ILogger _logger; /// <summary> /// The query timeout /// </summary> public TimeSpan TimeOut { get => _client.Timeout; set => _client.Timeout = value; } /// <summary> /// The AttemptCount /// </summary> public int AttemptCount { get => attemptCount; set { if (value < 1) { throw new ArgumentOutOfRangeException("Must be >= 1."); } attemptCount = value; } } /// <summary> /// Whether to throw an exception when paging over results and the total does not match the count of items retrieved. /// This can happen for example when an item in the first page is deleted during paging. /// </summary> public bool StrictPagingTotalChecking { get; set; } #endregion Properties #region Constructor / Dispose /// <summary> /// Create a portal client using subdomain, access id and access key /// </summary> /// <param name="subDomain">The subDomain</param> /// <param name="accessId">The access id</param> /// <param name="accessKey">The access key</param> /// <param name="iLogger">An optional ILogger</param> public PortalClient( string subDomain, string accessId, string accessKey, ILogger iLogger = null) { // Set up the logger _logger = iLogger ?? new NullLogger<PortalClient>(); _cache = new Cache<string, object>(TimeSpan.FromMinutes(5), _logger); AccountName = subDomain ?? throw new ArgumentNullException(nameof(subDomain)); _accessId = accessId ?? throw new ArgumentNullException(nameof(accessId)); _accessKey = accessKey ?? throw new ArgumentNullException(nameof(accessKey)); _handler = new HttpClientHandler { CookieContainer = new CookieContainer() }; _client = new HttpClient(_handler) { BaseAddress = new Uri($"https://{AccountName}.logicmonitor.com/santaba/") }; _client.DefaultRequestHeaders.Accept.Clear(); _client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/json")); _client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest"); _client.DefaultRequestHeaders.Add("X-version", "2"); _client.DefaultRequestHeaders.Add("X-CSRF-Token", "Fetch"); _client.Timeout = TimeSpan.FromMinutes(1); } private static string GetSignature(string httpVerb, long epoch, string data, string resourcePath, string accessKey) { // Construct signature using var hmac = new System.Security.Cryptography.HMACSHA256 { Key = Encoding.UTF8.GetBytes(accessKey) }; var compoundString = $"{httpVerb}{epoch}{data}{resourcePath}"; var signatureBytes = hmac.ComputeHash(Encoding.UTF8.GetBytes(compoundString)); var signatureHex = BitConverter.ToString(signatureBytes).Replace("-", "").ToLower(); return Convert.ToBase64String(Encoding.UTF8.GetBytes(signatureHex)); } /// <summary> /// Dispose /// </summary> public void Dispose() { // Sign out _client.Dispose(); _handler.Dispose(); } #endregion Constructor / Dispose #region Web Interaction /// <summary> /// Get all /// </summary> /// <typeparam name="T"></typeparam> /// <param name="cancellationToken"></param> /// <returns></returns> public Task<List<T>> GetAllAsync<T>(CancellationToken cancellationToken) where T : IHasEndpoint, new() => GetAllInternalAsync((Filter<T>)null, new T().Endpoint(), cancellationToken); /// <summary> /// Get all /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filter"></param> /// <param name="subUrl"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task<List<T>> GetAllAsync<T>(Filter<T> filter, string subUrl, CancellationToken cancellationToken = default) where T : new() => GetAllInternalAsync(filter, subUrl, cancellationToken); /// <summary> /// Get all /// </summary> /// <typeparam name="T"></typeparam> /// <param name="subUrl"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task<List<T>> GetAllAsync<T>(string subUrl, CancellationToken cancellationToken = default) where T : new() => GetAllInternalAsync(default(Filter<T>), subUrl, cancellationToken); /// <summary> /// Get all /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filter"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public Task<List<T>> GetAllAsync<T>(Filter<T> filter = null, CancellationToken cancellationToken = default) where T : IHasEndpoint, new() => GetAllInternalAsync(filter, new T().Endpoint(), cancellationToken); /// <summary> /// Get all T /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filter"></param> /// <param name="subUrl"></param> /// <param name="cancellationToken"></param> /// <returns></returns> private async Task<List<T>> GetAllInternalAsync<T>(Filter<T> filter, string subUrl, CancellationToken cancellationToken) where T : new() { var requestedTake = filter?.Take ?? int.MaxValue; // Ensure filter is set up if (filter == null) { filter = new Filter<T>(); } filter.Take = Math.Min(300, requestedTake); filter.Skip = 0; var list = new List<T>(); while (true) { // Get a page var page = await GetPageAsync(filter, subUrl, cancellationToken).ConfigureAwait(false); list.AddRange(page.Items); // Some endpoints return a negative total count var expectedTotal = Math.Min(page.TotalCount < 0 ? int.MaxValue : page.TotalCount, requestedTake); // Did we zero this time // OR do we already have all items? // OR Special case - OpsNotesTags don't like being paged. if (page.Items.Count == 0 || list.Count >= expectedTotal || typeof(T) == typeof(OpsNoteTag)) { // Yes. // Do strict checking if required if (StrictPagingTotalChecking && expectedTotal != list.Count) { throw new PagingException($"Mismatch between expected total: {expectedTotal} and received count: {list.Count}"); } // Return list. return list; } // Increment the skip value filter.Skip += filter.Take; } } /// <summary> /// Gets an item singleton /// </summary> /// <typeparam name="T">The item to get</typeparam> /// <param name="cancellationToken"></param> /// <returns></returns> public virtual Task<T> GetAsync<T>(CancellationToken cancellationToken = default) where T : class, IHasSingletonEndpoint, new() => GetBySubUrlAsync<T>(new T().Endpoint(), cancellationToken); /// <summary> /// Gets an item by id /// </summary> /// <param name="id">The item id</param> /// <param name="cancellationToken">The cancellation token</param> /// <typeparam name="T">The item to get</typeparam> /// <returns></returns> public virtual Task<T> GetAsync<T>(int id, CancellationToken cancellationToken = default) where T : IdentifiedItem, IHasEndpoint, new() => GetBySubUrlAsync<T>($"{new T().Endpoint()}/{id}", cancellationToken); /// <summary> /// Gets a single item by id, bringing back only specific properties as specified in a filter /// </summary> /// <param name="id">The item id</param> /// <param name="filter"></param> /// <param name="cancellationToken">The cancellation token</param> /// <typeparam name="T">The item to get</typeparam> /// <returns></returns> public virtual Task<T> GetAsync<T>(int id, Filter<T> filter, CancellationToken cancellationToken = default) where T : IdentifiedItem, IHasEndpoint, new() => GetBySubUrlAsync<T>($"{new T().Endpoint()}/{id}?{filter}", cancellationToken); /// <summary> /// Gets something by its name /// </summary> /// <typeparam name="T"></typeparam> /// <param name="name"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public virtual async Task<T> GetByNameAsync<T>(string name, CancellationToken cancellationToken = default) where T : NamedItem, IHasEndpoint, new() { var items = await GetAllAsync(new Filter<T> { FilterItems = new List<FilterItem<T>> { new Eq<T>(nameof(NamedEntity.Name), name) } }, cancellationToken: cancellationToken).ConfigureAwait(false); // If only one, return that. return items.Count switch { 0 => null, 1 => items[0], _ => throw new Exception($"An unexpected number of {typeof(T).Name} have name: {name}"), }; } /// <summary> /// Gets an item by id /// </summary> /// <param name="id">The item id</param> /// <param name="cancellationToken">The cancellation token</param> /// <typeparam name="T">The item to get</typeparam> /// <returns></returns> public virtual Task<T> GetAsync<T>(string id, CancellationToken cancellationToken = default) where T : StringIdentifiedItem, IHasEndpoint, new() => GetBySubUrlAsync<T>($"{new T().Endpoint()}/{id}", cancellationToken); /// <summary> /// Executes an item by id /// </summary> /// <typeparam name="T"></typeparam> /// <param name="object"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public virtual Task<T> ExecuteAsync<T>(T @object, CancellationToken cancellationToken = default) where T : IdentifiedItem, IExecutable, new() => GetBySubUrlAsync<T>($"{@object.Endpoint()}/{@object.Id}/executenow", cancellationToken); /// <summary> /// Executes an item by id /// </summary> /// <param name="id">The item id</param> /// <param name="cancellationToken">The cancellation token</param> /// <typeparam name="T">The item to get</typeparam> /// <returns></returns> public virtual Task<T> ExecuteAsync<T>(int id, CancellationToken cancellationToken = default) where T : IdentifiedItem, IExecutable, new() => GetBySubUrlAsync<T>($"{new T().Endpoint()}/{id}/executenow", cancellationToken); /// <summary> /// Patch a single IPatchable entity's property. /// </summary> /// <param name="entity">The entity</param> /// <param name="propertyName">The name of the property</param> /// <param name="value">The value</param> /// <param name="cancellationToken">The cancellation token</param> /// <typeparam name="T">The entity type</typeparam> /// <exception cref="ArgumentOutOfRangeException">Throw if the property does not exist on the entity.</exception> public virtual async Task PatchPropertyAsync<T>(T entity, string propertyName, object value, CancellationToken cancellationToken = default) where T : IPatchable => await PatchAsync(entity, new Dictionary<string, object> { { GetSerializationName<T>(propertyName), value } }, cancellationToken) .ConfigureAwait(false); /// <summary> /// Get the serialization name for a specified type /// </summary> /// <typeparam name="T">The type</typeparam> /// <param name="propertyName">The property</param> /// <returns></returns> public static string GetSerializationName<T>(string propertyName) { var propertyInfos = typeof(T).GetProperties(); var property = propertyInfos.SingleOrDefault(p => p.Name == propertyName); if (property == null) { throw new ArgumentOutOfRangeException(nameof(propertyName), $"{propertyName} is not a property of {typeof(T).Name}."); } // Use reflection to find the DataMember Name return property.GetCustomAttributes(typeof(DataMemberAttribute), true).Cast<DataMemberAttribute>().SingleOrDefault()?.Name; } /// <summary> /// Get the serialization name for a specified enum type /// </summary> /// <param name="enumObject">The property</param> /// <returns></returns> public static string GetSerializationNameFromEnumMember(object enumObject) { var type = enumObject.GetType(); if (!type.IsEnum) { throw new ArgumentException(nameof(enumObject), $"{enumObject} is not an enum"); } var fieldInfos = type.GetFields(); var field = fieldInfos.SingleOrDefault(f => f.Name == enumObject.ToString()); if (field == null) { throw new ArgumentOutOfRangeException(nameof(enumObject), $"{@enumObject} is not a member of enum {type.Name}."); } // Use reflection to find the DataMember Name var list = field.GetCustomAttributes(typeof(EnumMemberAttribute), true).Cast<EnumMemberAttribute>().ToList(); return list.SingleOrDefault()?.Value; } /// <summary> /// Gets the current portal version /// </summary> /// <returns>The portal version</returns> /// <exception cref="FormatException">Thrown if the portal version cannot be determined</exception> [Obsolete("Use GetVersionAsync() or GetVersionAsync(\"<accountName>\") instead.", true)] public async Task<int> GetPortalVersionAsync() { using var versionHttpClient = new HttpClient { BaseAddress = new Uri($"https://{AccountName}.logicmonitor.com/"), Timeout = TimeOut }; var response = await versionHttpClient.GetAsync("").ConfigureAwait(false); var responseText = await response.Content.ReadAsStringAsync().ConfigureAwait(false); var versionRegex = new Regex("sbui(?<version>\\d+)-"); var match = versionRegex.Match(responseText); if (match.Success) { return int.Parse(match.Groups["version"].Value); } throw new FormatException("Could not determine the portal version."); } /// <summary> /// Update an identified item /// </summary> /// <param name="object">The object to update</param> /// <typeparam name="T"></typeparam> /// <param name="cancellationToken">The cancellation token</param> /// <returns></returns> /// <exception cref="AggregateException"></exception> public virtual async Task PutAsync<T>(T @object, CancellationToken cancellationToken = default) where T : IdentifiedItem, IHasEndpoint // The ignoreReference permits forcing appliesTo functions and is ignored for other types => await PutAsync($"{@object.Endpoint()}/{@object.Id}?ignoreReference=true", @object, cancellationToken).ConfigureAwait(false); /// <summary> /// Update a string identified item /// </summary> /// <param name="object">The object to update</param> /// <typeparam name="T"></typeparam> /// <param name="cancellationToken">The cancellation token</param> /// <returns></returns> /// <exception cref="AggregateException"></exception> public virtual async Task PutStringIdentifiedItemAsync<T>(T @object, CancellationToken cancellationToken = default) where T : StringIdentifiedItem, IHasEndpoint // The ignoreReference permits forcing appliesTo functions and is ignored for other types => await PutAsync($"{@object.Endpoint()}/{@object.Id}?ignoreReference=true", @object, cancellationToken).ConfigureAwait(false); /// <summary> /// Update an item /// </summary> /// <param name="subUrl">The subURL</param> /// <param name="object">The updated object</param> /// <param name="cancellationToken">An optional CancellationToken</param> /// <returns></returns> public async Task PutAsync(string subUrl, object @object, CancellationToken cancellationToken = default) { var httpMethod = HttpMethod.Put; var prefix = GetPrefix(httpMethod); _logger.LogDebug($"{prefix} {subUrl}..."); var jsonString = JsonConvert.SerializeObject(@object); using var content = new StringContent(jsonString, Encoding.UTF8, "application/json"); HttpResponseMessage httpResponseMessage; // Handle rate limiting (see https://www.logicmonitor.com/support/rest-api-developers-guide/overview/using-logicmonitors-rest-api/) while (true) { // Determine the cancellationToken // We will always use one using (var requestMessage = new HttpRequestMessage(httpMethod, RequestUri(subUrl)) { Content = content }) { httpResponseMessage = await GetHttpResponseMessage(requestMessage, subUrl, jsonString, cancellationToken).ConfigureAwait(false); } _logger.LogDebug($"{prefix} complete"); // Check the outer HTTP status code if (!httpResponseMessage.IsSuccessStatusCode) { if ((int)httpResponseMessage.StatusCode != 429 && httpResponseMessage.ReasonPhrase != "Too Many Requests") { var responseBody = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); _logger.LogDebug($"{prefix} failed ({httpResponseMessage.StatusCode}): {responseBody}"); throw new LogicMonitorApiException(httpMethod, subUrl, httpResponseMessage.StatusCode, responseBody); } // We have been told to back off // Check that all rate limit headers are present var xRateLimitWindowLimitCount = await GetIntegerHeaderAsync(httpMethod, subUrl, httpResponseMessage.StatusCode, httpResponseMessage, "X-Rate-Limit-Limit").ConfigureAwait(false); var xRateLimitWindowRemainingCount = await GetIntegerHeaderAsync(httpMethod, subUrl, httpResponseMessage.StatusCode, httpResponseMessage, "X-Rate-Limit-Remaining").ConfigureAwait(false); var xRateLimitWindowSeconds = await GetIntegerHeaderAsync(httpMethod, subUrl, httpResponseMessage.StatusCode, httpResponseMessage, "X-Rate-Limit-Window").ConfigureAwait(false); var rateLimitInformation = $"Window: {xRateLimitWindowSeconds}s, Count: {xRateLimitWindowLimitCount}, Remaining {xRateLimitWindowRemainingCount}"; // Wait for the full window var delayMs = 1000 * xRateLimitWindowSeconds; // Wait some time and try again _logger.LogInformation($"{prefix} Rate limiting hit (with cancellation token): {rateLimitInformation}, waiting {delayMs:N0}ms"); await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); // Try again continue; } // Success - can be cached break; } var portalResponse = new PortalResponse<EmptyResponse>(httpResponseMessage); // Check the outer HTTP status code if (!portalResponse.IsSuccessStatusCode) { // If a success code was not received, throw an exception throw new LogicMonitorApiException(portalResponse.ErrorMessage) { HttpStatusCode = portalResponse.HttpStatusCode }; } } /// <summary> /// Deletes an item /// </summary> /// <param name="object">The object to delete</param> /// <param name="hardDelete">Whether to hard delete.</param> /// <param name="cancellationToken">The optional cancellation token</param> /// <typeparam name="T">The type of the item to delete</typeparam> /// <returns></returns> public virtual async Task DeleteAsync<T>( T @object, bool hardDelete = true, CancellationToken cancellationToken = default) where T : IdentifiedItem, IHasEndpoint, new() => await DeleteAsync($"{new T().Endpoint()}/{@object.Id}{(!hardDelete ? "?deleteHard=false" : string.Empty)}", cancellationToken) .ConfigureAwait(false); /// <summary> /// Deletes an item /// </summary> /// <param name="object">The object to delete</param> /// <param name="hardDelete">Whether to hard delete.</param> /// <param name="cancellationToken">The optional cancellation token</param> /// <typeparam name="T">The type of the item to delete</typeparam> /// <returns></returns> public virtual async Task DeleteStringIdentifiedAsync<T>( T @object, bool hardDelete = true, CancellationToken cancellationToken = default) where T : StringIdentifiedItem, IHasEndpoint, new() => await DeleteAsync($"{new T().Endpoint()}/{@object.Id}{(!hardDelete ? "?deleteHard=false" : string.Empty)}", cancellationToken) .ConfigureAwait(false); /// <summary> /// Deletes an item by id /// </summary> /// <param name="id">The item id</param> /// <param name="hardDelete">Whether to hard delete.</param> /// <param name="cancellationToken">The optional cancellation token</param> /// <typeparam name="T">The type of the item to delete</typeparam> /// <returns></returns> public virtual async Task DeleteAsync<T>( int id, bool hardDelete = true, CancellationToken cancellationToken = default ) where T : IdentifiedItem, IHasEndpoint, new() => await DeleteAsync($"{new T().Endpoint()}/{id}{(!hardDelete ? "?deleteHard=false" : string.Empty)}", cancellationToken) .ConfigureAwait(false); /// <summary> /// Deletes an item by id /// </summary> /// <param name="id">The item id</param> /// <param name="hardDelete">Whether to hard delete.</param> /// <param name="cancellationToken">The optional cancellation token</param> /// <typeparam name="T">The type of the item to delete</typeparam> /// <returns></returns> public virtual async Task DeleteAsync<T>( string id, bool hardDelete = true, CancellationToken cancellationToken = default) where T : StringIdentifiedItem, IHasEndpoint, new() => await DeleteAsync($"{new T().Endpoint()}/{id}{(!hardDelete ? "?deleteHard=false" : string.Empty)}", cancellationToken).ConfigureAwait(false); /// <summary> /// Deletes an item by id /// </summary> /// <param name="deviceDataSourceInstance">The DeviceDataSourceInstance to delete</param> /// <param name="hardDelete">Whether to hard delete.</param> /// <param name="cancellationToken">The optional cancellation token</param> /// <returns></returns> public virtual async Task DeleteAsync( DeviceDataSourceInstance deviceDataSourceInstance, bool hardDelete = true, CancellationToken cancellationToken = default) => await DeleteAsync($"device/devices/{deviceDataSourceInstance.DeviceId}/devicedatasources/{deviceDataSourceInstance.DeviceDataSourceId}/instances/{deviceDataSourceInstance.Id}{(!hardDelete ? "?deleteHard=false" : string.Empty)}", cancellationToken).ConfigureAwait(false); /// <summary> /// Create an item /// </summary> /// <param name="creationDto"></param> /// <param name="cancellationToken">The cancellation token</param> /// <typeparam name="T"></typeparam> /// <returns></returns> public virtual Task<T> CreateAsync<T>(CreationDto<T> creationDto, CancellationToken cancellationToken = default) where T : IHasEndpoint, new() => PostAsync<CreationDto<T>, T>(creationDto, new T().Endpoint(), cancellationToken); /// <summary> /// Gets an integer header /// </summary> /// <param name="httpMethod"></param> /// <param name="subUrl"></param> /// <param name="httpStatusCode"></param> /// <param name="httpResponseMessage">The response message</param> /// <param name="header">The required header</param> /// <exception cref="LogicMonitorApiException">Thrown when the header is not a single integer.</exception> /// <returns>The integer value</returns> private async Task<int> GetIntegerHeaderAsync(HttpMethod httpMethod, string subUrl, HttpStatusCode httpStatusCode, HttpResponseMessage httpResponseMessage, string header) { var responseBody = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); if (!httpResponseMessage.Headers.TryGetValues(header, out var valueStringEnumerable)) { var message = $"Response header '{header}' is not an integer."; _logger.LogDebug(message); throw new LogicMonitorApiException(httpMethod, subUrl, httpStatusCode, responseBody, message); } var valueStringList = valueStringEnumerable.ToList(); var firstOrDefaultMatchingHeader = valueStringList.FirstOrDefault(); if (firstOrDefaultMatchingHeader == null) { var message = $"'{header}' header value contains {valueStringList.Count} values. Expecting just one."; throw new LogicMonitorApiException(httpMethod, subUrl, httpStatusCode, responseBody, message); } if (!int.TryParse(firstOrDefaultMatchingHeader, out var valueInt)) { var message = $"'{header}' header value '{firstOrDefaultMatchingHeader}' is not an integer."; throw new LogicMonitorApiException(httpMethod, subUrl, httpStatusCode, responseBody, message); } return valueInt; } private string RequestUri(string subUrl) => $"https://{AccountName}.logicmonitor.com/santaba/rest/{subUrl}"; private async Task<HttpResponseMessage> GetHttpResponseMessage(HttpRequestMessage requestMessage, string subUrl, string data, CancellationToken cancellationToken) { var epoch = (long)(DateTime.UtcNow - new DateTime(1970, 1, 1)).TotalMilliseconds; //var epoch = 1525088468757; var subUrl2 = subUrl.Contains("?") ? subUrl.Substring(0, subUrl.IndexOf("?", StringComparison.Ordinal)) : subUrl; var httpVerb = requestMessage.Method.ToString().ToUpperInvariant(); var resourcePath = $"/{subUrl2}"; // Auth header var authHeaderValue = $"LMv1 {_accessId}:{GetSignature(httpVerb, epoch, data, resourcePath, _accessKey)}:{epoch}"; requestMessage.Headers.Add("Authorization", authHeaderValue); // HACK: Modify X-version if appropriate // Change when V3 is officially supportable // There is a bug with Patch such that V2 gives errors related to "custom property name cannot be predef.externalResourceType\ncustom property name cannot be predef.externalResourceID" if (V3HackRegex.IsMatch(resourcePath) || requestMessage.Method == PatchHttpMethod) { requestMessage.Headers.Remove("X-version"); requestMessage.Headers.Add("X-version", "3"); } return await _client.SendAsync(requestMessage, cancellationToken).ConfigureAwait(false); } private Task<Page<T>> FilteredGetAsync<T>(string subUrl, Filter<T> filter, CancellationToken cancellationToken) where T : new() => GetAsync<Page<T>>(UseCache, $"{subUrl}?{filter}", cancellationToken); /// <summary> /// Gets a filtered page of items /// </summary> /// <param name="filter">The filter</param> /// <param name="cancellationToken">An optional cancellation token</param> /// <typeparam name="T">The item type</typeparam> /// <returns>The filtered list</returns> public virtual Task<Page<T>> GetAsync<T>(Filter<T> filter, CancellationToken cancellationToken = default) where T : IHasEndpoint, new() => GetAsync<Page<T>>(UseCache, $"{new T().Endpoint()}?{filter}", cancellationToken); private Task<T> GetBySubUrlAsync<T>(string subUrl, CancellationToken cancellationToken) where T : class, new() => GetAsync<T>(UseCache, subUrl, cancellationToken); /// <summary> /// Gets a JObject directly from the API /// </summary> /// <param name="subUrl">The subUrl</param> /// <param name="cancellationToken">The cancellation token.</param> /// <returns></returns> public Task<JObject> GetJObjectAsync(string subUrl, CancellationToken cancellationToken) => GetAsync<JObject>(UseCache, subUrl, cancellationToken); /// <summary> /// Delete an item /// </summary> /// <param name="subUrl"></param> /// <param name="cancellationToken"></param> /// <returns></returns> public async Task DeleteAsync(string subUrl, CancellationToken cancellationToken = default) { var httpMethod = HttpMethod.Delete; var prefix = GetPrefix(httpMethod); _logger.LogDebug($"{prefix} {subUrl} ..."); var stopwatch = Stopwatch.StartNew(); HttpResponseMessage httpResponseMessage; // Handle rate limiting (see https://www.logicmonitor.com/support/rest-api-developers-guide/overview/using-logicmonitors-rest-api/) var failureCount = 0; while (true) { // Determine the cancellationToken // We will always use one try { using (var requestMessage = new HttpRequestMessage(httpMethod, RequestUri(subUrl))) { httpResponseMessage = await GetHttpResponseMessage(requestMessage, subUrl, null, cancellationToken).ConfigureAwait(false); } _logger.LogDebug($"{prefix} complete (from remote: {stopwatch.ElapsedMilliseconds:N0}ms)"); } catch (Exception e) { _logger.LogDebug($"{prefix} failed on attempt {++failureCount}: {e}"); if (failureCount < AttemptCount) { // Try again _logger.LogDebug($"{prefix} Retrying.."); continue; } _logger.LogDebug($"{prefix} Giving up."); throw; } // Check the outer HTTP status code if (!httpResponseMessage.IsSuccessStatusCode) { if ((int)httpResponseMessage.StatusCode != 429 && httpResponseMessage.ReasonPhrase != "Too Many Requests") { var responseBody = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); var message = $"{prefix} failed: {responseBody}"; _logger.LogDebug(message); throw new LogicMonitorApiException(HttpMethod.Get, subUrl, httpResponseMessage.StatusCode, responseBody, message); } // We have been told to back off // Check that all rate limit headers are present var xRateLimitWindowLimitCount = await GetIntegerHeaderAsync(httpMethod, subUrl, httpResponseMessage.StatusCode, httpResponseMessage, "X-Rate-Limit-Limit").ConfigureAwait(false); var xRateLimitWindowRemainingCount = await GetIntegerHeaderAsync(httpMethod, subUrl, httpResponseMessage.StatusCode, httpResponseMessage, "X-Rate-Limit-Remaining").ConfigureAwait(false); var xRateLimitWindowSeconds = await GetIntegerHeaderAsync(httpMethod, subUrl, httpResponseMessage.StatusCode, httpResponseMessage, "X-Rate-Limit-Window").ConfigureAwait(false); var rateLimitInformation = $"Window: {xRateLimitWindowSeconds}s, Count: {xRateLimitWindowLimitCount}, Remaining {xRateLimitWindowRemainingCount}"; // Wait for the full window var delayMs = 1000 * xRateLimitWindowSeconds; // Wait some time and try again _logger.LogDebug($"{prefix} Rate limiting hit (with cancellation token): {rateLimitInformation}, waiting {delayMs:N0}ms"); await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); // Try again continue; } // Success - can be cached if permitted break; } _logger.LogDebug($"{prefix} complete"); // Check the outer HTTP status code if (!httpResponseMessage.IsSuccessStatusCode) { // If a success code was not received, throw an exception var responseBody = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); var message = $"{prefix} failed ({httpResponseMessage.StatusCode}): {responseBody}"; _logger.LogDebug(message); throw new LogicMonitorApiException(HttpMethod.Get, subUrl, httpResponseMessage.StatusCode, responseBody, message); } // Get the content var jsonString = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); if (jsonString.Contains("group is not empty")) { // If a success code was not received, throw an exception var message = $"{prefix} failed - group is not empty for suburl"; _logger.LogDebug(message); var responseBody = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); throw new LogicMonitorApiException(httpMethod, subUrl, HttpStatusCode.PreconditionFailed, responseBody, message); } } private string GetPrefix(HttpMethod method) => $"{Guid.NewGuid()}: {method}"; /// <summary> /// Async Get method /// </summary> /// <param name="permitCacheIfEnabled"></param> /// <param name="subUrl"></param> /// <param name="cancellationToken">The cancellation token</param> /// <typeparam name="T"></typeparam> /// <returns></returns> /// <exception cref="LogicMonitorApiException"></exception> private async Task<T> GetAsync<T>(bool permitCacheIfEnabled, string subUrl, CancellationToken cancellationToken) where T : class, new() { var httpMethod = HttpMethod.Get; var prefix = GetPrefix(httpMethod); _logger.LogDebug($"{prefix} {subUrl} ..."); // Age the Cache _cache.Age(); var stopwatch = Stopwatch.StartNew(); var useCache = permitCacheIfEnabled && UseCache; if (useCache && _cache.TryGetValue(subUrl, out var cacheObject)) { _logger.LogDebug($"{prefix} complete (from cache: {stopwatch.ElapsedMilliseconds:N0}ms)"); return (T)cacheObject; } HttpResponseMessage httpResponseMessage; // Handle rate limiting (see https://www.logicmonitor.com/support/rest-api-developers-guide/overview/using-logicmonitors-rest-api/) var failureCount = 0; while (true) { // Determine the cancellationToken // We will always use one try { using (var requestMessage = new HttpRequestMessage(httpMethod, RequestUri(subUrl))) { httpResponseMessage = await GetHttpResponseMessage(requestMessage, subUrl, null, cancellationToken).ConfigureAwait(false); } _logger.LogDebug($"{prefix} complete (from remote: {stopwatch.ElapsedMilliseconds:N0}ms)"); } catch (Exception e) { _logger.LogDebug($"{prefix} failed on attempt {++failureCount}: {e}"); if (failureCount < AttemptCount) { // Try again _logger.LogDebug($"{prefix} Retrying.."); continue; } _logger.LogDebug($"{prefix} Giving up."); throw; } // Check the outer HTTP status code if (!httpResponseMessage.IsSuccessStatusCode) { if ((int)httpResponseMessage.StatusCode != 429 && httpResponseMessage.ReasonPhrase != "Too Many Requests") { var responseBody = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); var message = $"{prefix} failed on attempt {++failureCount}: {responseBody}"; _logger.LogDebug(message); if (failureCount < AttemptCount) { // Try again _logger.LogDebug($"{prefix} Retrying.."); continue; } throw new LogicMonitorApiException(httpMethod, subUrl, httpResponseMessage.StatusCode, responseBody, message); } // We have been told to back off // Check that all rate limit headers are present var xRateLimitWindowLimitCount = await GetIntegerHeaderAsync(httpMethod, subUrl, httpResponseMessage.StatusCode, httpResponseMessage, "X-Rate-Limit-Limit").ConfigureAwait(false); var xRateLimitWindowRemainingCount = await GetIntegerHeaderAsync(httpMethod, subUrl, httpResponseMessage.StatusCode, httpResponseMessage, "X-Rate-Limit-Remaining").ConfigureAwait(false); var xRateLimitWindowSeconds = await GetIntegerHeaderAsync(httpMethod, subUrl, httpResponseMessage.StatusCode, httpResponseMessage, "X-Rate-Limit-Window").ConfigureAwait(false); var rateLimitInformation = $"Window: {xRateLimitWindowSeconds}s, Count: {xRateLimitWindowLimitCount}, Remaining {xRateLimitWindowRemainingCount}"; // Wait for the full window var delayMs = 1000 * xRateLimitWindowSeconds; // Wait some time and try again _logger.LogDebug($"{prefix} Rate limiting hit (with cancellation token): {rateLimitInformation}, waiting {delayMs:N0}ms"); await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); // Try again continue; } // Success - can be cached if permitted break; } // If this is a file response, return that if (typeof(T).Name == nameof(XmlResponse)) { var content = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); return new XmlResponse { Content = content } as T; } else if (typeof(T) == typeof(List<byte>)) { var content = await httpResponseMessage.Content.ReadAsByteArrayAsync().ConfigureAwait(false); return content.ToList() as T; } else if (typeof(T) == typeof(DownloadFileInfo)) { var tempFileInfo = new FileInfo(Path.GetTempFileName()); using (Stream output = File.OpenWrite(tempFileInfo.FullName)) using (var input = await httpResponseMessage.Content.ReadAsStreamAsync().ConfigureAwait(false)) { input.CopyTo(output); } return new DownloadFileInfo { FileInfo = tempFileInfo } as T; } // Create a PortalResponse var portalResponse = new PortalResponse<T>(httpResponseMessage); // Check the outer HTTP status code if (!portalResponse.IsSuccessStatusCode) { // If a success code was not received, throw an exception var responseBody = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); var message = $"{prefix} failed ({httpResponseMessage.StatusCode}): {responseBody}"; _logger.LogDebug(message); throw new LogicMonitorApiException(httpMethod, subUrl, portalResponse.HttpStatusCode, responseBody, message); } // Return the object T deserializedObject; try { deserializedObject = portalResponse.GetObject(JsonConverters); } catch (DeserializationException e) { _logger.LogError($"{prefix} Unable to deserialize\n{e.ResponseBody}\n{e.Message}"); throw; } // Cache the result if (useCache) { _cache.AddOrUpdate(subUrl, deserializedObject); } // Return the result return deserializedObject; } /// <summary> /// Post an item /// </summary> /// <typeparam name="TIn">The posted object type</typeparam> /// <typeparam name="TOut">The returned object type</typeparam> /// <param name="object">The posted object </param> /// <param name="subUrl">The endpoint</param> /// <param name="cancellationToken">An optional CancellationToken</param> /// <returns></returns> public async Task<TOut> PostAsync<TIn, TOut>(TIn @object, string subUrl, CancellationToken cancellationToken = default) where TOut : new() { var httpMethod = HttpMethod.Post; var prefix = GetPrefix(httpMethod); _logger.LogDebug($"{prefix} {subUrl} ..."); // LMREP-1042: "d:\"EBSDB [prod24778]\" does not work, however "d:\"EBSDB *prod24778*\" matches. Unrelated to URl encoding, etc... var data = JsonConvert.SerializeObject(@object, new JsonSerializerSettings { NullValueHandling = NullValueHandling.Ignore }); //var subUrl1 = "rest/" + (subUrl ?? "functions/"); HttpResponseMessage httpResponseMessage; // Handle rate limiting (see https://www.logicmonitor.com/support/rest-api-developers-guide/overview/using-logicmonitors-rest-api/) while (true) { using (var content = new StringContent(data, Encoding.UTF8, "application/json")) { using (var requestMessage = new HttpRequestMessage(httpMethod, RequestUri(subUrl)) { Content = content }) { httpResponseMessage = await GetHttpResponseMessage(requestMessage, subUrl, data, cancellationToken).ConfigureAwait(false); } _logger.LogDebug($"{prefix} complete"); } // Check the outer HTTP status code // Check the outer HTTP status code if (!httpResponseMessage.IsSuccessStatusCode) { if ((int)httpResponseMessage.StatusCode != 429 && httpResponseMessage.ReasonPhrase != "Too Many Requests") { // If a success code was not received, throw an exception var responseBody = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); var message = $"{prefix} failed ({httpResponseMessage.StatusCode}): {responseBody}"; _logger.LogDebug(message); throw new LogicMonitorApiException(httpMethod, subUrl, httpResponseMessage.StatusCode, responseBody, message); } // We have been told to back off // Check that all rate limit headers are present var xRateLimitWindowLimitCount = await GetIntegerHeaderAsync(httpMethod, subUrl, httpResponseMessage.StatusCode, httpResponseMessage, "X-Rate-Limit-Limit").ConfigureAwait(false); var xRateLimitWindowRemainingCount = await GetIntegerHeaderAsync(httpMethod, subUrl, httpResponseMessage.StatusCode, httpResponseMessage, "X-Rate-Limit-Remaining").ConfigureAwait(false); var xRateLimitWindowSeconds = await GetIntegerHeaderAsync(httpMethod, subUrl, httpResponseMessage.StatusCode, httpResponseMessage, "X-Rate-Limit-Window").ConfigureAwait(false); var rateLimitInformation = $"Window: {xRateLimitWindowSeconds}s, Count: {xRateLimitWindowLimitCount}, Remaining {xRateLimitWindowRemainingCount}"; // Wait for the full window var delayMs = 1000 * xRateLimitWindowSeconds; // Wait some time and try again _logger.LogDebug($"{prefix} Rate limiting hit (with cancellation token): {rateLimitInformation}, waiting {delayMs:N0}ms"); await Task.Delay(delayMs, cancellationToken).ConfigureAwait(false); // Try again continue; } // Success - can be cached break; } // Success - can cache // Create a PortalResponse var portalResponse = new PortalResponse<TOut>(httpResponseMessage); // Check the outer HTTP status code if (!portalResponse.IsSuccessStatusCode) { // If a success code was not received, throw an exception throw new LogicMonitorApiException(portalResponse.ErrorMessage) { HttpStatusCode = portalResponse.HttpStatusCode }; } // Deserialize the JSON var deserializedObject = portalResponse.GetObject(); // Return return deserializedObject; } /// <summary> /// Patch specific fields /// </summary> /// <typeparam name="T"></typeparam> /// <param name="entity"></param> /// <param name="fieldsToUpdate">The fields to update</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns></returns> /// <exception cref="AggregateException"></exception> public virtual async Task PatchAsync<T>(T entity, Dictionary<string, object> fieldsToUpdate, CancellationToken cancellationToken = default) where T : IPatchable => await PatchAsync($"{entity.Endpoint()}/{entity.Id}", fieldsToUpdate, cancellationToken).ConfigureAwait(false); private async Task PatchAsync(string subUrl, Dictionary<string, object> fieldsToUpdate, CancellationToken cancellationToken) { var prefix = GetPrefix(PatchHttpMethod); var jsonString = JsonConvert.SerializeObject(fieldsToUpdate); _logger.LogDebug($"{prefix} ..."); HttpResponseMessage httpResponseMessage; using (var content = new StringContent(jsonString, Encoding.UTF8, "application/json")) { var patchSpec = $"?patchFields={string.Join(",", fieldsToUpdate.Keys)}"; using var requestMessage = new HttpRequestMessage(PatchHttpMethod, RequestUri(subUrl) + patchSpec) { Content = content }; httpResponseMessage = await GetHttpResponseMessage(requestMessage, subUrl, jsonString, cancellationToken).ConfigureAwait(false); } _logger.LogDebug($"{prefix} complete"); if (!httpResponseMessage.IsSuccessStatusCode) { // If a success code was not received, throw an exception var responseBody = await httpResponseMessage.Content.ReadAsStringAsync().ConfigureAwait(false); var message = $"{prefix} failed ({httpResponseMessage.StatusCode}): {responseBody}"; _logger.LogDebug(message); throw new LogicMonitorApiException(HttpMethod.Get, subUrl, httpResponseMessage.StatusCode, responseBody, message); } } /// <summary> /// Gets a page of items /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filter"></param> /// <param name="subUrl"></param> /// <param name="cancellationToken"></param> /// <returns>A list of Collectors</returns> public Task<Page<T>> GetPageAsync<T>(Filter<T> filter, string subUrl, CancellationToken cancellationToken = default) where T : new() => GetPageInternalAsync(filter, subUrl, cancellationToken); /// <summary> /// Gets a page of items /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filter"></param> /// <param name="cancellationToken"></param> /// <returns>A list of Collectors</returns> public Task<Page<T>> GetPageAsync<T>(Filter<T> filter, CancellationToken cancellationToken = default) where T : IHasEndpoint, new() => GetPageInternalAsync(filter, new T().Endpoint(), cancellationToken); /// <summary> /// Gets a page of items /// </summary> /// <typeparam name="T"></typeparam> /// <param name="filter"></param> /// <param name="subUrl"></param> /// <param name="cancellationToken"></param> /// <returns>A list of Collectors</returns> private Task<Page<T>> GetPageInternalAsync<T>(Filter<T> filter, string subUrl, CancellationToken cancellationToken) where T : new() => GetBySubUrlAsync<Page<T>>(subUrl.Contains('?') ? $"{subUrl}&{filter}" : $"{subUrl}?{filter}" , cancellationToken); #endregion Web Interaction #region Debug Commands /// <summary> /// Starts the execution of a debug command /// </summary> /// <param name="collectorId">The ID of the collector on which to execute the command</param> /// <param name="commandText">The command to execute</param> /// <param name="cancellationToken"></param> /// <returns>The ExecuteDebugCommandResponse containing the sessionId</returns> public Task<ExecuteDebugCommandResponse> ExecuteDebugCommandAsync(int collectorId, string commandText, CancellationToken cancellationToken = default) => PostAsync<ExecuteDebugCommandRequest, ExecuteDebugCommandResponse>(new ExecuteDebugCommandRequest { Command = commandText }, $"debug?collectorId={collectorId}", cancellationToken); /// <summary> /// Gets the debug command results, if available /// </summary> /// <param name="collectorId">The ID of the collector on which the command was executed</param> /// <param name="sessionId">The request ID from the ExecuteDebugCommandResponse</param> /// <param name="cancellationToken">The optional cancellation token</param> /// <returns></returns> public Task<ExecuteDebugCommandResponse> GetDebugCommandResultAsync(int collectorId, int sessionId, CancellationToken cancellationToken = default) => GetBySubUrlAsync<ExecuteDebugCommandResponse>($"debug/{sessionId}?collectorId={collectorId}&_={DateTime.UtcNow.Ticks}", cancellationToken); /// <summary> /// Waits for a Debug command response /// </summary> /// <param name="collectorId">The ID of the collector on which the command was executed</param> /// <param name="commandText">The command to execute</param> /// <param name="timeoutMs">The maximum amount of time to wait (default 10000 ms)</param> /// <param name="sleepIntervalMs">The sleep interval between attempts to retrieve the response (default 500ms)</param> /// <param name="cancellationToken">The cancellation token</param> /// <returns></returns> public async Task<ExecuteDebugCommandResponse> ExecuteDebugCommandAndWaitForResultAsync(int collectorId, string commandText, int timeoutMs = 10000, int sleepIntervalMs = 500, CancellationToken cancellationToken = default) { var executeDebugCommandResponse = await ExecuteDebugCommandAsync(collectorId, commandText, cancellationToken).ConfigureAwait(false); var stopwatch = Stopwatch.StartNew(); ExecuteDebugCommandResponse debugCommandResult = null; while (stopwatch.ElapsedMilliseconds < timeoutMs) { try { debugCommandResult = await GetDebugCommandResultAsync(collectorId, executeDebugCommandResponse.SessionId, cancellationToken).ConfigureAwait(false); } catch { // ignored } // Do we have a response? if (!string.IsNullOrWhiteSpace(debugCommandResult?.Output)) { break; } await Task.Delay(sleepIntervalMs, cancellationToken).ConfigureAwait(false); } return debugCommandResult; } #endregion Debug Commands private async Task SetCustomPropertyAsync( int id, string name, string value, SetPropertyMode mode, string subUrl, CancellationToken cancellationToken) { var propertiesSubUrl = $"{subUrl}/{id}/properties"; switch (mode) { case SetPropertyMode.Automatic: // Determine whether there is an existing property try { var _ = await GetBySubUrlAsync<Property>($"{propertiesSubUrl}/{name}", cancellationToken).ConfigureAwait(false); // No exception thrown? It exists // Are we deleting? if (value == null) { // Yes. await DeleteAsync($"{propertiesSubUrl}/{name}", cancellationToken).ConfigureAwait(false); } else { // No // PUT the replacement value await PutAsync($"{propertiesSubUrl}/{name}", new { value }, cancellationToken).ConfigureAwait(false); } } catch (Exception) { // It doesn't exist // so POST a new one (unless it's null, in which case nothing to do) if (value != null) { var _ = await PostAsync<Property, Property>( new Property { Name = name, Value = value }, $"{propertiesSubUrl}", cancellationToken).ConfigureAwait(false); } } break; case SetPropertyMode.Create: if (value == null) { throw new InvalidOperationException("Value must not be set to null when creating the property."); } await PostAsync<Property, Property>(new Property { Name = name, Value = value }, $"{propertiesSubUrl}", cancellationToken).ConfigureAwait(false); break; case SetPropertyMode.Update: if (value == null) { throw new InvalidOperationException("Value must not be set to null when updating the property."); } // PUT the replacement value await PutAsync($"{propertiesSubUrl}/{name}", new { value }, cancellationToken).ConfigureAwait(false); break; case SetPropertyMode.Delete: if (value != null) { throw new InvalidOperationException("Value must be set to null when deleting the value."); } // Delete the value await DeleteAsync($"{propertiesSubUrl}/{name}", cancellationToken).ConfigureAwait(false); break; default: throw new ArgumentOutOfRangeException(nameof(mode), mode, null); } } /// <summary> /// Returns true if the specified property on the class has the SantabaReadOnly attribute defined /// </summary> /// <param name="name">The name to match</param> /// <param name="logicMonitorClassType">The type of class to query</param> /// <param name="tryJsonNameFirst">If true, will use the DataMember/JSON property name to match before using property name</param> /// <returns>True if the property is read only</returns> public static bool IsPropertyReadOnly(string name, Type logicMonitorClassType, bool tryJsonNameFirst = false) { PropertyInfo propertyInfo; if (tryJsonNameFirst) { // Try and find a property which matches the DataMemberAttributes name if it's set propertyInfo = logicMonitorClassType.GetProperties() .SingleOrDefault(p => p.GetCustomAttributes(typeof(DataMemberAttribute), false) .Cast<DataMemberAttribute>() .SingleOrDefault(entity => entity.IsNameSetExplicitly)? .Name == name) // Also try and get the property by it's normal name ?? logicMonitorClassType.GetProperty(name); } else { // Just a simple GetProperty propertyInfo = logicMonitorClassType.GetProperty(name); } if (propertyInfo == null) { throw new PropertyNotFoundException($"Could not find property on {logicMonitorClassType.Name} with name {name}."); } return Attribute.IsDefined(propertyInfo, typeof(SantabaReadOnly)); } /// <summary> /// Clone an ICloneableItem /// </summary> /// <typeparam name="T">The type of the item being cloned</typeparam> /// <param name="id">The id of the item being cloned</param> /// <param name="cloneRequest">The clone request</param> /// <param name="cancellationToken">An optional CancellationToken</param> /// <returns></returns> public Task<T> CloneAsync<T>(int id, CloneRequest<T> cloneRequest, CancellationToken cancellationToken = default) where T : IHasEndpoint, ICloneableItem, new() => PostAsync<CloneRequest<T>, T>(cloneRequest, $"{new T().Endpoint()}/{id}/clone", cancellationToken); } }
40.614623
332
0.704709
[ "MIT" ]
tdicks/LogicMonitor.Api
LogicMonitor.Api/PortalClient.cs
53,327
C#
using Claw.Blasts; using Claw.UI.Controls; using Claw.UI.Helper; using Claw.UI.Panels; using Claw.UI.Style; using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Windows; using System.Windows.Controls; using System.Windows.Data; using System.Windows.Documents; using System.Windows.Input; using System.Windows.Media; using System.Windows.Media.Imaging; using System.Windows.Shapes; namespace Claw.UI.Windows { /// <summary> /// Logic for ChooseIconWindow.xaml /// </summary> public partial class ChooseIconWindow : ClawWindow { /// <summary> /// Shows a selection dialog for the given blasts. /// </summary> /// <param name="options">The blasts the user can select from.</param> /// <param name="selected">The initially selected blast.</param> /// <returns>An instance of ChooseIconWindowResult representing the dialogs result.</returns> public static ChooseIconWindowResult ShowDialog(IList<Blast> options, Blast selected) { var window = new ChooseIconWindow(options, selected); window.ShowDialog(); Blast sel = null; ListViewItem selItem = (ListViewItem)window.lvBlasts.SelectedItem; if (selItem.Tag != null) { sel = (Blast)selItem.Tag; } return new ChooseIconWindowResult(!window.success, sel); } protected override Panel BaseComponent { get { return baseGrid; } } private bool success = false; private ChooseIconWindow(IList<Blast> options, Blast selected) { InitializeComponent(); foreach (Blast blast in options) { var imageControl = ImageHelper.CreateImageControl(blast.GetData()); var grid = new Grid(); grid.Children.Add(imageControl); var item = new ListViewItem(); item.Content = grid; item.Tag = blast; lvBlasts.Items.Add(item); if (blast == selected) { lvBlasts.SelectedItem = item; } } } private void OnOKClick(object sender, RoutedEventArgs e) { success = true; Close(); } private void OnCancelClick(object sender, RoutedEventArgs e) { Close(); } } }
29.505882
101
0.582935
[ "MIT" ]
UserXXX/Claw
Claw/UI/Windows/ChooseIconWindow.xaml.cs
2,510
C#
using MO.Common.Lang; namespace MO.Bridge.Engine.Display { public class FReigon : FObject { } }
11.888889
34
0.672897
[ "Apache-2.0" ]
favedit/MoCross
Utiliy/Core/MuBridge/Engine/Display/FReigon.cs
109
C#
using Stratis.SmartContracts; /// <summary> /// Staking market contract used for managing available staking pools. /// </summary> public class OpdexStakingMarket : OpdexMarket, IOpdexStakingMarket { /// <summary> /// Constructor initializing the staking market. /// </summary> /// <param name="state">Smart contract state.</param> /// <param name="transactionFee">The market transaction fee, 0-10 equal to 0-1%.</param> /// <param name="stakingToken">The address of the staking token.</param> public OpdexStakingMarket(ISmartContractState state, uint transactionFee, Address stakingToken) : base(state, transactionFee) { StakingToken = stakingToken; } /// <inheritdoc /> public Address StakingToken { get => State.GetAddress(MarketStateKeys.StakingToken); private set => State.SetAddress(MarketStateKeys.StakingToken, value); } /// <inheritdoc /> public override Address CreatePool(Address token) { Assert(State.IsContract(token), "OPDEX: INVALID_TOKEN"); var pool = GetPool(token); Assert(pool == Address.Zero, "OPDEX: POOL_EXISTS"); var poolResponse = Create<OpdexStakingPool>(0, new object[] {token, TransactionFee, StakingToken}); Assert(poolResponse.Success, "OPDEX: INVALID_POOL"); pool = poolResponse.NewContractAddress; SetPool(token, pool); Log(new CreateLiquidityPoolLog { Token = token, Pool = pool }); return pool; } }
32.021277
129
0.671096
[ "MIT" ]
Opdex/opdex-v1-core
src/Contracts/Markets/OpdexStakingMarket.cs
1,505
C#
using System; using System.Linq; using System.Windows; using System.Windows.Media; using HandyControl.Data; namespace HandyControl.Controls { public class SideMenu : HeaderedSimpleItemsControl { private SideMenuItem _selectedItem; private SideMenuItem _selectedHeader; private bool _isItemSelected; public SideMenu() { AddHandler(SideMenuItem.SelectedEvent, new RoutedEventHandler(SideMenuItemSelected)); Loaded += (s, e) => Init(); } protected override void Refresh() { base.Refresh(); Init(); } private void Init() { if (ItemsHost == null) return; OnExpandModeChanged(ExpandMode); } private void SideMenuItemSelected(object sender, RoutedEventArgs e) { if (e.OriginalSource is SideMenuItem item) { if (item.Role == SideMenuItemRole.Item) { _isItemSelected = true; if (Equals(item, _selectedItem)) return; if (_selectedItem != null) { _selectedItem.IsSelected = false; } _selectedItem = item; _selectedItem.IsSelected = true; RaiseEvent(new FunctionEventArgs<object>(SelectionChangedEvent, this) { Info = e.OriginalSource }); } else { if (!Equals(item, _selectedHeader)) { if (_selectedHeader != null) { if (ExpandMode == ExpandMode.Freedom && item.ItemsHost.IsVisible && !_isItemSelected) { item.IsSelected = false; SwitchPanelArea(item); return; } _selectedHeader.IsSelected = false; if (ExpandMode != ExpandMode.Freedom) { SwitchPanelArea(_selectedHeader); } } _selectedHeader = item; _selectedHeader.IsSelected = true; SwitchPanelArea(_selectedHeader); } else if (ExpandMode == ExpandMode.Freedom && !_isItemSelected) { _selectedHeader.IsSelected = false; SwitchPanelArea(_selectedHeader); _selectedHeader = null; } if (_isItemSelected) { _isItemSelected = false; } else if(_selectedHeader != null) { if (AutoSelect) { _selectedHeader.SelectDefaultItem(); } _isItemSelected = false; } } } } private void SwitchPanelArea(SideMenuItem oldItem) { switch (ExpandMode) { case ExpandMode.ShowAll: return; case ExpandMode.ShowOne: case ExpandMode.Freedom: case ExpandMode.Accordion: oldItem.SwitchPanelArea(oldItem.IsSelected); break; } } protected override DependencyObject GetContainerForItemOverride() => new SideMenuItem(); protected override bool IsItemItsOwnContainerOverride(object item) => item is SideMenuItem; public Brush SubSideBrush { get => (Brush)GetValue(SubSideBrushProperty); set => SetValue(SubSideBrushProperty, value); } public static readonly DependencyProperty SubSideBrushProperty = DependencyProperty.RegisterAttached("SubSideBrush", typeof(Brush), typeof(SideMenu), new FrameworkPropertyMetadata(default(Brushes), FrameworkPropertyMetadataOptions.Inherits)); public Brush SideBrush { get => (Brush)GetValue(SideBrushProperty); set => SetValue(SideBrushProperty, value); } public static readonly DependencyProperty SideBrushProperty = DependencyProperty.RegisterAttached("SideBrush", typeof(Brush), typeof(SideMenu), new FrameworkPropertyMetadata(default(Brushes), FrameworkPropertyMetadataOptions.Inherits)); public static readonly DependencyProperty AutoSelectProperty = DependencyProperty.Register( "AutoSelect", typeof(bool), typeof(SideMenu), new PropertyMetadata(ValueBoxes.TrueBox)); public bool AutoSelect { get => (bool) GetValue(AutoSelectProperty); set => SetValue(AutoSelectProperty, ValueBoxes.BooleanBox(value)); } public static readonly DependencyProperty ExpandModeProperty = DependencyProperty.Register( "ExpandMode", typeof(ExpandMode), typeof(SideMenu), new PropertyMetadata(default(ExpandMode), OnExpandModeChanged)); private static void OnExpandModeChanged(DependencyObject d, DependencyPropertyChangedEventArgs e) { var ctl = (SideMenu) d; var v = (ExpandMode) e.NewValue; if (ctl.ItemsHost == null) { return; } ctl.OnExpandModeChanged(v); } private void OnExpandModeChanged(ExpandMode mode) { if (mode == ExpandMode.ShowAll) { ShowAll(); } else if (mode == ExpandMode.ShowOne) { SideMenuItem sideMenuItemSelected = null; foreach (var sideMenuItem in ItemsHost.Children.OfType<SideMenuItem>()) { if (sideMenuItemSelected != null) { sideMenuItem.IsSelected = false; if (sideMenuItem.ItemsHost != null) { foreach (var sideMenuSubItem in sideMenuItem.ItemsHost.Children.OfType<SideMenuItem>()) { sideMenuSubItem.IsSelected = false; } } } else if (sideMenuItem.IsSelected) { switch (sideMenuItem.Role) { case SideMenuItemRole.Header: _selectedHeader = sideMenuItem; break; case SideMenuItemRole.Item: _selectedItem = sideMenuItem; break; } ShowSelectedOne(sideMenuItem); sideMenuItemSelected = sideMenuItem; if (sideMenuItem.ItemsHost != null) { foreach (var sideMenuSubItem in sideMenuItem.ItemsHost.Children.OfType<SideMenuItem>()) { if (_selectedItem != null) { sideMenuSubItem.IsSelected = false; } else if (sideMenuSubItem.IsSelected) { _selectedItem = sideMenuSubItem; } } } } } } } public ExpandMode ExpandMode { get => (ExpandMode) GetValue(ExpandModeProperty); set => SetValue(ExpandModeProperty, value); } public static readonly DependencyProperty PanelAreaLengthProperty = DependencyProperty.Register( "PanelAreaLength", typeof(double), typeof(SideMenu), new PropertyMetadata(double.NaN)); public double PanelAreaLength { get => (double) GetValue(PanelAreaLengthProperty); set => SetValue(PanelAreaLengthProperty, value); } private void ShowAll() { foreach (var sideMenuItem in ItemsHost.Children.OfType<SideMenuItem>()) { sideMenuItem.SwitchPanelArea(true); } } private void ShowSelectedOne(SideMenuItem item) { foreach (var sideMenuItem in ItemsHost.Children.OfType<SideMenuItem>()) { sideMenuItem.SwitchPanelArea(Equals(sideMenuItem, item)); } } public static readonly RoutedEvent SelectionChangedEvent = EventManager.RegisterRoutedEvent( "SelectionChanged", RoutingStrategy.Bubble, typeof(EventHandler<FunctionEventArgs<object>>), typeof(SideMenu)); public event EventHandler<FunctionEventArgs<object>> SelectionChanged { add => AddHandler(SelectionChangedEvent, value); remove => RemoveHandler(SelectionChangedEvent, value); } } }
36.246212
189
0.490856
[ "MIT" ]
danwalmsley/HandyControls
src/Shared/HandyControl_Shared/Controls/SideMenu/SideMenu.cs
9,571
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; namespace PxgBot.Classes { public static class PXG { /// <summary> /// X, Y, Z position /// </summary> public class Position { public int X { get; set; } public int Y { get; set; } public int Z { get; set; } public Position(int X, int Y, int Z) { this.X = X; this.Y = Y; this.Z = Z; } } } }
20.344828
48
0.462712
[ "MIT" ]
tassoruas/PxgBot
Classes/PXG.cs
592
C#
using System; using UnityEngine; namespace DoubTech.SpaceGameUtils.Orbit { [Serializable] public class Ellipse { [SerializeField] public float radiusX; [SerializeField] public float radiusY; public Vector2 Evaluate(float t) { var angle = Mathf.Deg2Rad * 360 * t; var x = Mathf.Sin(angle) * radiusX; var y = Mathf.Cos(angle) * radiusY; return new Vector2(x, y); } } }
22.52381
48
0.579281
[ "MIT" ]
yolanother/UnitySpaceGameUtils
Scripts/Runtime/Orbit/Ellipse.cs
473
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Net.Http; using System.Threading; using System.Threading.Tasks; using System.Web.Http; namespace StoreWebApp.Results { public class ChallengeResult : IHttpActionResult { public ChallengeResult(string loginProvider, ApiController controller) { LoginProvider = loginProvider; Request = controller.Request; } public string LoginProvider { get; set; } public HttpRequestMessage Request { get; set; } public Task<HttpResponseMessage> ExecuteAsync(CancellationToken cancellationToken) { Request.GetOwinContext().Authentication.Challenge(LoginProvider); HttpResponseMessage response = new HttpResponseMessage(HttpStatusCode.Unauthorized); response.RequestMessage = Request; return Task.FromResult(response); } } }
29.030303
96
0.694154
[ "Apache-2.0" ]
OctopusCorporation/Store
StoreWebApp/StoreWebApp/Results/ChallengeResult.cs
960
C#
using System.Collections.Generic; using Microsoft.AspNetCore.Authentication.Cookies; using Microsoft.AspNetCore.Authorization; using Microsoft.AspNetCore.Mvc; namespace BlazorHosted.Server.Controllers; [CsrfProtectionCorsPreflight] [Authorize(AuthenticationSchemes = CookieAuthenticationDefaults.AuthenticationScheme)] [ApiController] [Route("api/[controller]")] public class DirectApiController : ControllerBase { [HttpGet] public IEnumerable<string> Get() { return new List<string> { "some data", "more data", "loads of data" }; } }
29.05
87
0.748709
[ "MIT" ]
damienbod/PwaBlazorBffAzureB2C
BlazorBffAzureB2C/Server/Controllers/DirectApiController.cs
583
C#
// Lucene version compatibility level 4.8.1 using J2N.Collections.Generic.Extensions; using Lucene.Net.Analysis; using Lucene.Net.Documents; using Lucene.Net.Documents.Extensions; using Lucene.Net.Index; using Lucene.Net.Index.Extensions; using Lucene.Net.Join; using Lucene.Net.Search; using Lucene.Net.Search.Grouping; using Lucene.Net.Store; using Lucene.Net.Util; using NUnit.Framework; using RandomizedTesting.Generators; using System; using System.Collections.Generic; using System.Globalization; using System.Linq; using System.Text; using Console = Lucene.Net.Util.SystemConsole; namespace Lucene.Net.Tests.Join { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ [Obsolete("Production tests are in Lucene.Net.Search.Join. This class will be removed in 4.8.0 release candidate."), System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)] public class TestBlockJoin : LuceneTestCase { // One resume... private Document MakeResume(string name, string country) { Document resume = new Document(); resume.Add(NewStringField("docType", "resume", Field.Store.NO)); resume.Add(NewStringField("name", name, Field.Store.YES)); resume.Add(NewStringField("country", country, Field.Store.NO)); return resume; } // ... has multiple jobs private Document MakeJob(string skill, int year) { Document job = new Document(); job.Add(NewStringField("skill", skill, Field.Store.YES)); job.Add(new Int32Field("year", year, Field.Store.NO)); job.Add(new StoredField("year", year)); return job; } // ... has multiple qualifications private Document MakeQualification(string qualification, int year) { Document job = new Document(); job.Add(NewStringField("qualification", qualification, Field.Store.YES)); job.Add(new Int32Field("year", year, Field.Store.NO)); return job; } [Test] public void TestEmptyChildFilter() { Directory dir = NewDirectory(); IndexWriterConfig config = new IndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)); config.SetMergePolicy(NoMergePolicy.NO_COMPOUND_FILES); // we don't want to merge - since we rely on certain segment setup IndexWriter w = new IndexWriter(dir, config); IList<Document> docs = new List<Document>(); docs.Add(MakeJob("java", 2007)); docs.Add(MakeJob("python", 2010)); docs.Add(MakeResume("Lisa", "United Kingdom")); w.AddDocuments(docs); docs.Clear(); docs.Add(MakeJob("ruby", 2005)); docs.Add(MakeJob("java", 2006)); docs.Add(MakeResume("Frank", "United States")); w.AddDocuments(docs); w.Commit(); int num = AtLeast(10); // produce a segment that doesn't have a value in the docType field for (int i = 0; i < num; i++) { docs.Clear(); docs.Add(MakeJob("java", 2007)); w.AddDocuments(docs); } IndexReader r = DirectoryReader.Open(w, Random.NextBoolean()); w.Dispose(); assertTrue(r.Leaves.size() > 1); IndexSearcher s = new IndexSearcher(r); Filter parentsFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("docType", "resume")))); BooleanQuery childQuery = new BooleanQuery(); childQuery.Add(new BooleanClause(new TermQuery(new Term("skill", "java")), Occur.MUST)); childQuery.Add(new BooleanClause(NumericRangeQuery.NewInt32Range("year", 2006, 2011, true, true), Occur.MUST)); ToParentBlockJoinQuery childJoinQuery = new ToParentBlockJoinQuery(childQuery, parentsFilter, ScoreMode.Avg); BooleanQuery fullQuery = new BooleanQuery(); fullQuery.Add(new BooleanClause(childJoinQuery, Occur.MUST)); fullQuery.Add(new BooleanClause(new MatchAllDocsQuery(), Occur.MUST)); ToParentBlockJoinCollector c = new ToParentBlockJoinCollector(Sort.RELEVANCE, 1, true, true); s.Search(fullQuery, c); ITopGroups<int> results = c.GetTopGroups(childJoinQuery, null, 0, 10, 0, true); assertFalse(float.IsNaN(results.MaxScore)); assertEquals(1, results.TotalGroupedHitCount); assertEquals(1, results.Groups.Length); IGroupDocs<int> group = results.Groups[0]; Document childDoc = s.Doc(group.ScoreDocs[0].Doc); assertEquals("java", childDoc.Get("skill")); assertNotNull(group.GroupValue); Document parentDoc = s.Doc(group.GroupValue); assertEquals("Lisa", parentDoc.Get("name")); r.Dispose(); dir.Dispose(); } [Test] public void TestSimple() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, dir); IList<Document> docs = new List<Document>(); docs.Add(MakeJob("java", 2007)); docs.Add(MakeJob("python", 2010)); docs.Add(MakeResume("Lisa", "United Kingdom")); w.AddDocuments(docs); docs.Clear(); docs.Add(MakeJob("ruby", 2005)); docs.Add(MakeJob("java", 2006)); docs.Add(MakeResume("Frank", "United States")); w.AddDocuments(docs); IndexReader r = w.GetReader(); w.Dispose(); IndexSearcher s = NewSearcher(r); // Create a filter that defines "parent" documents in the index - in this case resumes Filter parentsFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("docType", "resume")))); // Define child document criteria (finds an example of relevant work experience) BooleanQuery childQuery = new BooleanQuery(); childQuery.Add(new BooleanClause(new TermQuery(new Term("skill", "java")), Occur.MUST)); childQuery.Add(new BooleanClause(NumericRangeQuery.NewInt32Range("year", 2006, 2011, true, true), Occur.MUST)); // Define parent document criteria (find a resident in the UK) Query parentQuery = new TermQuery(new Term("country", "United Kingdom")); // Wrap the child document query to 'join' any matches // up to corresponding parent: ToParentBlockJoinQuery childJoinQuery = new ToParentBlockJoinQuery(childQuery, parentsFilter, ScoreMode.Avg); // Combine the parent and nested child queries into a single query for a candidate BooleanQuery fullQuery = new BooleanQuery(); fullQuery.Add(new BooleanClause(parentQuery, Occur.MUST)); fullQuery.Add(new BooleanClause(childJoinQuery, Occur.MUST)); ToParentBlockJoinCollector c = new ToParentBlockJoinCollector(Sort.RELEVANCE, 1, true, true); s.Search(fullQuery, c); ITopGroups<int> results = c.GetTopGroups(childJoinQuery, null, 0, 10, 0, true); assertFalse(float.IsNaN(results.MaxScore)); //assertEquals(1, results.totalHitCount); assertEquals(1, results.TotalGroupedHitCount); assertEquals(1, results.Groups.Length); IGroupDocs<int> group = results.Groups[0]; assertEquals(1, group.TotalHits); assertFalse(float.IsNaN(group.Score)); Document childDoc = s.Doc(group.ScoreDocs[0].Doc); //System.out.println(" doc=" + group.ScoreDocs[0].Doc); assertEquals("java", childDoc.Get("skill")); assertNotNull(group.GroupValue); Document parentDoc = s.Doc(group.GroupValue); assertEquals("Lisa", parentDoc.Get("name")); //System.out.println("TEST: now test up"); // Now join "up" (map parent hits to child docs) instead...: ToChildBlockJoinQuery parentJoinQuery = new ToChildBlockJoinQuery(parentQuery, parentsFilter, Random.NextBoolean()); BooleanQuery fullChildQuery = new BooleanQuery(); fullChildQuery.Add(new BooleanClause(parentJoinQuery, Occur.MUST)); fullChildQuery.Add(new BooleanClause(childQuery, Occur.MUST)); //System.out.println("FULL: " + fullChildQuery); TopDocs hits = s.Search(fullChildQuery, 10); assertEquals(1, hits.TotalHits); childDoc = s.Doc(hits.ScoreDocs[0].Doc); //System.out.println("CHILD = " + childDoc + " docID=" + hits.ScoreDocs[0].Doc); assertEquals("java", childDoc.Get("skill")); assertEquals(2007, childDoc.GetField("year").GetInt32ValueOrDefault()); assertEquals("Lisa", GetParentDoc(r, parentsFilter, hits.ScoreDocs[0].Doc).Get("name")); // Test with filter on child docs: assertEquals(0, s.Search(fullChildQuery, new QueryWrapperFilter(new TermQuery(new Term("skill", "foosball"))), 1).TotalHits); r.Dispose(); dir.Dispose(); } [Test] public void TestBugCausedByRewritingTwice() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, dir); IList<Document> docs = new List<Document>(); for (int i = 0; i < 10; i++) { docs.Clear(); docs.Add(MakeJob("ruby", i)); docs.Add(MakeJob("java", 2007)); docs.Add(MakeResume("Frank", "United States")); w.AddDocuments(docs); } IndexReader r = w.GetReader(); w.Dispose(); IndexSearcher s = NewSearcher(r); MultiTermQuery qc = NumericRangeQuery.NewInt32Range("year", 2007, 2007, true, true); // Hacky: this causes the query to need 2 rewrite // iterations: qc.MultiTermRewriteMethod = MultiTermQuery.CONSTANT_SCORE_BOOLEAN_QUERY_REWRITE; Filter parentsFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("docType", "resume")))); int h1 = qc.GetHashCode(); Query qw1 = qc.Rewrite(r); int h2 = qw1.GetHashCode(); Query qw2 = qw1.Rewrite(r); int h3 = qw2.GetHashCode(); assertTrue(h1 != h2); assertTrue(h2 != h3); assertTrue(h3 != h1); ToParentBlockJoinQuery qp = new ToParentBlockJoinQuery(qc, parentsFilter, ScoreMode.Max); ToParentBlockJoinCollector c = new ToParentBlockJoinCollector(Sort.RELEVANCE, 10, true, true); s.Search(qp, c); ITopGroups<int> groups = c.GetTopGroups(qp, Sort.INDEXORDER, 0, 10, 0, true); foreach (GroupDocs<int> group in groups.Groups) { assertEquals(1, group.TotalHits); } r.Dispose(); dir.Dispose(); } protected QueryWrapperFilter Skill(string skill) { return new QueryWrapperFilter(new TermQuery(new Term("skill", skill))); } [Test] public virtual void TestSimpleFilter() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, dir); IList<Document> docs = new List<Document>(); docs.Add(MakeJob("java", 2007)); docs.Add(MakeJob("python", 2010)); docs.Shuffle(Random); docs.Add(MakeResume("Lisa", "United Kingdom")); IList<Document> docs2 = new List<Document>(); docs2.Add(MakeJob("ruby", 2005)); docs2.Add(MakeJob("java", 2006)); docs2.Shuffle(Random); docs2.Add(MakeResume("Frank", "United States")); AddSkillless(w); bool turn = Random.NextBoolean(); w.AddDocuments(turn ? docs : docs2); AddSkillless(w); w.AddDocuments(!turn ? docs : docs2); AddSkillless(w); IndexReader r = w.GetReader(); w.Dispose(); IndexSearcher s = NewSearcher(r); // Create a filter that defines "parent" documents in the index - in this case resumes Filter parentsFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("docType", "resume")))); // Define child document criteria (finds an example of relevant work experience) BooleanQuery childQuery = new BooleanQuery(); childQuery.Add(new BooleanClause(new TermQuery(new Term("skill", "java")), Occur.MUST)); childQuery.Add(new BooleanClause(NumericRangeQuery.NewInt32Range("year", 2006, 2011, true, true), Occur.MUST)); // Define parent document criteria (find a resident in the UK) Query parentQuery = new TermQuery(new Term("country", "United Kingdom")); // Wrap the child document query to 'join' any matches // up to corresponding parent: ToParentBlockJoinQuery childJoinQuery = new ToParentBlockJoinQuery(childQuery, parentsFilter, ScoreMode.Avg); assertEquals("no filter - both passed", 2, s.Search(childJoinQuery, 10).TotalHits); assertEquals("dummy filter passes everyone ", 2, s.Search(childJoinQuery, parentsFilter, 10).TotalHits); assertEquals("dummy filter passes everyone ", 2, s.Search(childJoinQuery, new QueryWrapperFilter(new TermQuery(new Term("docType", "resume"))), 10).TotalHits); // not found test assertEquals("noone live there", 0, s.Search(childJoinQuery, new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("country", "Oz")))), 1).TotalHits); assertEquals("noone live there", 0, s.Search(childJoinQuery, new QueryWrapperFilter(new TermQuery(new Term("country", "Oz"))), 1).TotalHits); // apply the UK filter by the searcher TopDocs ukOnly = s.Search(childJoinQuery, new QueryWrapperFilter(parentQuery), 1); assertEquals("has filter - single passed", 1, ukOnly.TotalHits); assertEquals("Lisa", r.Document(ukOnly.ScoreDocs[0].Doc).Get("name")); // looking for US candidates TopDocs usThen = s.Search(childJoinQuery, new QueryWrapperFilter(new TermQuery(new Term("country", "United States"))), 1); assertEquals("has filter - single passed", 1, usThen.TotalHits); assertEquals("Frank", r.Document(usThen.ScoreDocs[0].Doc).Get("name")); TermQuery us = new TermQuery(new Term("country", "United States")); assertEquals("@ US we have java and ruby", 2, s.Search(new ToChildBlockJoinQuery(us, parentsFilter, Random.NextBoolean()), 10).TotalHits); assertEquals("java skills in US", 1, s.Search(new ToChildBlockJoinQuery(us, parentsFilter, Random.NextBoolean()), Skill("java"), 10).TotalHits); BooleanQuery rubyPython = new BooleanQuery(); rubyPython.Add(new TermQuery(new Term("skill", "ruby")), Occur.SHOULD); rubyPython.Add(new TermQuery(new Term("skill", "python")), Occur.SHOULD); assertEquals("ruby skills in US", 1, s.Search(new ToChildBlockJoinQuery(us, parentsFilter, Random.NextBoolean()), new QueryWrapperFilter(rubyPython), 10).TotalHits); r.Dispose(); dir.Dispose(); } private void AddSkillless(RandomIndexWriter w) { if (Random.NextBoolean()) { w.AddDocument(MakeResume("Skillless", Random.NextBoolean() ? "United Kingdom" : "United States")); } } private Document GetParentDoc(IndexReader reader, Filter parents, int childDocID) { IList<AtomicReaderContext> leaves = reader.Leaves; int subIndex = ReaderUtil.SubIndex(childDocID, leaves); AtomicReaderContext leaf = leaves[subIndex]; FixedBitSet bits = (FixedBitSet)parents.GetDocIdSet(leaf, null); return leaf.AtomicReader.Document(bits.NextSetBit(childDocID - leaf.DocBase)); } [Test] public void TestBoostBug() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, dir); IndexReader r = w.GetReader(); w.Dispose(); IndexSearcher s = NewSearcher(r); ToParentBlockJoinQuery q = new ToParentBlockJoinQuery(new MatchAllDocsQuery(), new QueryWrapperFilter(new MatchAllDocsQuery()), ScoreMode.Avg); QueryUtils.Check(Random, q, s); s.Search(q, 10); BooleanQuery bq = new BooleanQuery(); bq.Boost = 2f; // we boost the BQ bq.Add(q, Occur.MUST); s.Search(bq, 10); r.Dispose(); dir.Dispose(); } [Test] public void TestNestedDocScoringWithDeletes() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(NoMergePolicy.COMPOUND_FILES)); // Cannot assert this since we use NoMergePolicy: w.DoRandomForceMergeAssert = false; IList<Document> docs = new List<Document>(); docs.Add(MakeJob("java", 2007)); docs.Add(MakeJob("python", 2010)); docs.Add(MakeResume("Lisa", "United Kingdom")); w.AddDocuments(docs); docs.Clear(); docs.Add(MakeJob("c", 1999)); docs.Add(MakeJob("ruby", 2005)); docs.Add(MakeJob("java", 2006)); docs.Add(MakeResume("Frank", "United States")); w.AddDocuments(docs); w.Commit(); IndexSearcher s = NewSearcher(DirectoryReader.Open(dir)); ToParentBlockJoinQuery q = new ToParentBlockJoinQuery( NumericRangeQuery.NewInt32Range("year", 1990, 2010, true, true), new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("docType", "resume")))), ScoreMode.Total ); TopDocs topDocs = s.Search(q, 10); assertEquals(2, topDocs.TotalHits); assertEquals(6, topDocs.ScoreDocs[0].Doc); assertEquals(3.0f, topDocs.ScoreDocs[0].Score, 0.0f); assertEquals(2, topDocs.ScoreDocs[1].Doc); assertEquals(2.0f, topDocs.ScoreDocs[1].Score, 0.0f); s.IndexReader.Dispose(); w.DeleteDocuments(new Term("skill", "java")); w.Dispose(); s = NewSearcher(DirectoryReader.Open(dir)); topDocs = s.Search(q, 10); assertEquals(2, topDocs.TotalHits); assertEquals(6, topDocs.ScoreDocs[0].Doc); assertEquals(2.0f, topDocs.ScoreDocs[0].Score, 0.0f); assertEquals(2, topDocs.ScoreDocs[1].Doc); assertEquals(1.0f, topDocs.ScoreDocs[1].Score, 0.0f); s.IndexReader.Dispose(); dir.Dispose(); } private string[][] GetRandomFields(int maxUniqueValues) { string[][] fields = new string[TestUtil.NextInt32(Random, 2, 4)][]; for (int fieldID = 0; fieldID < fields.Length; fieldID++) { int valueCount; if (fieldID == 0) { valueCount = 2; } else { valueCount = TestUtil.NextInt32(Random, 1, maxUniqueValues); } string[] values = fields[fieldID] = new string[valueCount]; for (int i = 0; i < valueCount; i++) { values[i] = TestUtil.RandomRealisticUnicodeString(Random); //values[i] = TestUtil.randomSimpleString(random); } } return fields; } private Term RandomParentTerm(string[] values) { return new Term("parent0", values[Random.Next(values.Length)]); } private Term RandomChildTerm(string[] values) { return new Term("child0", values[Random.Next(values.Length)]); } private Sort GetRandomSort(string prefix, int numFields) { List<SortField> sortFields = new List<SortField>(); // TODO: sometimes sort by score; problem is scores are // not comparable across the two indices // sortFields.Add(SortField.FIELD_SCORE); if (Random.NextBoolean()) { sortFields.Add(new SortField(prefix + Random.Next(numFields), SortFieldType.STRING, Random.NextBoolean())); } else if (Random.NextBoolean()) { sortFields.Add(new SortField(prefix + Random.Next(numFields), SortFieldType.STRING, Random.NextBoolean())); sortFields.Add(new SortField(prefix + Random.Next(numFields), SortFieldType.STRING, Random.NextBoolean())); } // Break ties: sortFields.Add(new SortField(prefix + "ID", SortFieldType.INT32)); return new Sort(sortFields.ToArray()); } [Test] public void TestRandom() { // We build two indices at once: one normalized (which // ToParentBlockJoinQuery/Collector, // ToChildBlockJoinQuery can query) and the other w/ // the same docs, just fully denormalized: Directory dir = NewDirectory(); Directory joinDir = NewDirectory(); int numParentDocs = TestUtil.NextInt32(Random, 100 * RandomMultiplier, 300 * RandomMultiplier); //int numParentDocs = 30; // Values for parent fields: string[][] parentFields = GetRandomFields(numParentDocs / 2); // Values for child fields: string[][] childFields = GetRandomFields(numParentDocs); bool doDeletes = Random.NextBoolean(); IList<int> toDelete = new List<int>(); // TODO: parallel star join, nested join cases too! RandomIndexWriter w = new RandomIndexWriter(Random, dir); RandomIndexWriter joinW = new RandomIndexWriter(Random, joinDir); for (int parentDocID = 0; parentDocID < numParentDocs; parentDocID++) { Document parentDoc = new Document(); Document parentJoinDoc = new Document(); Field id = NewStringField("parentID", "" + parentDocID, Field.Store.YES); parentDoc.Add(id); parentJoinDoc.Add(id); parentJoinDoc.Add(NewStringField("isParent", "x", Field.Store.NO)); for (int field = 0; field < parentFields.Length; field++) { if (Random.NextDouble() < 0.9) { Field f = NewStringField("parent" + field, parentFields[field][Random.Next(parentFields[field].Length)], Field.Store.NO); parentDoc.Add(f); parentJoinDoc.Add(f); } } if (doDeletes) { parentDoc.Add(NewStringField("blockID", "" + parentDocID, Field.Store.NO)); parentJoinDoc.Add(NewStringField("blockID", "" + parentDocID, Field.Store.NO)); } IList<Document> joinDocs = new List<Document>(); if (Verbose) { StringBuilder sb = new StringBuilder(); sb.Append("parentID=").Append(parentDoc.Get("parentID")); for (int fieldID = 0; fieldID < parentFields.Length; fieldID++) { string parent = parentDoc.Get("parent" + fieldID); if (parent != null) { sb.Append(" parent" + fieldID + "=" + parent); } } Console.WriteLine(" " + sb); } int numChildDocs = TestUtil.NextInt32(Random, 1, 20); for (int childDocID = 0; childDocID < numChildDocs; childDocID++) { // Denormalize: copy all parent fields into child doc: Document childDoc = TestUtil.CloneDocument(parentDoc); Document joinChildDoc = new Document(); joinDocs.Add(joinChildDoc); Field childID = NewStringField("childID", "" + childDocID, Field.Store.YES); childDoc.Add(childID); joinChildDoc.Add(childID); for (int childFieldID = 0; childFieldID < childFields.Length; childFieldID++) { if (Random.NextDouble() < 0.9) { Field f = NewStringField("child" + childFieldID, childFields[childFieldID][Random.Next(childFields[childFieldID].Length)], Field.Store.NO); childDoc.Add(f); joinChildDoc.Add(f); } } if (Verbose) { StringBuilder sb = new StringBuilder(); sb.Append("childID=").Append(joinChildDoc.Get("childID")); for (int fieldID = 0; fieldID < childFields.Length; fieldID++) { string child = joinChildDoc.Get("child" + fieldID); if (child != null) { sb.Append(" child" + fieldID + "=" + child); } } Console.WriteLine(" " + sb); } if (doDeletes) { joinChildDoc.Add(NewStringField("blockID", "" + parentDocID, Field.Store.NO)); } w.AddDocument(childDoc); } // Parent last: joinDocs.Add(parentJoinDoc); joinW.AddDocuments(joinDocs); if (doDeletes && Random.Next(30) == 7) { toDelete.Add(parentDocID); } } foreach (int deleteID in toDelete) { if (Verbose) { Console.WriteLine("DELETE parentID=" + deleteID); } w.DeleteDocuments(new Term("blockID", "" + deleteID)); joinW.DeleteDocuments(new Term("blockID", "" + deleteID)); } IndexReader r = w.GetReader(); w.Dispose(); IndexReader joinR = joinW.GetReader(); joinW.Dispose(); if (Verbose) { Console.WriteLine("TEST: reader=" + r); Console.WriteLine("TEST: joinReader=" + joinR); for (int docIDX = 0; docIDX < joinR.MaxDoc; docIDX++) { Console.WriteLine(" docID=" + docIDX + " doc=" + joinR.Document(docIDX)); } } IndexSearcher s = NewSearcher(r); IndexSearcher joinS = new IndexSearcher(joinR); Filter parentsFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("isParent", "x")))); int iters = 200 * RandomMultiplier; for (int iter = 0; iter < iters; iter++) { if (Verbose) { Console.WriteLine("TEST: iter=" + (1 + iter) + " of " + iters); } Query childQuery; if (Random.Next(3) == 2) { int childFieldID = Random.Next(childFields.Length); childQuery = new TermQuery(new Term("child" + childFieldID, childFields[childFieldID][Random.Next(childFields[childFieldID].Length)])); } else if (Random.Next(3) == 2) { BooleanQuery bq = new BooleanQuery(); childQuery = bq; int numClauses = TestUtil.NextInt32(Random, 2, 4); bool didMust = false; for (int clauseIDX = 0; clauseIDX < numClauses; clauseIDX++) { Query clause; Occur occur; if (!didMust && Random.NextBoolean()) { occur = Random.NextBoolean() ? Occur.MUST : Occur.MUST_NOT; clause = new TermQuery(RandomChildTerm(childFields[0])); didMust = true; } else { occur = Occur.SHOULD; int childFieldID = TestUtil.NextInt32(Random, 1, childFields.Length - 1); clause = new TermQuery(new Term("child" + childFieldID, childFields[childFieldID][Random.Next(childFields[childFieldID].Length)])); } bq.Add(clause, occur); } } else { BooleanQuery bq = new BooleanQuery(); childQuery = bq; bq.Add(new TermQuery(RandomChildTerm(childFields[0])), Occur.MUST); int childFieldID = TestUtil.NextInt32(Random, 1, childFields.Length - 1); bq.Add(new TermQuery(new Term("child" + childFieldID, childFields[childFieldID][Random.Next(childFields[childFieldID].Length)])), Random.NextBoolean() ? Occur.MUST : Occur.MUST_NOT); } int x = Random.Next(4); ScoreMode agg; if (x == 0) { agg = ScoreMode.None; } else if (x == 1) { agg = ScoreMode.Max; } else if (x == 2) { agg = ScoreMode.Total; } else { agg = ScoreMode.Avg; } ToParentBlockJoinQuery childJoinQuery = new ToParentBlockJoinQuery(childQuery, parentsFilter, agg); // To run against the block-join index: Query parentJoinQuery; // Same query as parentJoinQuery, but to run against // the fully denormalized index (so we can compare // results): Query parentQuery; if (Random.NextBoolean()) { parentQuery = childQuery; parentJoinQuery = childJoinQuery; } else { // AND parent field w/ child field BooleanQuery bq = new BooleanQuery(); parentJoinQuery = bq; Term parentTerm = RandomParentTerm(parentFields[0]); if (Random.NextBoolean()) { bq.Add(childJoinQuery, Occur.MUST); bq.Add(new TermQuery(parentTerm), Occur.MUST); } else { bq.Add(new TermQuery(parentTerm), Occur.MUST); bq.Add(childJoinQuery, Occur.MUST); } BooleanQuery bq2 = new BooleanQuery(); parentQuery = bq2; if (Random.NextBoolean()) { bq2.Add(childQuery, Occur.MUST); bq2.Add(new TermQuery(parentTerm), Occur.MUST); } else { bq2.Add(new TermQuery(parentTerm), Occur.MUST); bq2.Add(childQuery, Occur.MUST); } } Sort parentSort = GetRandomSort("parent", parentFields.Length); Sort childSort = GetRandomSort("child", childFields.Length); if (Verbose) { Console.WriteLine("\nTEST: query=" + parentQuery + " joinQuery=" + parentJoinQuery + " parentSort=" + parentSort + " childSort=" + childSort); } // Merge both sorts: List<SortField> sortFields = new List<SortField>(parentSort.GetSort()); sortFields.AddRange(childSort.GetSort()); Sort parentAndChildSort = new Sort(sortFields.ToArray()); TopDocs results = s.Search(parentQuery, null, r.NumDocs, parentAndChildSort); if (Verbose) { Console.WriteLine("\nTEST: normal index gets " + results.TotalHits + " hits"); ScoreDoc[] hits = results.ScoreDocs; for (int hitIDX = 0; hitIDX < hits.Length; hitIDX++) { Document doc = s.Doc(hits[hitIDX].Doc); //System.out.println(" score=" + hits[hitIDX].Score + " parentID=" + doc.Get("parentID") + " childID=" + doc.Get("childID") + " (docID=" + hits[hitIDX].Doc + ")"); Console.WriteLine(" parentID=" + doc.Get("parentID") + " childID=" + doc.Get("childID") + " (docID=" + hits[hitIDX].Doc + ")"); FieldDoc fd = (FieldDoc)hits[hitIDX]; if (fd.Fields != null) { Console.Write(" "); foreach (object o in fd.Fields) { if (o is BytesRef) { Console.Write(((BytesRef)o).Utf8ToString() + " "); } else { Console.Write(o + " "); } } Console.WriteLine(); } } } bool trackScores; bool trackMaxScore; if (agg == ScoreMode.None) { trackScores = false; trackMaxScore = false; } else { trackScores = Random.NextBoolean(); trackMaxScore = Random.NextBoolean(); } ToParentBlockJoinCollector c = new ToParentBlockJoinCollector(parentSort, 10, trackScores, trackMaxScore); joinS.Search(parentJoinQuery, c); int hitsPerGroup = TestUtil.NextInt32(Random, 1, 20); //final int hitsPerGroup = 100; ITopGroups<int> joinResults = c.GetTopGroups(childJoinQuery, childSort, 0, hitsPerGroup, 0, true); if (Verbose) { Console.WriteLine("\nTEST: block join index gets " + (joinResults is null ? 0 : joinResults.Groups.Length) + " groups; hitsPerGroup=" + hitsPerGroup); if (joinResults != null) { IGroupDocs<int>[] groups = joinResults.Groups; for (int groupIDX = 0; groupIDX < groups.Length; groupIDX++) { IGroupDocs<int> group = groups[groupIDX]; if (group.GroupSortValues != null) { Console.Write(" "); foreach (object o in group.GroupSortValues) { if (o is BytesRef) { Console.Write(((BytesRef)o).Utf8ToString() + " "); } else { Console.Write(o + " "); } } Console.WriteLine(); } assertNotNull(group.GroupValue); Document parentDoc = joinS.Doc(group.GroupValue); Console.WriteLine(" group parentID=" + parentDoc.Get("parentID") + " (docID=" + group.GroupValue + ")"); for (int hitIDX = 0; hitIDX < group.ScoreDocs.Length; hitIDX++) { Document doc = joinS.Doc(group.ScoreDocs[hitIDX].Doc); //System.out.println(" score=" + group.ScoreDocs[hitIDX].Score + " childID=" + doc.Get("childID") + " (docID=" + group.ScoreDocs[hitIDX].Doc + ")"); Console.WriteLine(" childID=" + doc.Get("childID") + " child0=" + doc.Get("child0") + " (docID=" + group.ScoreDocs[hitIDX].Doc + ")"); } } } } if (results.TotalHits == 0) { assertNull(joinResults); } else { CompareHits(r, joinR, results, joinResults); TopDocs b = joinS.Search(childJoinQuery, 10); foreach (ScoreDoc hit in b.ScoreDocs) { Explanation explanation = joinS.Explain(childJoinQuery, hit.Doc); Document document = joinS.Doc(hit.Doc - 1); int childId = Convert.ToInt32(document.Get("childID"), CultureInfo.InvariantCulture); assertTrue(explanation.IsMatch); assertEquals(hit.Score, explanation.Value, 0.0f); assertEquals(string.Format("Score based on child doc range from {0} to {1}", hit.Doc - 1 - childId, hit.Doc - 1), explanation.Description); } } // Test joining in the opposite direction (parent to // child): // Get random query against parent documents: Query parentQuery2; if (Random.Next(3) == 2) { int fieldID = Random.Next(parentFields.Length); parentQuery2 = new TermQuery(new Term("parent" + fieldID, parentFields[fieldID][Random.Next(parentFields[fieldID].Length)])); } else if (Random.Next(3) == 2) { BooleanQuery bq = new BooleanQuery(); parentQuery2 = bq; int numClauses = TestUtil.NextInt32(Random, 2, 4); bool didMust = false; for (int clauseIDX = 0; clauseIDX < numClauses; clauseIDX++) { Query clause; Occur occur; if (!didMust && Random.NextBoolean()) { occur = Random.NextBoolean() ? Occur.MUST : Occur.MUST_NOT; clause = new TermQuery(RandomParentTerm(parentFields[0])); didMust = true; } else { occur = Occur.SHOULD; int fieldID = TestUtil.NextInt32(Random, 1, parentFields.Length - 1); clause = new TermQuery(new Term("parent" + fieldID, parentFields[fieldID][Random.Next(parentFields[fieldID].Length)])); } bq.Add(clause, occur); } } else { BooleanQuery bq = new BooleanQuery(); parentQuery2 = bq; bq.Add(new TermQuery(RandomParentTerm(parentFields[0])), Occur.MUST); int fieldID = TestUtil.NextInt32(Random, 1, parentFields.Length - 1); bq.Add(new TermQuery(new Term("parent" + fieldID, parentFields[fieldID][Random.Next(parentFields[fieldID].Length)])), Random.NextBoolean() ? Occur.MUST : Occur.MUST_NOT); } if (Verbose) { Console.WriteLine("\nTEST: top down: parentQuery2=" + parentQuery2); } // Maps parent query to child docs: ToChildBlockJoinQuery parentJoinQuery2 = new ToChildBlockJoinQuery(parentQuery2, parentsFilter, Random.NextBoolean()); // To run against the block-join index: Query childJoinQuery2; // Same query as parentJoinQuery, but to run against // the fully denormalized index (so we can compare // results): Query childQuery2; // apply a filter to children Filter childFilter2, childJoinFilter2; if (Random.NextBoolean()) { childQuery2 = parentQuery2; childJoinQuery2 = parentJoinQuery2; childFilter2 = null; childJoinFilter2 = null; } else { Term childTerm = RandomChildTerm(childFields[0]); if (Random.NextBoolean()) // filtered case { childJoinQuery2 = parentJoinQuery2; Filter f = new QueryWrapperFilter(new TermQuery(childTerm)); childJoinFilter2 = Random.NextBoolean() ? new FixedBitSetCachingWrapperFilter(f) : f; } else { childJoinFilter2 = null; // AND child field w/ parent query: BooleanQuery bq = new BooleanQuery(); childJoinQuery2 = bq; if (Random.NextBoolean()) { bq.Add(parentJoinQuery2, Occur.MUST); bq.Add(new TermQuery(childTerm), Occur.MUST); } else { bq.Add(new TermQuery(childTerm), Occur.MUST); bq.Add(parentJoinQuery2, Occur.MUST); } } if (Random.NextBoolean()) // filtered case { childQuery2 = parentQuery2; Filter f = new QueryWrapperFilter(new TermQuery(childTerm)); childFilter2 = Random.NextBoolean() ? new FixedBitSetCachingWrapperFilter(f) : f; } else { childFilter2 = null; BooleanQuery bq2 = new BooleanQuery(); childQuery2 = bq2; if (Random.NextBoolean()) { bq2.Add(parentQuery2, Occur.MUST); bq2.Add(new TermQuery(childTerm), Occur.MUST); } else { bq2.Add(new TermQuery(childTerm), Occur.MUST); bq2.Add(parentQuery2, Occur.MUST); } } } Sort childSort2 = GetRandomSort("child", childFields.Length); // Search denormalized index: if (Verbose) { Console.WriteLine("TEST: run top down query=" + childQuery2 + " filter=" + childFilter2 + " sort=" + childSort2); } TopDocs results2 = s.Search(childQuery2, childFilter2, r.NumDocs, childSort2); if (Verbose) { Console.WriteLine(" " + results2.TotalHits + " totalHits:"); foreach (ScoreDoc sd in results2.ScoreDocs) { Document doc = s.Doc(sd.Doc); Console.WriteLine(" childID=" + doc.Get("childID") + " parentID=" + doc.Get("parentID") + " docID=" + sd.Doc); } } // Search join index: if (Verbose) { Console.WriteLine("TEST: run top down join query=" + childJoinQuery2 + " filter=" + childJoinFilter2 + " sort=" + childSort2); } TopDocs joinResults2 = joinS.Search(childJoinQuery2, childJoinFilter2, joinR.NumDocs, childSort2); if (Verbose) { Console.WriteLine(" " + joinResults2.TotalHits + " totalHits:"); foreach (ScoreDoc sd in joinResults2.ScoreDocs) { Document doc = joinS.Doc(sd.Doc); Document parentDoc = GetParentDoc(joinR, parentsFilter, sd.Doc); Console.WriteLine(" childID=" + doc.Get("childID") + " parentID=" + parentDoc.Get("parentID") + " docID=" + sd.Doc); } } CompareChildHits(r, joinR, results2, joinResults2); } r.Dispose(); joinR.Dispose(); dir.Dispose(); joinDir.Dispose(); } private void CompareChildHits(IndexReader r, IndexReader joinR, TopDocs results, TopDocs joinResults) { assertEquals(results.TotalHits, joinResults.TotalHits); assertEquals(results.ScoreDocs.Length, joinResults.ScoreDocs.Length); for (int hitCount = 0; hitCount < results.ScoreDocs.Length; hitCount++) { ScoreDoc hit = results.ScoreDocs[hitCount]; ScoreDoc joinHit = joinResults.ScoreDocs[hitCount]; Document doc1 = r.Document(hit.Doc); Document doc2 = joinR.Document(joinHit.Doc); assertEquals("hit " + hitCount + " differs", doc1.Get("childID"), doc2.Get("childID")); // don't compare scores -- they are expected to differ assertTrue(hit is FieldDoc); assertTrue(joinHit is FieldDoc); FieldDoc hit0 = (FieldDoc)hit; FieldDoc joinHit0 = (FieldDoc)joinHit; assertArrayEquals(hit0.Fields, joinHit0.Fields); } } private void CompareHits(IndexReader r, IndexReader joinR, TopDocs results, ITopGroups<int> joinResults) { // results is 'complete'; joinResults is a subset int resultUpto = 0; int joinGroupUpto = 0; ScoreDoc[] hits = results.ScoreDocs; IGroupDocs<int>[] groupDocs = joinResults.Groups; while (joinGroupUpto < groupDocs.Length) { IGroupDocs<int> group = groupDocs[joinGroupUpto++]; ScoreDoc[] groupHits = group.ScoreDocs; assertNotNull(group.GroupValue); Document parentDoc = joinR.Document(group.GroupValue); string parentID = parentDoc.Get("parentID"); //System.out.println("GROUP groupDoc=" + group.groupDoc + " parent=" + parentDoc); assertNotNull(parentID); assertTrue(groupHits.Length > 0); for (int hitIDX = 0; hitIDX < groupHits.Length; hitIDX++) { Document nonJoinHit = r.Document(hits[resultUpto++].Doc); Document joinHit = joinR.Document(groupHits[hitIDX].Doc); assertEquals(parentID, nonJoinHit.Get("parentID")); assertEquals(joinHit.Get("childID"), nonJoinHit.Get("childID")); } if (joinGroupUpto < groupDocs.Length) { // Advance non-join hit to the next parentID: //System.out.println(" next joingroupUpto=" + joinGroupUpto + " gd.Length=" + groupDocs.Length + " parentID=" + parentID); while (true) { assertTrue(resultUpto < hits.Length); if (!parentID.Equals(r.Document(hits[resultUpto].Doc).Get("parentID"), StringComparison.Ordinal)) { break; } resultUpto++; } } } } [Test] public void TestMultiChildTypes() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, dir); IList<Document> docs = new List<Document>(); docs.Add(MakeJob("java", 2007)); docs.Add(MakeJob("python", 2010)); docs.Add(MakeQualification("maths", 1999)); docs.Add(MakeResume("Lisa", "United Kingdom")); w.AddDocuments(docs); IndexReader r = w.GetReader(); w.Dispose(); IndexSearcher s = NewSearcher(r); // Create a filter that defines "parent" documents in the index - in this case resumes Filter parentsFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("docType", "resume")))); // Define child document criteria (finds an example of relevant work experience) BooleanQuery childJobQuery = new BooleanQuery(); childJobQuery.Add(new BooleanClause(new TermQuery(new Term("skill", "java")), Occur.MUST)); childJobQuery.Add(new BooleanClause(NumericRangeQuery.NewInt32Range("year", 2006, 2011, true, true), Occur.MUST)); BooleanQuery childQualificationQuery = new BooleanQuery(); childQualificationQuery.Add(new BooleanClause(new TermQuery(new Term("qualification", "maths")), Occur.MUST)); childQualificationQuery.Add(new BooleanClause(NumericRangeQuery.NewInt32Range("year", 1980, 2000, true, true), Occur.MUST)); // Define parent document criteria (find a resident in the UK) Query parentQuery = new TermQuery(new Term("country", "United Kingdom")); // Wrap the child document query to 'join' any matches // up to corresponding parent: ToParentBlockJoinQuery childJobJoinQuery = new ToParentBlockJoinQuery(childJobQuery, parentsFilter, ScoreMode.Avg); ToParentBlockJoinQuery childQualificationJoinQuery = new ToParentBlockJoinQuery(childQualificationQuery, parentsFilter, ScoreMode.Avg); // Combine the parent and nested child queries into a single query for a candidate BooleanQuery fullQuery = new BooleanQuery(); fullQuery.Add(new BooleanClause(parentQuery, Occur.MUST)); fullQuery.Add(new BooleanClause(childJobJoinQuery, Occur.MUST)); fullQuery.Add(new BooleanClause(childQualificationJoinQuery, Occur.MUST)); // Collects all job and qualification child docs for // each resume hit in the top N (sorted by score): ToParentBlockJoinCollector c = new ToParentBlockJoinCollector(Sort.RELEVANCE, 10, true, false); s.Search(fullQuery, c); // Examine "Job" children ITopGroups<int> jobResults = c.GetTopGroups(childJobJoinQuery, null, 0, 10, 0, true); //assertEquals(1, results.totalHitCount); assertEquals(1, jobResults.TotalGroupedHitCount); assertEquals(1, jobResults.Groups.Length); IGroupDocs<int> group = jobResults.Groups[0]; assertEquals(1, group.TotalHits); Document childJobDoc = s.Doc(group.ScoreDocs[0].Doc); //System.out.println(" doc=" + group.ScoreDocs[0].Doc); assertEquals("java", childJobDoc.Get("skill")); assertNotNull(group.GroupValue); Document parentDoc = s.Doc(group.GroupValue); assertEquals("Lisa", parentDoc.Get("name")); // Now Examine qualification children ITopGroups<int> qualificationResults = c.GetTopGroups(childQualificationJoinQuery, null, 0, 10, 0, true); assertEquals(1, qualificationResults.TotalGroupedHitCount); assertEquals(1, qualificationResults.Groups.Length); IGroupDocs<int> qGroup = qualificationResults.Groups[0]; assertEquals(1, qGroup.TotalHits); Document childQualificationDoc = s.Doc(qGroup.ScoreDocs[0].Doc); assertEquals("maths", childQualificationDoc.Get("qualification")); assertNotNull(qGroup.GroupValue); parentDoc = s.Doc(qGroup.GroupValue); assertEquals("Lisa", parentDoc.Get("name")); r.Dispose(); dir.Dispose(); } [Test] public void TestAdvanceSingleParentSingleChild() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, dir); Document childDoc = new Document(); childDoc.Add(NewStringField("child", "1", Field.Store.NO)); Document parentDoc = new Document(); parentDoc.Add(NewStringField("parent", "1", Field.Store.NO)); w.AddDocuments(new Document[] { childDoc, parentDoc }); IndexReader r = w.GetReader(); w.Dispose(); IndexSearcher s = NewSearcher(r); Query tq = new TermQuery(new Term("child", "1")); Filter parentFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("parent", "1")))); ToParentBlockJoinQuery q = new ToParentBlockJoinQuery(tq, parentFilter, ScoreMode.Avg); Weight weight = s.CreateNormalizedWeight(q); DocIdSetIterator disi = weight.GetScorer(s.IndexReader.Leaves.First(), null); assertEquals(1, disi.Advance(1)); r.Dispose(); dir.Dispose(); } [Test] public void TestAdvanceSingleParentNoChild() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, dir, NewIndexWriterConfig(TEST_VERSION_CURRENT, new MockAnalyzer(Random)).SetMergePolicy(new LogDocMergePolicy())); Document parentDoc = new Document(); parentDoc.Add(NewStringField("parent", "1", Field.Store.NO)); parentDoc.Add(NewStringField("isparent", "yes", Field.Store.NO)); w.AddDocuments(new Document[] { parentDoc }); // Add another doc so scorer is not null parentDoc = new Document(); parentDoc.Add(NewStringField("parent", "2", Field.Store.NO)); parentDoc.Add(NewStringField("isparent", "yes", Field.Store.NO)); Document childDoc = new Document(); childDoc.Add(NewStringField("child", "2", Field.Store.NO)); w.AddDocuments(new Document[] { childDoc, parentDoc }); // Need single seg: w.ForceMerge(1); IndexReader r = w.GetReader(); w.Dispose(); IndexSearcher s = NewSearcher(r); Query tq = new TermQuery(new Term("child", "2")); Filter parentFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("isparent", "yes")))); ToParentBlockJoinQuery q = new ToParentBlockJoinQuery(tq, parentFilter, ScoreMode.Avg); Weight weight = s.CreateNormalizedWeight(q); DocIdSetIterator disi = weight.GetScorer(s.IndexReader.Leaves.First(), null); assertEquals(2, disi.Advance(0)); r.Dispose(); dir.Dispose(); } [Test] public void TestGetTopGroups() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, dir); IList<Document> docs = new List<Document>(); docs.Add(MakeJob("ruby", 2005)); docs.Add(MakeJob("java", 2006)); docs.Add(MakeJob("java", 2010)); docs.Add(MakeJob("java", 2012)); docs.Shuffle(Random); docs.Add(MakeResume("Frank", "United States")); AddSkillless(w); w.AddDocuments(docs); AddSkillless(w); IndexReader r = w.GetReader(); w.Dispose(); IndexSearcher s = new IndexSearcher(r); // Create a filter that defines "parent" documents in the index - in this case resumes Filter parentsFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("docType", "resume")))); // Define child document criteria (finds an example of relevant work experience) BooleanQuery childQuery = new BooleanQuery(); childQuery.Add(new BooleanClause(new TermQuery(new Term("skill", "java")), Occur.MUST)); childQuery.Add(new BooleanClause(NumericRangeQuery.NewInt32Range("year", 2006, 2011, true, true), Occur.MUST)); // Wrap the child document query to 'join' any matches // up to corresponding parent: ToParentBlockJoinQuery childJoinQuery = new ToParentBlockJoinQuery(childQuery, parentsFilter, ScoreMode.Avg); ToParentBlockJoinCollector c = new ToParentBlockJoinCollector(Sort.RELEVANCE, 2, true, true); s.Search(childJoinQuery, c); //Get all child documents within groups ITopGroups<int>[] getTopGroupsResults = new ITopGroups<int>[2]; getTopGroupsResults[0] = c.GetTopGroups(childJoinQuery, null, 0, 10, 0, true); getTopGroupsResults[1] = c.GetTopGroupsWithAllChildDocs(childJoinQuery, null, 0, 0, true); foreach (ITopGroups<int> results in getTopGroupsResults) { assertFalse(float.IsNaN(results.MaxScore)); assertEquals(2, results.TotalGroupedHitCount); assertEquals(1, results.Groups.Length); IGroupDocs<int> resultGroup = results.Groups[0]; assertEquals(2, resultGroup.TotalHits); assertFalse(float.IsNaN(resultGroup.Score)); assertNotNull(resultGroup.GroupValue); Document parentDocument = s.Doc(resultGroup.GroupValue); assertEquals("Frank", parentDocument.Get("name")); assertEquals(2, resultGroup.ScoreDocs.Length); //all matched child documents collected foreach (ScoreDoc scoreDoc in resultGroup.ScoreDocs) { Document childDoc = s.Doc(scoreDoc.Doc); assertEquals("java", childDoc.Get("skill")); int year = Convert.ToInt32(childDoc.Get("year"), CultureInfo.InvariantCulture); assertTrue(year >= 2006 && year <= 2011); } } //Get part of child documents ITopGroups<int> boundedResults = c.GetTopGroups(childJoinQuery, null, 0, 1, 0, true); assertFalse(float.IsNaN(boundedResults.MaxScore)); assertEquals(2, boundedResults.TotalGroupedHitCount); assertEquals(1, boundedResults.Groups.Length); IGroupDocs<int> group = boundedResults.Groups[0]; assertEquals(2, group.TotalHits); assertFalse(float.IsNaN(group.Score)); assertNotNull(group.GroupValue); Document parentDoc = s.Doc(group.GroupValue); assertEquals("Frank", parentDoc.Get("name")); assertEquals(1, group.ScoreDocs.Length); //not all matched child documents collected foreach (ScoreDoc scoreDoc in group.ScoreDocs) { Document childDoc = s.Doc(scoreDoc.Doc); assertEquals("java", childDoc.Get("skill")); int year = Convert.ToInt32(childDoc.Get("year"), CultureInfo.InvariantCulture); assertTrue(year >= 2006 && year <= 2011); } r.Dispose(); dir.Dispose(); } // LUCENE-4968 [Test] public void TestSometimesParentOnlyMatches() { Directory d = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, d); Document parent = new Document(); parent.Add(new StoredField("parentID", "0")); parent.Add(NewTextField("parentText", "text", Field.Store.NO)); parent.Add(NewStringField("isParent", "yes", Field.Store.NO)); IList<Document> docs = new List<Document>(); Document child = new Document(); docs.Add(child); child.Add(new StoredField("childID", "0")); child.Add(NewTextField("childText", "text", Field.Store.NO)); // parent last: docs.Add(parent); w.AddDocuments(docs); docs.Clear(); parent = new Document(); parent.Add(NewTextField("parentText", "text", Field.Store.NO)); parent.Add(NewStringField("isParent", "yes", Field.Store.NO)); parent.Add(new StoredField("parentID", "1")); // parent last: docs.Add(parent); w.AddDocuments(docs); IndexReader r = w.GetReader(); w.Dispose(); Query childQuery = new TermQuery(new Term("childText", "text")); Filter parentsFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("isParent", "yes")))); ToParentBlockJoinQuery childJoinQuery = new ToParentBlockJoinQuery(childQuery, parentsFilter, ScoreMode.Avg); BooleanQuery parentQuery = new BooleanQuery(); parentQuery.Add(childJoinQuery, Occur.SHOULD); parentQuery.Add(new TermQuery(new Term("parentText", "text")), Occur.SHOULD); ToParentBlockJoinCollector c = new ToParentBlockJoinCollector(new Sort(new SortField("parentID", SortFieldType.STRING)), 10, true, true); NewSearcher(r).Search(parentQuery, c); ITopGroups<int> groups = c.GetTopGroups(childJoinQuery, null, 0, 10, 0, false); // Two parents: assertEquals(2, (int)groups.TotalGroupCount); // One child docs: assertEquals(1, groups.TotalGroupedHitCount); IGroupDocs<int> group = groups.Groups[0]; Document doc = r.Document((int)group.GroupValue); assertEquals("0", doc.Get("parentID")); group = groups.Groups[1]; doc = r.Document((int)group.GroupValue); assertEquals("1", doc.Get("parentID")); r.Dispose(); d.Dispose(); } // LUCENE-4968 [Test] public void TestChildQueryNeverMatches() { Directory d = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, d); Document parent = new Document(); parent.Add(new StoredField("parentID", "0")); parent.Add(NewTextField("parentText", "text", Field.Store.NO)); parent.Add(NewStringField("isParent", "yes", Field.Store.NO)); IList<Document> docs = new List<Document>(); Document child = new Document(); docs.Add(child); child.Add(new StoredField("childID", "0")); child.Add(NewTextField("childText", "text", Field.Store.NO)); // parent last: docs.Add(parent); w.AddDocuments(docs); docs.Clear(); parent = new Document(); parent.Add(NewTextField("parentText", "text", Field.Store.NO)); parent.Add(NewStringField("isParent", "yes", Field.Store.NO)); parent.Add(new StoredField("parentID", "1")); // parent last: docs.Add(parent); w.AddDocuments(docs); IndexReader r = w.GetReader(); w.Dispose(); // never matches: Query childQuery = new TermQuery(new Term("childText", "bogus")); Filter parentsFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("isParent", "yes")))); ToParentBlockJoinQuery childJoinQuery = new ToParentBlockJoinQuery(childQuery, parentsFilter, ScoreMode.Avg); BooleanQuery parentQuery = new BooleanQuery(); parentQuery.Add(childJoinQuery, Occur.SHOULD); parentQuery.Add(new TermQuery(new Term("parentText", "text")), Occur.SHOULD); ToParentBlockJoinCollector c = new ToParentBlockJoinCollector(new Sort(new SortField("parentID", SortFieldType.STRING)), 10, true, true); NewSearcher(r).Search(parentQuery, c); ITopGroups<int> groups = c.GetTopGroups(childJoinQuery, null, 0, 10, 0, false); // Two parents: assertEquals(2, (int)groups.TotalGroupCount); // One child docs: assertEquals(0, groups.TotalGroupedHitCount); IGroupDocs<int> group = groups.Groups[0]; Document doc = r.Document((int)group.GroupValue); assertEquals("0", doc.Get("parentID")); group = groups.Groups[1]; doc = r.Document((int)group.GroupValue); assertEquals("1", doc.Get("parentID")); r.Dispose(); d.Dispose(); } // LUCENE-4968 [Test] public void TestChildQueryMatchesParent() { Directory d = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, d); Document parent = new Document(); parent.Add(new StoredField("parentID", "0")); parent.Add(NewTextField("parentText", "text", Field.Store.NO)); parent.Add(NewStringField("isParent", "yes", Field.Store.NO)); IList<Document> docs = new List<Document>(); Document child = new Document(); docs.Add(child); child.Add(new StoredField("childID", "0")); child.Add(NewTextField("childText", "text", Field.Store.NO)); // parent last: docs.Add(parent); w.AddDocuments(docs); docs.Clear(); parent = new Document(); parent.Add(NewTextField("parentText", "text", Field.Store.NO)); parent.Add(NewStringField("isParent", "yes", Field.Store.NO)); parent.Add(new StoredField("parentID", "1")); // parent last: docs.Add(parent); w.AddDocuments(docs); IndexReader r = w.GetReader(); w.Dispose(); // illegally matches parent: Query childQuery = new TermQuery(new Term("parentText", "text")); Filter parentsFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("isParent", "yes")))); ToParentBlockJoinQuery childJoinQuery = new ToParentBlockJoinQuery(childQuery, parentsFilter, ScoreMode.Avg); BooleanQuery parentQuery = new BooleanQuery(); parentQuery.Add(childJoinQuery, Occur.SHOULD); parentQuery.Add(new TermQuery(new Term("parentText", "text")), Occur.SHOULD); ToParentBlockJoinCollector c = new ToParentBlockJoinCollector(new Sort(new SortField("parentID", SortFieldType.STRING)), 10, true, true); try { NewSearcher(r).Search(parentQuery, c); fail("should have hit exception"); } catch (Exception ise) when (ise.IsIllegalStateException()) { // expected } r.Dispose(); d.Dispose(); } [Test] public void TestAdvanceSingleDeletedParentNoChild() { Directory dir = NewDirectory(); RandomIndexWriter w = new RandomIndexWriter(Random, dir); // First doc with 1 children Document parentDoc = new Document(); parentDoc.Add(NewStringField("parent", "1", Field.Store.NO)); parentDoc.Add(NewStringField("isparent", "yes", Field.Store.NO)); Document childDoc = new Document(); childDoc.Add(NewStringField("child", "1", Field.Store.NO)); w.AddDocuments(new Document[] { childDoc, parentDoc }); parentDoc = new Document(); parentDoc.Add(NewStringField("parent", "2", Field.Store.NO)); parentDoc.Add(NewStringField("isparent", "yes", Field.Store.NO)); w.AddDocuments(new Document[] { parentDoc }); w.DeleteDocuments(new Term("parent", "2")); parentDoc = new Document(); parentDoc.Add(NewStringField("parent", "2", Field.Store.NO)); parentDoc.Add(NewStringField("isparent", "yes", Field.Store.NO)); childDoc = new Document(); childDoc.Add(NewStringField("child", "2", Field.Store.NO)); w.AddDocuments(new Document[] { childDoc, parentDoc }); IndexReader r = w.GetReader(); w.Dispose(); IndexSearcher s = NewSearcher(r); // Create a filter that defines "parent" documents in the index - in this case resumes Filter parentsFilter = new FixedBitSetCachingWrapperFilter(new QueryWrapperFilter(new TermQuery(new Term("isparent", "yes")))); Query parentQuery = new TermQuery(new Term("parent", "2")); ToChildBlockJoinQuery parentJoinQuery = new ToChildBlockJoinQuery(parentQuery, parentsFilter, Random.NextBoolean()); TopDocs topdocs = s.Search(parentJoinQuery, 3); assertEquals(1, topdocs.TotalHits); r.Dispose(); dir.Dispose(); } } }
45.639975
210
0.528344
[ "Apache-2.0" ]
10088/lucenenet
src/Lucene.Net.Tests.Join/Support/TestBlockJoin.cs
71,918
C#
using NPOI.OpenXml4Net.Util; using System; using System.Collections.Generic; using System.IO; using System.Xml; using System.Xml.Serialization; namespace NPOI.OpenXmlFormats.Wordprocessing { [Serializable] [XmlRoot(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main", IsNullable = true)] [XmlType(Namespace = "http://schemas.openxmlformats.org/wordprocessingml/2006/main")] public class CT_TblGridChange : CT_Markup { private List<CT_TblGridCol> tblGridField; [XmlArrayItem("gridCol", IsNullable = false)] [XmlArray(Order = 0)] public List<CT_TblGridCol> tblGrid { get { return tblGridField; } set { tblGridField = value; } } public new static CT_TblGridChange Parse(XmlNode node, XmlNamespaceManager namespaceManager) { if (node == null) { return null; } CT_TblGridChange cT_TblGridChange = new CT_TblGridChange(); cT_TblGridChange.id = XmlHelper.ReadString(node.Attributes["r:id"]); cT_TblGridChange.tblGrid = new List<CT_TblGridCol>(); foreach (XmlNode childNode in node.ChildNodes) { if (childNode.LocalName == "tblGrid") { cT_TblGridChange.tblGrid.Add(CT_TblGridCol.Parse(childNode, namespaceManager)); } } return cT_TblGridChange; } internal new void Write(StreamWriter sw, string nodeName) { sw.Write(string.Format("<w:{0}", nodeName)); XmlHelper.WriteAttribute(sw, "r:id", base.id); sw.Write(">"); if (tblGrid != null) { foreach (CT_TblGridCol item in tblGrid) { item.Write(sw, "tblGrid"); } } sw.Write(string.Format("</w:{0}>", nodeName)); } } }
24.651515
105
0.69453
[ "MIT" ]
iNeverSleeeeep/NPOI-For-Unity
NPOI.OpenXmlFormats.Wordprocessing/CT_TblGridChange.cs
1,627
C#
//------------------------------------------------------------------------------ // <auto-generated> // Este código fue generado por una herramienta. // Versión de runtime:4.0.30319.42000 // // Los cambios en este archivo podrían causar un comportamiento incorrecto y se perderán si // se vuelve a generar el código. // </auto-generated> //------------------------------------------------------------------------------ using System; using System.Reflection; [assembly: System.Reflection.AssemblyCompanyAttribute("WebAPI.JSON.CRUD")] [assembly: System.Reflection.AssemblyConfigurationAttribute("Debug")] [assembly: System.Reflection.AssemblyFileVersionAttribute("1.0.0.0")] [assembly: System.Reflection.AssemblyInformationalVersionAttribute("1.0.0")] [assembly: System.Reflection.AssemblyProductAttribute("WebAPI.JSON.CRUD")] [assembly: System.Reflection.AssemblyTitleAttribute("WebAPI.JSON.CRUD")] [assembly: System.Reflection.AssemblyVersionAttribute("1.0.0.0")] // Generado por la clase WriteCodeFragment de MSBuild.
43.291667
95
0.6564
[ "MIT" ]
FernandoCalmet/DOTNET-6-ASPNET-Core-JSON-CRUD
WebAPI.JSON.CRUD/obj/Debug/net6.0/WebAPI.JSON.CRUD.AssemblyInfo.cs
1,044
C#
using System; using System.Collections.Generic; using NHapi.Base.Log; using NHapi.Model.V22.Group; using NHapi.Model.V22.Segment; using NHapi.Model.V22.Datatype; using NHapi.Base; using NHapi.Base.Parser; using NHapi.Base.Model; namespace NHapi.Model.V22.Message { ///<summary> /// Represents a NMD_N01 message structure (see chapter [AAA]). This structure contains the /// following elements: ///<ol> ///<li>0: MSH (MESSAGE HEADER) </li> ///<li>1: NMD_N01_CLOCK_AND_STATS_WITH_NOTES (a Group object) repeating</li> ///</ol> ///</summary> [Serializable] public class NMD_N01 : AbstractMessage { ///<summary> /// Creates a new NMD_N01 Group with custom IModelClassFactory. ///</summary> public NMD_N01(IModelClassFactory factory) : base(factory){ init(factory); } ///<summary> /// Creates a new NMD_N01 Group with DefaultModelClassFactory. ///</summary> public NMD_N01() : base(new DefaultModelClassFactory()) { init(new DefaultModelClassFactory()); } ///<summary> /// initalize method for NMD_N01. This does the segment setup for the message. ///</summary> private void init(IModelClassFactory factory) { try { this.add(typeof(MSH), true, false); this.add(typeof(NMD_N01_CLOCK_AND_STATS_WITH_NOTES), true, true); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error creating NMD_N01 - this is probably a bug in the source code generator.", e); } } public override string Version { get{ return Constants.VERSION; } } ///<summary> /// Returns MSH (MESSAGE HEADER) - creates it if necessary ///</summary> public MSH MSH { get{ MSH ret = null; try { ret = (MSH)this.GetStructure("MSH"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } } ///<summary> /// Returns first repetition of NMD_N01_CLOCK_AND_STATS_WITH_NOTES (a Group object) - creates it if necessary ///</summary> public NMD_N01_CLOCK_AND_STATS_WITH_NOTES GetCLOCK_AND_STATS_WITH_NOTES() { NMD_N01_CLOCK_AND_STATS_WITH_NOTES ret = null; try { ret = (NMD_N01_CLOCK_AND_STATS_WITH_NOTES)this.GetStructure("CLOCK_AND_STATS_WITH_NOTES"); } catch(HL7Exception e) { HapiLogFactory.GetHapiLog(GetType()).Error("Unexpected error accessing data - this is probably a bug in the source code generator.", e); throw new System.Exception("An unexpected error ocurred",e); } return ret; } ///<summary> ///Returns a specific repetition of NMD_N01_CLOCK_AND_STATS_WITH_NOTES /// * (a Group object) - creates it if necessary /// throws HL7Exception if the repetition requested is more than one /// greater than the number of existing repetitions. ///</summary> public NMD_N01_CLOCK_AND_STATS_WITH_NOTES GetCLOCK_AND_STATS_WITH_NOTES(int rep) { return (NMD_N01_CLOCK_AND_STATS_WITH_NOTES)this.GetStructure("CLOCK_AND_STATS_WITH_NOTES", rep); } /** * Returns the number of existing repetitions of NMD_N01_CLOCK_AND_STATS_WITH_NOTES */ public int CLOCK_AND_STATS_WITH_NOTESRepetitionsUsed { get{ int reps = -1; try { reps = this.GetAll("CLOCK_AND_STATS_WITH_NOTES").Length; } catch (HL7Exception e) { string message = "Unexpected error accessing data - this is probably a bug in the source code generator."; HapiLogFactory.GetHapiLog(GetType()).Error(message, e); throw new System.Exception(message); } return reps; } } /** * Enumerate over the NMD_N01_CLOCK_AND_STATS_WITH_NOTES results */ public IEnumerable<NMD_N01_CLOCK_AND_STATS_WITH_NOTES> CLOCK_AND_STATS_WITH_NOTESs { get { for (int rep = 0; rep < CLOCK_AND_STATS_WITH_NOTESRepetitionsUsed; rep++) { yield return (NMD_N01_CLOCK_AND_STATS_WITH_NOTES)this.GetStructure("CLOCK_AND_STATS_WITH_NOTES", rep); } } } ///<summary> ///Adds a new NMD_N01_CLOCK_AND_STATS_WITH_NOTES ///</summary> public NMD_N01_CLOCK_AND_STATS_WITH_NOTES AddCLOCK_AND_STATS_WITH_NOTES() { return this.AddStructure("CLOCK_AND_STATS_WITH_NOTES") as NMD_N01_CLOCK_AND_STATS_WITH_NOTES; } ///<summary> ///Removes the given NMD_N01_CLOCK_AND_STATS_WITH_NOTES ///</summary> public void RemoveCLOCK_AND_STATS_WITH_NOTES(NMD_N01_CLOCK_AND_STATS_WITH_NOTES toRemove) { this.RemoveStructure("CLOCK_AND_STATS_WITH_NOTES", toRemove); } ///<summary> ///Removes the NMD_N01_CLOCK_AND_STATS_WITH_NOTES at the given index ///</summary> public void RemoveCLOCK_AND_STATS_WITH_NOTESAt(int index) { this.RemoveRepetition("CLOCK_AND_STATS_WITH_NOTES", index); } } }
30.851613
145
0.723338
[ "MPL-2.0", "MPL-2.0-no-copyleft-exception" ]
AMCN41R/nHapi
src/NHapi.Model.V22/Message/NMD_N01.cs
4,782
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 athena-2017-05-18.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.Athena.Model; using Amazon.Runtime; using Amazon.Runtime.Internal; using Amazon.Runtime.Internal.Transform; using Amazon.Runtime.Internal.Util; using ThirdParty.Json.LitJson; namespace Amazon.Athena.Model.Internal.MarshallTransformations { /// <summary> /// ResultConfiguration Marshaller /// </summary> public class ResultConfigurationMarshaller : IRequestMarshaller<ResultConfiguration, JsonMarshallerContext> { /// <summary> /// Unmarshaller the response from the service to the response class. /// </summary> /// <param name="requestObject"></param> /// <param name="context"></param> /// <returns></returns> public void Marshall(ResultConfiguration requestObject, JsonMarshallerContext context) { if(requestObject.IsSetEncryptionConfiguration()) { context.Writer.WritePropertyName("EncryptionConfiguration"); context.Writer.WriteObjectStart(); var marshaller = EncryptionConfigurationMarshaller.Instance; marshaller.Marshall(requestObject.EncryptionConfiguration, context); context.Writer.WriteObjectEnd(); } if(requestObject.IsSetOutputLocation()) { context.Writer.WritePropertyName("OutputLocation"); context.Writer.Write(requestObject.OutputLocation); } } /// <summary> /// Singleton Marshaller. /// </summary> public readonly static ResultConfigurationMarshaller Instance = new ResultConfigurationMarshaller(); } }
34.164384
112
0.680433
[ "Apache-2.0" ]
ianb888/aws-sdk-net
sdk/src/Services/Athena/Generated/Model/Internal/MarshallTransformations/ResultConfigurationMarshaller.cs
2,494
C#
using System; using System.Collections.Generic; using System.Collections.Immutable; using System.Text; using System.Text.RegularExpressions; using System.Web; using System.Runtime.Serialization; using System.Reflection; using TinyJson; using System.Collections; #nullable enable // Loosely based on https://github.com/wildbit/mustachio #pragma warning disable CA1303 // Do not pass literals as localized parameters namespace NoJsonTextMustache { public enum TokenType { Content, Comment, CollectionOpen, CollectionClose, InvertedElement, EscapedElement, UnEscapedElement } public class Token { public TokenType Type { get; set; } public string Value { get; set; } = ""; // Doesn't preserve spaces and exact char used for unescaped element public override string ToString() { var s = Type switch { TokenType.Content => Value, TokenType.Comment => $"{{{{!{Value}}}}}", TokenType.CollectionOpen => $"{{{{#{Value}}}}}", TokenType.CollectionClose => $"{{{{/{Value}}}}}", TokenType.InvertedElement => $"{{{{^{Value}}}}}", TokenType.UnEscapedElement => $"{{{{{{{Value}}}}}", TokenType.EscapedElement => $"{{{{{Value}}}}}", _ => "" }; return s; } } public static class Parser { private static readonly Regex _tokenFinder = new Regex("([{]{2}[^{}]+?[}]{2})|([{]{3}[^{}]+?[}]{3})", RegexOptions.Compiled | RegexOptions.Compiled); public static IEnumerable<Token> Tokenize(string template) { var matches = _tokenFinder.Matches(template); var idx = 0; var tokens = new List<Token>(); foreach (Match? m in matches) { if(m == null) throw new Exception("How can a regex match be null?"); // Capture text that comes before a mustache tag if(m.Index > idx) tokens.Add(new Token { Type = TokenType.Content, Value = template.Substring(idx, m.Index - idx)}); if(m.Value.StartsWith("{{#", StringComparison.InvariantCulture)) { var token = m.Value.TrimStart('{').TrimEnd('}').TrimStart('#').Trim(); tokens.Add(new Token { Type = TokenType.CollectionOpen, Value = token }); } else if(m.Value.StartsWith("{{/", StringComparison.InvariantCulture)) { var token = m.Value.TrimStart('{').TrimEnd('}').TrimStart('/').Trim(); tokens.Add(new Token { Type = TokenType.CollectionClose, Value = token }); } else if(m.Value.StartsWith("{{^", StringComparison.InvariantCulture)) { var token = m.Value.TrimStart('{').TrimEnd('}').TrimStart('^').Trim(); tokens.Add(new Token { Type = TokenType.InvertedElement, Value = token }); } else if (m.Value.StartsWith("{{{", StringComparison.InvariantCulture) | m.Value.StartsWith("{{&", StringComparison.InvariantCulture)) { var token = m.Value.TrimStart('{').TrimEnd('}').TrimStart('&').Trim(); tokens.Add(new Token { Type = TokenType.UnEscapedElement, Value = token }); } else if(m.Value.StartsWith("{{!", StringComparison.InvariantCulture)) { var token = m.Value.TrimStart('{').TrimEnd('}').TrimStart('!'); tokens.Add(new Token { Type = TokenType.Comment, Value = token }); } else if(m.Value.StartsWith("{{", StringComparison.InvariantCulture)) { var token = m.Value.TrimStart('{').TrimEnd('}'); tokens.Add(new Token { Type = TokenType.EscapedElement, Value = token }); } else { throw new Exception("Unknown mustache tag."); } idx = m.Index + m.Length; } if(idx < template.Length) tokens.Add(new Token { Type = TokenType.Content, Value = template.Substring(idx)}); return tokens; } static (Collection, IEnumerator<Token>) HandleContent(Token content, IEnumerator<Token> rest, Collection tree) => (new Collection { Name = tree.Name, Nodes = tree.Nodes.ToImmutableList().Add(new Content { Text = content.Value}) }, rest); static (Collection, IEnumerator<Token>) HandleComment(Token _, IEnumerator<Token> rest, Collection tree) => (tree, rest); static (Collection, IEnumerator<Token>) HandleEscapedVariable(Token variable, IEnumerator<Token> rest, Collection tree) => (new Collection { Name = tree.Name, Nodes = tree.Nodes.ToImmutableList().Add(new EscapedVariable { Name = variable.Value }) }, rest); static (Collection, IEnumerator<Token>) HandleUnEscapedVariable(Token variable, IEnumerator<Token> rest, Collection tree) => (new Collection { Name = tree.Name, Nodes = tree.Nodes.ToImmutableList().Add(new UnEscapedVariable { Name = variable.Value }) }, rest); static (Collection, IEnumerator<Token>) HandleOpenCollection(Token open, IEnumerator<Token> rest, Collection tree) { var c = open.Value.Length == 0 ? new Collection { Name = "" } : new Collection { Name = open.Value }; var shouldExit = false; var stillTokens = rest.MoveNext(); while(!shouldExit && stillTokens) { var t = rest.Current; switch (t.Type) { case TokenType.Content: (c, rest) = HandleContent(t, rest, c); break; case TokenType.Comment: (c, rest) = HandleComment(t, rest, c); break; case TokenType.CollectionOpen: (c, rest) = HandleOpenCollection(t, rest, c); break; case TokenType.CollectionClose: if(t.Value == open.Value) shouldExit = true; break; case TokenType.InvertedElement: break; case TokenType.EscapedElement: (c, rest) = HandleEscapedVariable(t, rest, c); break; case TokenType.UnEscapedElement: (c, rest) = HandleUnEscapedVariable(t, rest, c); break; default: break; } if(!shouldExit) stillTokens = rest.MoveNext(); } if(open.Value.Length == 0) return (c, rest); // top value collection else return (new Collection {Name = tree.Name, Nodes = tree.Nodes.ToImmutableArray().Add(c) } , rest); } static public Collection Parse(IEnumerable<Token> tokens) { if(tokens == null) throw new ArgumentNullException(nameof(tokens)); var en = tokens.GetEnumerator(); var c = new Collection(); var rootToken = new Token { Type = TokenType.CollectionOpen, Value = ""}; var (res, rest) = HandleOpenCollection(rootToken, en, c); return res; } static string FindProperty(string name, ImmutableStack<object> path) { while(!path.IsEmpty) { path = path.Pop(out var el); var d = el as Dictionary<string,object>; if(d != null) { var found = d.TryGetValue(name, out var val); if(found) return val!.ToString()!; } } return ""; } static StringBuilder RenderNode(Node n, StringBuilder sb, ImmutableStack<object> path) => n switch { Content c => sb.Append(c.Text), EscapedVariable e => sb.Append(HttpUtility.HtmlEncode(FindProperty(e.Name, path))), UnEscapedVariable u => sb.Append(FindProperty(u.Name, path)), Collection c => RenderCollection(c, sb, path), _ => sb.Append("UNKNOWN NODE") }; static StringBuilder RenderCollection(Collection c, StringBuilder sb, ImmutableStack<object> path) { var coll = (path.Peek() as Dictionary<string, object>); if(coll is null) throw new Exception("Shouldn't get here as passing a collection ..."); var found = coll.TryGetValue(c.Name, out var el); if(!found) return sb; path = path.Push(el!); if(el is bool && (bool)el == false) return sb; if(el is List<object> && (el as List<object>)!.Count == 0) return sb; if(el is bool && (bool)el == true) { // Object for initial collection sb = RenderObject(c, sb, path); } // . Otherwise for each object render node with json object updated to current else if(el is List<object>) { foreach (var subEl in (el as List<object>)!) { foreach (var n in c.Nodes) { sb = RenderNode(n, sb, path.Push(subEl)); } } } // . We can't be on a node that is not an array or a bool else { throw new ArgumentException($"{nameof(el)} at {c.Name} is not a bool or array node"); } return sb; } static StringBuilder RenderObject(Collection c, StringBuilder sb, ImmutableStack<object> path) { foreach (var n in c.Nodes) { sb = RenderNode(n, sb, path); } return sb; } public static string Render(Collection c, string jsonText) { if(c == null) throw new ArgumentNullException(nameof(c)); var vars = jsonText.FromJson<object>(); var sb = new StringBuilder(); sb = RenderObject(c, sb, ImmutableStack.Create<object>(vars)); var s = sb.ToString(); return s; } } public abstract class Node { } public class Content: Node { public string Text { get;set;} = ""; } public class EscapedVariable: Node { public string Name { get;set;} = ""; } public class UnEscapedVariable: Node { public string Name { get;set;} = ""; } public class Collection: Node { public string Name { get; set;} = ""; public IEnumerable<Node> Nodes { get; set; } = new List<Node>(); } } #nullable disable // From: https://github.com/zanders3/json namespace TinyJson { // Really simple JSON parser in ~300 lines // - Attempts to parse JSON files with minimal GC allocation // - Nice and simple "[1,2,3]".FromJson<List<int>>() API // - Classes and structs can be parsed too! // class Foo { public int Value; } // "{\"Value\":10}".FromJson<Foo>() // - Can parse JSON without type information into Dictionary<string,object> and List<object> e.g. // "[1,2,3]".FromJson<object>().GetType() == typeof(List<object>) // "{\"Value\":10}".FromJson<object>().GetType() == typeof(Dictionary<string,object>) // - No JIT Emit support to support AOT compilation on iOS // - Attempts are made to NOT throw an exception if the JSON is corrupted or invalid: returns null instead. // - Only public fields and property setters on classes/structs will be written to // // Limitations: // - No JIT Emit support to parse structures quickly // - Limited to parsing <2GB JSON files (due to int.MaxValue) // - Parsing of abstract classes or interfaces is NOT supported and will throw an exception. public static class JSONParser { [ThreadStatic] static Stack<List<string>> splitArrayPool; [ThreadStatic] static StringBuilder stringBuilder; [ThreadStatic] static Dictionary<Type, Dictionary<string, FieldInfo>> fieldInfoCache; [ThreadStatic] static Dictionary<Type, Dictionary<string, PropertyInfo>> propertyInfoCache; public static T FromJson<T>(this string json) { // Initialize, if needed, the ThreadStatic variables if (propertyInfoCache == null) propertyInfoCache = new Dictionary<Type, Dictionary<string, PropertyInfo>>(); if (fieldInfoCache == null) fieldInfoCache = new Dictionary<Type, Dictionary<string, FieldInfo>>(); if (stringBuilder == null) stringBuilder = new StringBuilder(); if (splitArrayPool == null) splitArrayPool = new Stack<List<string>>(); //Remove all whitespace not within strings to make parsing simpler stringBuilder.Length = 0; for (int i = 0; i < json.Length; i++) { char c = json[i]; if (c == '"') { i = AppendUntilStringEnd(true, i, json); continue; } if (char.IsWhiteSpace(c)) continue; stringBuilder.Append(c); } //Parse the thing! return (T)ParseValue(typeof(T), stringBuilder.ToString()); } static int AppendUntilStringEnd(bool appendEscapeCharacter, int startIdx, string json) { stringBuilder.Append(json[startIdx]); for (int i = startIdx+1; i<json.Length; i++) { if (json[i] == '\\') { if (appendEscapeCharacter) stringBuilder.Append(json[i]); stringBuilder.Append(json[i + 1]); i++;//Skip next character as it is escaped } else if (json[i] == '"') { stringBuilder.Append(json[i]); return i; } else stringBuilder.Append(json[i]); } return json.Length - 1; } //Splits { <value>:<value>, <value>:<value> } and [ <value>, <value> ] into a list of <value> strings static List<string> Split(string json) { List<string> splitArray = splitArrayPool.Count > 0 ? splitArrayPool.Pop() : new List<string>(); splitArray.Clear(); if(json.Length == 2) return splitArray; int parseDepth = 0; stringBuilder.Length = 0; for (int i = 1; i<json.Length-1; i++) { switch (json[i]) { case '[': case '{': parseDepth++; break; case ']': case '}': parseDepth--; break; case '"': i = AppendUntilStringEnd(true, i, json); continue; case ',': case ':': if (parseDepth == 0) { splitArray.Add(stringBuilder.ToString()); stringBuilder.Length = 0; continue; } break; } stringBuilder.Append(json[i]); } splitArray.Add(stringBuilder.ToString()); return splitArray; } internal static object ParseValue(Type type, string json) { if (type == typeof(string)) { if (json.Length <= 2) return string.Empty; StringBuilder parseStringBuilder = new StringBuilder(json.Length); for (int i = 1; i<json.Length-1; ++i) { if (json[i] == '\\' && i + 1 < json.Length - 1) { int j = "\"\\nrtbf/".IndexOf(json[i + 1]); if (j >= 0) { parseStringBuilder.Append("\"\\\n\r\t\b\f/"[j]); ++i; continue; } if (json[i + 1] == 'u' && i + 5 < json.Length - 1) { UInt32 c = 0; if (UInt32.TryParse(json.Substring(i + 2, 4), System.Globalization.NumberStyles.AllowHexSpecifier, null, out c)) { parseStringBuilder.Append((char)c); i += 5; continue; } } } parseStringBuilder.Append(json[i]); } return parseStringBuilder.ToString(); } if (type.IsPrimitive) { var result = Convert.ChangeType(json, type, System.Globalization.CultureInfo.InvariantCulture); return result; } if (type == typeof(decimal)) { decimal result; decimal.TryParse(json, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out result); return result; } if (json == "null") { return null; } if (type.IsEnum) { if (json[0] == '"') json = json.Substring(1, json.Length - 2); try { return Enum.Parse(type, json, false); } catch { return 0; } } if (type.IsArray) { Type arrayType = type.GetElementType(); if (json[0] != '[' || json[json.Length - 1] != ']') return null; List<string> elems = Split(json); Array newArray = Array.CreateInstance(arrayType, elems.Count); for (int i = 0; i < elems.Count; i++) newArray.SetValue(ParseValue(arrayType, elems[i]), i); splitArrayPool.Push(elems); return newArray; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(List<>)) { Type listType = type.GetGenericArguments()[0]; if (json[0] != '[' || json[json.Length - 1] != ']') return null; List<string> elems = Split(json); var list = (IList)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count }); for (int i = 0; i < elems.Count; i++) list.Add(ParseValue(listType, elems[i])); splitArrayPool.Push(elems); return list; } if (type.IsGenericType && type.GetGenericTypeDefinition() == typeof(Dictionary<,>)) { Type keyType, valueType; { Type[] args = type.GetGenericArguments(); keyType = args[0]; valueType = args[1]; } //Refuse to parse dictionary keys that aren't of type string if (keyType != typeof(string)) return null; //Must be a valid dictionary element if (json[0] != '{' || json[json.Length - 1] != '}') return null; //The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON List<string> elems = Split(json); if (elems.Count % 2 != 0) return null; var dictionary = (IDictionary)type.GetConstructor(new Type[] { typeof(int) }).Invoke(new object[] { elems.Count / 2 }); for (int i = 0; i < elems.Count; i += 2) { if (elems[i].Length <= 2) continue; string keyValue = elems[i].Substring(1, elems[i].Length - 2); object val = ParseValue(valueType, elems[i + 1]); dictionary.Add(keyValue, val); } return dictionary; } if (type == typeof(object)) { return ParseAnonymousValue(json); } if (json[0] == '{' && json[json.Length - 1] == '}') { return ParseObject(type, json); } return null; } static object ParseAnonymousValue(string json) { if (json.Length == 0) return null; if (json[0] == '{' && json[json.Length - 1] == '}') { List<string> elems = Split(json); if (elems.Count % 2 != 0) return null; var dict = new Dictionary<string, object>(elems.Count / 2); for (int i = 0; i < elems.Count; i += 2) dict.Add(elems[i].Substring(1, elems[i].Length - 2), ParseAnonymousValue(elems[i + 1])); return dict; } if (json[0] == '[' && json[json.Length - 1] == ']') { List<string> items = Split(json); var finalList = new List<object>(items.Count); for (int i = 0; i < items.Count; i++) finalList.Add(ParseAnonymousValue(items[i])); return finalList; } if (json[0] == '"' && json[json.Length - 1] == '"') { string str = json.Substring(1, json.Length - 2); return str.Replace("\\", string.Empty); } if (char.IsDigit(json[0]) || json[0] == '-') { if (json.Contains(".")) { double result; double.TryParse(json, System.Globalization.NumberStyles.Float, System.Globalization.CultureInfo.InvariantCulture, out result); return result; } else { int result; int.TryParse(json, out result); return result; } } if (json == "true") return true; if (json == "false") return false; // handles json == "null" as well as invalid JSON return null; } static Dictionary<string, T> CreateMemberNameDictionary<T>(T[] members) where T : MemberInfo { Dictionary<string, T> nameToMember = new Dictionary<string, T>(StringComparer.OrdinalIgnoreCase); for (int i = 0; i < members.Length; i++) { T member = members[i]; if (member.IsDefined(typeof(IgnoreDataMemberAttribute), true)) continue; string name = member.Name; if (member.IsDefined(typeof(DataMemberAttribute), true)) { DataMemberAttribute dataMemberAttribute = (DataMemberAttribute)Attribute.GetCustomAttribute(member, typeof(DataMemberAttribute), true); if (!string.IsNullOrEmpty(dataMemberAttribute.Name)) name = dataMemberAttribute.Name; } nameToMember.Add(name, member); } return nameToMember; } static object ParseObject(Type type, string json) { object instance = FormatterServices.GetUninitializedObject(type); //The list is split into key/value pairs only, this means the split must be divisible by 2 to be valid JSON List<string> elems = Split(json); if (elems.Count % 2 != 0) return instance; Dictionary<string, FieldInfo> nameToField; Dictionary<string, PropertyInfo> nameToProperty; if (!fieldInfoCache.TryGetValue(type, out nameToField)) { nameToField = CreateMemberNameDictionary(type.GetFields(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy)); fieldInfoCache.Add(type, nameToField); } if (!propertyInfoCache.TryGetValue(type, out nameToProperty)) { nameToProperty = CreateMemberNameDictionary(type.GetProperties(BindingFlags.Instance | BindingFlags.Public | BindingFlags.FlattenHierarchy)); propertyInfoCache.Add(type, nameToProperty); } for (int i = 0; i < elems.Count; i += 2) { if (elems[i].Length <= 2) continue; string key = elems[i].Substring(1, elems[i].Length - 2); string value = elems[i + 1]; FieldInfo fieldInfo; PropertyInfo propertyInfo; if (nameToField.TryGetValue(key, out fieldInfo)) fieldInfo.SetValue(instance, ParseValue(fieldInfo.FieldType, value)); else if (nameToProperty.TryGetValue(key, out propertyInfo)) propertyInfo.SetValue(instance, ParseValue(propertyInfo.PropertyType, value), null); } return instance; } } }
41.850242
157
0.495556
[ "MIT" ]
lucabol/LMustache
Mustache/NoJsonTextMustacheParser.cs
25,991
C#
////******************************************************************** //https://github.com/mehfuzh/LinqExtender/blob/master/License.txt //Copyright (c) 2007- 2010 LinqExtender Toolkit Project. //Project Modified by Intuit /******************************************************************************* * Copyright 2016 Intuit * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. *******************************************************************************/ // ////******************************************************************** using System; using System.Collections.Generic; using System.Diagnostics; namespace Intuit.Ipp.LinqExtender { /// <summary> /// Represents the query conditions in a tree logical tree form. /// </summary> [DebuggerStepThrough] [Obsolete("Deprecated. Use QueryService->ExecuteIdsQuery")] internal class TreeNode { /// <summary> /// Defines a tree node. /// </summary> public class Node { /// <summary> /// Gets a value for the tree node. /// </summary> public object Value { get; set; } } /// <summary> /// Id of the current node. /// </summary> public Guid Id { get; set; } /// <summary> /// parent Id of the current node. /// </summary> public Guid ParentId { get; set; } /// <summary> /// list of nodes under each expression. /// </summary> internal IList<Node> Nodes { get { if (nodes == null) { nodes = new List<Node>(); } return nodes; } set { nodes = value; } } /// <summary> /// left leaf of the current root, can contain bucketItem or a CurrentNode /// </summary> public Node Left { get { if (Nodes.Count > 0) { return Nodes[0]; } return null; } } /// <summary> /// right leaf of the current root, can contain bucketItem or a CurrentNode /// </summary> /// public Node Right { get { if (Nodes.Count > 1) { return Nodes[1]; } return null; } } internal LogicalOperator RootImpl { get; set; } ///<summary> /// Root which the left and right item follows. ///</summary> public LogicalOperator Root { get { if (Right != null) return RootImpl; // for single item should return NONE. return LogicalOperator.None; } } /// <summary> /// Clones the tree node. /// </summary> /// <returns>clonned <see cref="TreeNode"/></returns> public TreeNode Clone() { var clonned = Activator.CreateInstance<TreeNode>(); foreach (var node in this.GetType().GetProperties()) { if (node.CanWrite) { node.SetValue(clonned, node.GetValue(this, null), null); } } return clonned; } private IList<Node> nodes; } }
29.085714
83
0.451375
[ "Apache-2.0" ]
ANSIOS-X9SAN-iOS-XR/QuickBooks-V3-DotNET-SDK
IPPDotNetDevKitCSV3/ThirdParty/Linq Extender/TreeNode.cs
4,072
C#
using System; using System.Collections.Generic; using System.Linq; using System.Net; using System.Security.Claims; using System.Threading.Tasks; using Autofac.Extras.Moq; using FizzWare.NBuilder; using FluentAssertions; using Microsoft.AspNetCore.Http; using Microsoft.AspNetCore.Mvc; using Moq; using NUnit.Framework; using VideoWeb.Common.Caching; using VideoWeb.Common.Models; using VideoWeb.Contract.Responses; using VideoWeb.Controllers; using VideoWeb.Mappings; using VideoApi.Client; using VideoApi.Contract.Responses; using VideoWeb.UnitTests.Builders; using VideoApi.Contract.Enums; namespace VideoWeb.UnitTests.Controllers.ConferenceController { public class GetConferenceByIdVhoTests { private AutoMock _mocker; private ConferencesController _sut; [SetUp] public void Setup() { _mocker = AutoMock.GetLoose(); var claimsPrincipal = new ClaimsPrincipalBuilder().WithRole(AppRoles.VhOfficerRole).Build(); _sut = SetupControllerWithClaims(claimsPrincipal); } [Test] public async Task Should_return_ok_when_user_is_an_admin() { var conference = CreateValidConferenceResponse(null); conference.Participants[0].UserRole = UserRole.Individual; _mocker.Mock<IVideoApiClient>() .Setup(x => x.GetConferenceDetailsByIdAsync(It.IsAny<Guid>())) .ReturnsAsync(conference); var result = await _sut.GetConferenceByIdVHOAsync(conference.Id); var typedResult = (OkObjectResult)result.Result; typedResult.Should().NotBeNull(); _mocker.Mock<IConferenceCache>().Verify(x => x.AddConferenceAsync(new ConferenceDetailsResponse()), Times.Never); var response = (ConferenceResponseVho)typedResult.Value; response.CaseNumber.Should().Be(conference.CaseNumber); response.Participants[0].Role.Should().Be(UserRole.Individual); } [Test] public async Task Should_return_bad_request() { var apiException = new VideoApiException<ProblemDetails>("Bad Request", (int)HttpStatusCode.BadRequest, "Please provide a valid conference Id", null, default, null); _mocker.Mock<IVideoApiClient>() .Setup(x => x.GetConferenceDetailsByIdAsync(It.IsAny<Guid>())) .ThrowsAsync(apiException); var result = await _sut.GetConferenceByIdVHOAsync(Guid.Empty); var typedResult = (BadRequestObjectResult)result.Result; typedResult.Should().NotBeNull(); } [Test] public async Task Should_return_forbidden_request() { var apiException = new VideoApiException<ProblemDetails>("Unauthorised Token", (int)HttpStatusCode.Unauthorized, "Invalid Client ID", null, default, null); _mocker.Mock<IVideoApiClient>() .Setup(x => x.GetConferenceDetailsByIdAsync(It.IsAny<Guid>())) .ThrowsAsync(apiException); var result = await _sut.GetConferenceByIdVHOAsync(Guid.NewGuid()); var typedResult = (ObjectResult)result.Result; typedResult.StatusCode.Should().Be((int)HttpStatusCode.Unauthorized); } [Test] public async Task Should_return_exception() { var apiException = new VideoApiException<ProblemDetails>("Internal Server Error", (int)HttpStatusCode.InternalServerError, "Stacktrace goes here", null, default, null); _mocker.Mock<IVideoApiClient>() .Setup(x => x.GetConferenceDetailsByIdAsync(It.IsAny<Guid>())) .ThrowsAsync(apiException); var result = await _sut.GetConferenceByIdVHOAsync(Guid.NewGuid()); var typedResult = result.Value; typedResult.Should().BeNull(); } private ConferenceDetailsResponse CreateValidConferenceResponse(string username = "john@hmcts.net") { var judge = new ParticipantDetailsResponseBuilder(UserRole.Judge, "Judge").Build(); var individualDefendant = new ParticipantDetailsResponseBuilder(UserRole.Individual, "Defendant").Build(); var individualClaimant = new ParticipantDetailsResponseBuilder(UserRole.Individual, "Claimant").Build(); var repClaimant = new ParticipantDetailsResponseBuilder(UserRole.Representative, "Claimant").Build(); var panelMember = new ParticipantDetailsResponseBuilder(UserRole.JudicialOfficeHolder, "Panel Member").Build(); var participants = new List<ParticipantDetailsResponse>() { individualDefendant, individualClaimant, repClaimant, judge, panelMember }; if (!string.IsNullOrWhiteSpace(username)) { participants.First().Username = username; } var conference = Builder<ConferenceDetailsResponse>.CreateNew() .With(x => x.Participants = participants) .Build(); return conference; } private ConferencesController SetupControllerWithClaims(ClaimsPrincipal claimsPrincipal) { var context = new ControllerContext { HttpContext = new DefaultHttpContext { User = claimsPrincipal } }; var parameters = new ParameterBuilder(_mocker) .AddTypedParameters<ParticipantResponseMapper>() .AddTypedParameters<EndpointsResponseMapper>() .AddTypedParameters<ParticipantForHostResponseMapper>() .AddTypedParameters<ParticipantResponseForVhoMapper>() .AddTypedParameters<ParticipantForUserResponseMapper>() .Build(); _mocker.Mock<IMapperFactory>().Setup(x => x.Get<VideoApi.Contract.Responses.ConferenceForHostResponse, VideoWeb.Contract.Responses.ConferenceForHostResponse>()).Returns(_mocker.Create<ConferenceForHostResponseMapper>(parameters)); _mocker.Mock<IMapperFactory>().Setup(x => x.Get<VideoApi.Contract.Responses.ConferenceForIndividualResponse, VideoWeb.Contract.Responses.ConferenceForIndividualResponse>()).Returns(_mocker.Create<ConferenceForIndividualResponseMapper>(parameters)); _mocker.Mock<IMapperFactory>().Setup(x => x.Get<ConferenceForAdminResponse, ConferenceForVhOfficerResponse>()).Returns(_mocker.Create<ConferenceForVhOfficerResponseMapper>(parameters)); _mocker.Mock<IMapperFactory>().Setup(x => x.Get<ConferenceDetailsResponse, ConferenceResponseVho>()).Returns(_mocker.Create<ConferenceResponseVhoMapper>(parameters)); _mocker.Mock<IMapperFactory>().Setup(x => x.Get<ConferenceDetailsResponse, ConferenceResponse>()).Returns(_mocker.Create<ConferenceResponseMapper>(parameters)); var controller = _mocker.Create<ConferencesController>(); controller.ControllerContext = context; return controller; } } }
45.468354
260
0.664811
[ "MIT" ]
hmcts/vh-video-web
VideoWeb/VideoWeb.UnitTests/Controllers/ConferenceController/GetConferenceByIdVHOTests.cs
7,184
C#
namespace CSharpCoin.windows.main { partial class AppReceiveWindow { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { this.SuspendLayout(); // // AppReceiveWindow // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.ClientSize = new System.Drawing.Size(800, 450); this.Name = "AppReceiveWindow"; this.ShowIcon = false; this.Text = "Receive"; this.ResumeLayout(false); } #endregion } }
30.702128
107
0.548857
[ "MIT" ]
viduedo/CSharpCoin
CSharpCoin/windows/main/AppReceiveWindow.Designer.cs
1,445
C#
using Esri.ArcGISRuntime.Data; using Esri.ArcGISRuntime.Geometry; using Esri.ArcGISRuntime.Mapping; using Esri.ArcGISRuntime.Symbology; using Esri.ArcGISRuntime.UI; using Esri.ArcGISRuntime.UI.Controls; 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 ArcGISApp1.Controls.OtherTool { /// <summary> /// UnionCsy.xaml 的交互逻辑 /// </summary> public partial class UnionCsy : UserControl { Window w; MapView myMapView; public static FeatureLayer layer; Graphic graphic; Esri.ArcGISRuntime.Geometry.Geometry resultGeometry; // 三种Symbol public static SimpleLineSymbol simpleLineSymbol; public static SimpleFillSymbol simpleFillSymbol = new SimpleFillSymbol() { Outline = new SimpleLineSymbol() { Style = SimpleLineSymbolStyle.Solid, Width = 4, Color = System.Drawing.Color.Red }, Style = SimpleFillSymbolStyle.Solid, Color = System.Drawing.Color.Red }; public static SimpleMarkerSymbol simplePointSymbol = new SimpleMarkerSymbol() { Color = System.Drawing.Color.Green, Size = 6, Style = SimpleMarkerSymbolStyle.Circle }; // 判断要素类型 int featureStyle = 0; public UnionCsy() { InitializeComponent(); } private async void unionBtn_Click(object sender, RoutedEventArgs e) { FeatureQueryResult r = await layer.GetSelectedFeaturesAsync(); IEnumerator<Feature> resultFeatures = r.GetEnumerator(); List<Feature> features = new List<Feature>(); while (resultFeatures.MoveNext()) { features.Add(resultFeatures.Current); } for (int i = 0; i < features.Count - 1;i++) { resultGeometry = GeometryEngine.Union(features[i].Geometry, features[i+1].Geometry.Extent); } try { if (featureStyle == 1) { graphic = new Graphic(resultGeometry, simplePointSymbol); } else if (featureStyle == 2) { graphic = new Graphic(resultGeometry, simpleLineSymbol); } else if (featureStyle == 3) { graphic = new Graphic(resultGeometry, simpleFillSymbol); } MainWindow.graphicsOverlay.Graphics.Add(graphic); } catch { } } private void myUserControl_Loaded(object sender, RoutedEventArgs e) { w = Window.GetWindow(this); myMapView = (MapView)w.FindName("myMapView"); } private void symbolBtn_Click(object sender, RoutedEventArgs e) { // 先关闭所有的工具条 Canvas userControlsLayoutCsy = (Canvas)w.FindName("userControlsLayoutCsy"); List<StackPanel> tools = ArcGISApp1.Utils.GetChildNode.GetChildObjects<StackPanel>(userControlsLayoutCsy); for (int i = 0; i < tools.Count(); i++) { tools[i].Visibility = Visibility.Collapsed; } // 符号渲染窗口 if (layer.FeatureTable.GeometryType == Esri.ArcGISRuntime.Geometry.GeometryType.Point) { featureStyle = 1; var window = new Window(); Controls.SymbolFormCSY.PointCsy pointForm = new Controls.SymbolFormCSY.PointCsy(); window.Content = pointForm; window.SizeToContent = SizeToContent.WidthAndHeight; window.WindowStartupLocation = WindowStartupLocation.CenterScreen; window.Title = "点符号渲染工具"; window.Closed += windowClosed_Point; window.Show(); } else if (layer.FeatureTable.GeometryType == Esri.ArcGISRuntime.Geometry.GeometryType.Polyline) { featureStyle = 2; var window = new Window(); Controls.SymbolFormCSY.LineCsy lineForm = new Controls.SymbolFormCSY.LineCsy(); window.Content = lineForm; window.SizeToContent = SizeToContent.WidthAndHeight; window.WindowStartupLocation = WindowStartupLocation.CenterScreen; window.Title = "线符号渲染工具"; window.Closed += windowClosed_Line; window.Show(); } else if (layer.FeatureTable.GeometryType == Esri.ArcGISRuntime.Geometry.GeometryType.Polygon) { featureStyle = 3; var window = new Window(); Controls.SymbolFormCSY.FillCsy fillForm = new Controls.SymbolFormCSY.FillCsy(); window.Content = fillForm; window.SizeToContent = SizeToContent.WidthAndHeight; window.WindowStartupLocation = WindowStartupLocation.CenterScreen; window.Title = "面符号渲染工具"; window.Closed += windowClosed_Polygon; window.Show(); } } private void windowClosed_Point(object sender, EventArgs e) { featureStyle = 1; simplePointSymbol = SymbolFormCSY.PointCsy.simplePointSymbol; } private void windowClosed_Line(object sender, EventArgs e) { featureStyle = 2; simpleLineSymbol = SymbolFormCSY.LineCsy.simpleLineSymbol; } private void windowClosed_Polygon(object sender, EventArgs e) { featureStyle = 3; simpleFillSymbol = SymbolFormCSY.FillCsy.simpleFillSymbol; } } }
35.80814
118
0.581101
[ "MIT" ]
soitwaterdemos/Arcgis-Runtime-Secondary-Developmen
MIX0300/ArcGISApp1/Controls/OtherTool/UnionCsy.xaml.cs
6,259
C#
using System.Text.Json.Serialization; namespace Horizon.Payment.Alipay.Response { /// <summary> /// AlipayMarketingCardUpdateResponse. /// </summary> public class AlipayMarketingCardUpdateResponse : AlipayResponse { /// <summary> /// 二级错误处理结果(如果公用返回结果为false,则可以看这个接口判断明细原因) 如果公用返回为true,则该字段为空 /// </summary> [JsonPropertyName("result_code")] public string ResultCode { get; set; } } }
26.588235
71
0.654867
[ "Apache-2.0" ]
bluexray/Horizon.Sample
Horizon.Payment.Alipay/Response/AlipayMarketingCardUpdateResponse.cs
550
C#
using OpenKh.Engine; using OpenKh.Game.Field; using OpenKh.Game.Infrastructure; using System.Collections.Generic; using System.Numerics; using System.Text; using static OpenKh.Kh2.Ard.Event; namespace OpenKh.Game.Events { public class EventPlayer { private const int FramesPerSecond = 30; private const float TimeMul = 1.0f / FramesPerSecond; private readonly IField _field; private readonly IList<IEventEntry> _eventEntries; private readonly IList<SetCameraData> _cameras = new List<SetCameraData>(); private readonly Dictionary<int, string> _actors = new Dictionary<int, string>(); private double _secondsPrev; private double _seconds; private int _cameraId; private int _eventDuration; public bool IsEnd { get; private set; } public EventPlayer(IField field, IList<IEventEntry> eventEntries) { _field = field; _eventEntries = eventEntries; } public void Initialize() { IsEnd = false; foreach (var entry in _eventEntries) { switch (entry) { case SetEndFrame item: _eventDuration = item.EndFrame; break; case ReadAssets assets: foreach (var assetEntry in assets.Set) { switch (assetEntry) { case ReadActor item: _actors[item.ActorId] = item.Name; _field.AddActor(item.ActorId, item.ObjectId); _field.SetActorVisibility(item.ActorId, false); break; } } // Double for-loop to ensure to load actors first, then // animations to prevent crashes. foreach (var assetEntry in assets.Set) { switch (assetEntry) { case ReadMotion item: _field.SetActorAnimation( item.ActorId, GetAnmPath(item.ActorId, item.Name)); _field.SetActorVisibility(item.ActorId, item.UnknownIndex == 0); break; } } break; case EventStart item: _field.FadeFromBlack(item.FadeIn * TimeMul); break; case SetCameraData item: _cameras.Add(item); break; } } _cameraId = 0; } public void Update(double deltaTime) { _seconds += deltaTime; var nFrame = (int)(_seconds * FramesPerSecond); var nPrevFrame = (int)(_secondsPrev * FramesPerSecond); var cameraFrameTime = _seconds; if (nFrame >= _eventDuration) { IsEnd = true; return; } foreach (var entry in _eventEntries) { switch (entry) { case SeqActorPosition item: if (item.Frame > nPrevFrame && item.Frame <= nFrame) { _field.SetActorPosition( item.ActorId, item.PositionX, item.PositionY, -item.PositionZ, item.RotationY); } break; case SeqPlayAnimation item: if (item.FrameStart > nPrevFrame && item.FrameStart <= nFrame) { _field.SetActorAnimation( item.ActorId, GetAnmPath(item.ActorId, item.Path)); _field.SetActorVisibility(item.ActorId, true); } break; case SeqActorLeave item: if (item.Frame > nPrevFrame && item.Frame <= nFrame) _field.SetActorVisibility(item.ActorId, false); break; case SeqCamera item: if (nFrame >= item.FrameStart && nFrame < item.FrameEnd) { _cameraId = item.CameraId; var frameLength = item.FrameEnd - item.FrameStart; cameraFrameTime = (_seconds * FramesPerSecond - item.FrameStart) / 30f; } break; case SeqFade item: if (item.FrameIndex > nPrevFrame && item.FrameIndex <= nFrame) { switch (item.Type) { case SeqFade.FadeType.FromBlack: case SeqFade.FadeType.FromBlackVariant: _field.FadeFromBlack(item.Duration * TimeMul); break; case SeqFade.FadeType.FromWhite: case SeqFade.FadeType.FromWhiteVariant: _field.FadeFromWhite(item.Duration * TimeMul); break; case SeqFade.FadeType.ToBlack: case SeqFade.FadeType.ToBlackVariant: _field.FadeToBlack(item.Duration * TimeMul); break; case SeqFade.FadeType.ToWhite: case SeqFade.FadeType.ToWhiteVariant: _field.FadeToWhite(item.Duration * TimeMul); break; } } break; case SeqSubtitle item: if (nFrame >= item.FrameStart && nPrevFrame < item.FrameStart) { if (item.HideFlag == 0) _field.ShowSubtitle(item.Index, (ushort)item.MessageId); else if (item.HideFlag != 0) _field.HideSubtitle(item.Index); } break; } } if (_cameraId < _cameras.Count) { var curCamera = _cameras[_cameraId]; _field.SetCamera( new Vector3( (float)GetCameraValue(cameraFrameTime, curCamera.PositionX, null), (float)GetCameraValue(cameraFrameTime, curCamera.PositionY, null), (float)GetCameraValue(cameraFrameTime, curCamera.PositionZ, null)), new Vector3( (float)GetCameraValue(cameraFrameTime, curCamera.LookAtX, null), (float)GetCameraValue(cameraFrameTime, curCamera.LookAtY, null), (float)GetCameraValue(cameraFrameTime, curCamera.LookAtZ, null)), (float)GetCameraValue(cameraFrameTime, curCamera.FieldOfView, null), (float)GetCameraValue(cameraFrameTime, curCamera.Roll, null)); } _secondsPrev = _seconds; } private string GetAnmPath(int actorId, string name) { var sb = new StringBuilder(); var split = name.Split("anm_")[1].Split("/"); sb.Append(split[0]); sb.Append("/"); sb.Append(_actors[actorId]); sb.Append("/"); sb.Append(split[1]); return sb.ToString(); } private static double GetCameraValue( double time, IList<SetCameraData.CameraKeys> keyFrames, SetCameraData.CameraKeys prevKey) { if (keyFrames.Count == 0) return 0.0; if (keyFrames.Count == 1) return keyFrames[0].Value; const int First = 0; var Last = keyFrames.Count - 1; var m = time + 1.0 / 60.0; var currentFrameIndex = (int)(m * 512.0); if (currentFrameIndex > keyFrames[First].KeyFrame - 0x10000000) { if (currentFrameIndex < keyFrames[Last].KeyFrame) { // Do a binary search through all the key frames var left = First; var right = Last; if (right <= 1) return InterpolateCamera(right - 1, m, keyFrames, prevKey); while (true) { var mid = (left + right) / 2; if (currentFrameIndex >= keyFrames[mid].KeyFrame) { if (currentFrameIndex <= keyFrames[mid].KeyFrame) return keyFrames[mid].Value; left = mid; } else right = mid; if (right - left <= 1) return InterpolateCamera(right - 1, m, keyFrames, prevKey); } } double tangent; var keyFrameDistance = keyFrames[Last].KeyFrame - keyFrames[Last - 1].KeyFrame; if (keyFrames[Last].Interpolation != Kh2.Motion.Interpolation.Linear || keyFrameDistance == 0) tangent = keyFrames[Last].TangentEaseOut; else tangent = (keyFrames[Last].Value - keyFrames[Last - 1].Value) / keyFrameDistance; return ((currentFrameIndex - (keyFrames[Last].KeyFrame + 0x10000000) + 0x10000000) * tangent) + keyFrames[Last].Value; } else { double tangent; var keyFrameDistance = keyFrames[First + 1].KeyFrame - keyFrames[First].KeyFrame; if (keyFrames[First].Interpolation != Kh2.Motion.Interpolation.Linear || keyFrameDistance == 0) tangent = keyFrames[First].TangentEaseIn; else tangent = (keyFrames[First + 1].Value - keyFrames[First].Value) / keyFrameDistance; return -(((keyFrames[First].KeyFrame - currentFrameIndex - 0x10000000) * tangent) - keyFrames[First].Value); } } private static double InterpolateCamera( int keyFrameIndex, double time, IList<SetCameraData.CameraKeys> keyFrames, SetCameraData.CameraKeys prevKey) { const double N = 1.0 / 512.0; var curKeyFrame = keyFrames[keyFrameIndex]; var nextKeyFrame = keyFrames[keyFrameIndex + 1]; if (prevKey != null) prevKey.TangentEaseOut = curKeyFrame.TangentEaseOut; var t = time - curKeyFrame.KeyFrame * N; var tx = (nextKeyFrame.KeyFrame - curKeyFrame.KeyFrame) * N; switch (curKeyFrame.Interpolation) { case Kh2.Motion.Interpolation.Nearest: return curKeyFrame.Value; case Kh2.Motion.Interpolation.Linear: return curKeyFrame.Value + ((nextKeyFrame.Value - curKeyFrame.Value) * t / tx); case Kh2.Motion.Interpolation.Hermite: case (Kh2.Motion.Interpolation)3: case (Kh2.Motion.Interpolation)4: var itx = 1.0 / tx; // Perform a cubic hermite interpolation var p0 = curKeyFrame.Value; var p1 = nextKeyFrame.Value; var m0 = curKeyFrame.TangentEaseOut; var m1 = nextKeyFrame.TangentEaseIn; var t2 = t * t * itx; var t3 = t * t * t * itx * itx; return p0 * (2 * t3 * itx - 3 * t2 * itx + 1) + m0 * (t3 - 2 * t2 + t) + p1 * (-2 * t3 * itx + 3 * t2 * itx) + m1 * (t3 - t2); default: return 0; } } } }
42.532895
134
0.446017
[ "Apache-2.0" ]
1234567890num/OpenKh
OpenKh.Game/Events/EventPlayer.cs
12,930
C#
using Nager.Country.Currencies; namespace Nager.Country.CountryInfos { /// <summary> /// Kenya /// </summary> public class KenyaCountryInfo : ICountryInfo { ///<inheritdoc/> public string CommonName => "Kenya"; ///<inheritdoc/> public string OfficialName => "Republic of Kenya"; ///<inheritdoc/> public string NativeName => "Kenya"; ///<inheritdoc/> public Alpha2Code Alpha2Code => Alpha2Code.KE; ///<inheritdoc/> public Alpha3Code Alpha3Code => Alpha3Code.KEN; ///<inheritdoc/> public int NumericCode => 404; ///<inheritdoc/> public string[] TLD => new [] { ".ke" }; ///<inheritdoc/> public Region Region => Region.Africa; ///<inheritdoc/> public SubRegion SubRegion => SubRegion.EasternAfrica; ///<inheritdoc/> public Alpha2Code[] BorderCountries => new Alpha2Code[] { Alpha2Code.ET, Alpha2Code.SO, Alpha2Code.SS, Alpha2Code.TZ, Alpha2Code.UG, }; ///<inheritdoc/> public ICurrency[] Currencies => new [] { new KesCurrency() }; ///<inheritdoc/> public string[] CallingCodes => new [] { "254" }; } }
28.173913
70
0.542438
[ "MIT" ]
OpenBoxLab/Nager.Country
src/Nager.Country/CountryInfos/KenyaCountryInfo.cs
1,296
C#
// Copyright (c) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE file in the project root for full license information. using Microsoft.Protocols.TestSuites.FileSharing.Common.Adapter; using Microsoft.Protocols.TestTools; using Microsoft.Protocols.TestTools.StackSdk.Networking.Rpce; using Microsoft.Protocols.TestTools.StackSdk.Security.SspiLib; using Microsoft.Protocols.TestTools.StackSdk.Security.SspiService; using Microsoft.Protocols.TestTools.StackSdk.Swn; using System; using System.Linq; using System.Net; namespace Microsoft.Protocols.TestSuites.FileSharing.ServerFailover.TestSuite { public class SWNTestUtility { private static ITestSite baseTestSite; public static string swnWitnessName = "SmbWitness"; /// <summary> /// The base test site /// </summary> public static ITestSite BaseTestSite { set { baseTestSite = value; } get { return baseTestSite; } } #region Print methods /// <summary> /// Print WITNESS_INTERFACE_LIST. /// </summary> /// <param name="interfaceList">Interface list.</param> [CLSCompliant(false)] public static void PrintInterfaceList(WITNESS_INTERFACE_LIST interfaceList) { BaseTestSite.Log.Add(LogEntryKind.Debug, "WITNESS_INTERFACE_LIST length: {0}", interfaceList.NumberOfInterfaces); for (int i = 0; i < interfaceList.NumberOfInterfaces; i++) { BaseTestSite.Log.Add(LogEntryKind.Debug, "\tInterface {0}:", i); BaseTestSite.Log.Add(LogEntryKind.Debug, "\t\tInterfaceGroupName: {0}", interfaceList.InterfaceInfo[i].InterfaceGroupName); BaseTestSite.Log.Add(LogEntryKind.Debug, "\t\tVersion: {0:X08}", interfaceList.InterfaceInfo[i].Version); BaseTestSite.Log.Add(LogEntryKind.Debug, "\t\tNodeState: {0}", interfaceList.InterfaceInfo[i].NodeState); BaseTestSite.Log.Add(LogEntryKind.Debug, "\t\tIPV4: {0}", (new IPAddress(interfaceList.InterfaceInfo[i].IPV4)).ToString()); BaseTestSite.Log.Add(LogEntryKind.Debug, "\t\tIPV6: {0}", ConvertIPV6(interfaceList.InterfaceInfo[i].IPV6).ToString()); BaseTestSite.Log.Add(LogEntryKind.Debug, "\t\tFlags: {0:x8}", interfaceList.InterfaceInfo[i].Flags); } } /// <summary> /// Print RESP_ASYNC_NOTIFY /// </summary> /// <param name="respNotify">Asynchronous notification</param> public static void PrintNotification(RESP_ASYNC_NOTIFY respNotify) { BaseTestSite.Log.Add(LogEntryKind.Debug, "Receive asynchronous notification"); switch ((SwnMessageType)respNotify.MessageType) { case SwnMessageType.RESOURCE_CHANGE_NOTIFICATION: { RESOURCE_CHANGE[] resourceChangeList; SwnUtility.ParseResourceChange(respNotify, out resourceChangeList); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tRESOURCE_CHANGE"); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tcount: {0}", resourceChangeList.Length); foreach (var res in resourceChangeList) { BaseTestSite.Log.Add(LogEntryKind.Debug, "\t\tResource name: {0}", res.ResourceName.Substring(0, res.ResourceName.Length - 1)); switch ((SwnResourceChangeType)res.ChangeType) { case SwnResourceChangeType.RESOURCE_STATE_UNKNOWN: BaseTestSite.Log.Add(LogEntryKind.Debug, "\t\tChange type: RESOURCE_STATE_UNKNOWN"); break; case SwnResourceChangeType.RESOURCE_STATE_AVAILABLE: BaseTestSite.Log.Add(LogEntryKind.Debug, "\t\tChange type: RESOURCE_STATE_AVAILABLE"); break; case SwnResourceChangeType.RESOURCE_STATE_UNAVAILABLE: BaseTestSite.Log.Add(LogEntryKind.Debug, "\t\tChange type: RESOURCE_STATE_UNAVAILABLE"); break; default: BaseTestSite.Log.Add(LogEntryKind.Debug, "\t\tChange type: Unknown type {0}", res.ChangeType); break; } } } break; case SwnMessageType.CLIENT_MOVE_NOTIFICATION: { IPADDR_INFO_LIST IPAddrInfoList; SwnUtility.ParseIPAddrInfoList(respNotify, out IPAddrInfoList); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tCLIENT_MOVE"); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tReserved: {0}", IPAddrInfoList.Reserved); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tIP address count: {0}", IPAddrInfoList.IPAddrInstances); foreach (var ip in IPAddrInfoList.IPAddrList) { BaseTestSite.Log.Add(LogEntryKind.Debug, "\tFlags: {0}", ip.Flags); if (((uint)SwnIPAddrInfoFlags.IPADDR_V4 & ip.Flags) != 0) { BaseTestSite.Log.Add(LogEntryKind.Debug, "\tIPAddr V4: {0}", (new IPAddress(ip.IPV4)).ToString()); } if (((uint)SwnIPAddrInfoFlags.IPADDR_V6 & ip.Flags) != 0) { BaseTestSite.Log.Add(LogEntryKind.Debug, "\tIPAddr V6: {0}", ConvertIPV6(ip.IPV6).ToString()); } } } break; case SwnMessageType.SHARE_MOVE_NOTIFICATION: { IPADDR_INFO_LIST IPAddrInfoList; SwnUtility.ParseIPAddrInfoList(respNotify, out IPAddrInfoList); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tSHARE_MOVE"); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tReserved: {0}", IPAddrInfoList.Reserved); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tIP address count: {0}", IPAddrInfoList.IPAddrInstances); foreach (var ip in IPAddrInfoList.IPAddrList) { BaseTestSite.Log.Add(LogEntryKind.Debug, "\tFlags: {0}", ip.Flags); if (((uint)SwnIPAddrInfoFlags.IPADDR_V4 & ip.Flags) != 0) { BaseTestSite.Log.Add(LogEntryKind.Debug, "\tIPAddr V4: {0}", (new IPAddress(ip.IPV4)).ToString()); } if (((uint)SwnIPAddrInfoFlags.IPADDR_V6 & ip.Flags) != 0) { BaseTestSite.Log.Add(LogEntryKind.Debug, "\tIPAddr V6: {0}", ConvertIPV6(ip.IPV6).ToString()); } } } break; case SwnMessageType.IP_CHANGE_NOTIFICATION: { IPADDR_INFO_LIST IPAddrInfoList; SwnUtility.ParseIPAddrInfoList(respNotify, out IPAddrInfoList); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tIP_CHANGE"); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tReserved: {0}", IPAddrInfoList.Reserved); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tIP address count: {0}", IPAddrInfoList.IPAddrInstances); foreach (var ip in IPAddrInfoList.IPAddrList) { BaseTestSite.Log.Add(LogEntryKind.Debug, "\tFlags: {0}", ip.Flags); if (((uint)SwnIPAddrInfoFlags.IPADDR_V4 & ip.Flags) != 0) { BaseTestSite.Log.Add(LogEntryKind.Debug, "\tIPAddr V4: {0}", (new IPAddress(ip.IPV4)).ToString()); } if (((uint)SwnIPAddrInfoFlags.IPADDR_V6 & ip.Flags) != 0) { BaseTestSite.Log.Add(LogEntryKind.Debug, "\tIPAddr V6: {0}", ConvertIPV6(ip.IPV6).ToString()); } } } break; default: BaseTestSite.Assert.Fail("\t\tMessage type: Unknown type {0}", respNotify.MessageType); break; } } #endregion /// <summary> /// Get principle name without domain name. /// </summary> /// <param name="domainName">Domain name</param> /// <param name="serverName">Server name</param> /// <returns>Return principle name</returns> public static string GetPrincipleName(string domainName, string serverName) { if (serverName.Contains(domainName)) { return serverName.Substring(0, serverName.Length - domainName.Length - 1); } return serverName; } /// <summary> /// Bind RPC server. /// </summary> /// <param name="swnClient">SWN rpc client</param> /// <param name="networkAddress">RPC network address</param> /// <param name="domainName">Domain name</param> /// <param name="userName">User name</param> /// <param name="password">Password</param> /// <param name="securityPackage">Security package</param> /// <param name="authLevel">Authentication level</param> /// <param name="timeout">Timeout</param> /// <param name="serverComputerName">ServerComputerName</param> /// <returns>Return true if success, otherwise return false</returns> public static bool BindServer(SwnClient swnClient, IPAddress networkAddress, string domainName, string userName, string password, SecurityPackageType securityPackage, RpceAuthenticationLevel authLevel, TimeSpan timeout, string serverComputerName = null) { AccountCredential accountCredential = new AccountCredential(domainName, userName, password); string cifsServicePrincipalName = string.Empty; if (!string.IsNullOrEmpty(serverComputerName)) { cifsServicePrincipalName = "cifs/" + serverComputerName; } else { IPHostEntry hostEntry = null; try { hostEntry = Dns.GetHostEntry(networkAddress); } catch (Exception ex) { throw new Exception(string.Format("Failed to resolve network address {0} with exception: {1}", networkAddress.ToString(), ex.Message)); } if (hostEntry != null && !string.IsNullOrEmpty(hostEntry.HostName)) { cifsServicePrincipalName = "cifs/" + hostEntry.HostName; } else { throw new Exception("Failed to get HostName from network address " + networkAddress.ToString()); } } ClientSecurityContext securityContext = new SspiClientSecurityContext( securityPackage, accountCredential, cifsServicePrincipalName, ClientSecurityContextAttribute.Connection | ClientSecurityContextAttribute.DceStyle | ClientSecurityContextAttribute.Integrity | ClientSecurityContextAttribute.ReplayDetect | ClientSecurityContextAttribute.SequenceDetect | ClientSecurityContextAttribute.UseSessionKey, SecurityTargetDataRepresentation.SecurityNativeDrep); try { //Bind BaseTestSite.Log.Add(LogEntryKind.Debug, "Start to Bind RPC to {0}.", networkAddress.ToString()); swnClient.SwnBind(networkAddress.ToString(), accountCredential, securityContext, authLevel, timeout); } catch (Exception ex) { BaseTestSite.Log.Add(LogEntryKind.Debug, "Bind server {0} failed. Exception: {1}", networkAddress.ToString(), ex.Message); swnClient.SwnUnbind(timeout); return false; } BaseTestSite.Log.Add(LogEntryKind.Debug, "Bind server {0} successfully.", networkAddress.ToString()); return true; } /// <summary> /// Get the witness server to be used to register. /// </summary> /// <param name="interfaceList">The interface list from server.</param> /// <param name="registerInterface">Interface to register.</param> public static void GetRegisterInterface(WITNESS_INTERFACE_LIST interfaceList, out WITNESS_INTERFACE_INFO registerInterface) { registerInterface = new WITNESS_INTERFACE_INFO(); foreach (var info in interfaceList.InterfaceInfo) { if (info.NodeState == SwnNodeState.AVAILABLE && (info.Flags & (uint)SwnNodeFlagsValue.INTERFACE_WITNESS) != 0) { registerInterface = info; BaseTestSite.Log.Add(LogEntryKind.Debug, "Register to interface:"); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tInterface group name: {0}", registerInterface.InterfaceGroupName); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tInterface IPV4 address: {0}", new IPAddress(registerInterface.IPV4).ToString()); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tInterface IPV6 address: {0}", SWNTestUtility.ConvertIPV6(registerInterface.IPV6).ToString()); return; } } BaseTestSite.Assert.Fail("Cannot get register interface."); } /// <summary> /// Get the witness server to be used to access. /// </summary> /// <param name="interfaceList">The interface list from server.</param> /// <param name="accessInterface">Interface to access.</param> public static void GetAccessInterface(WITNESS_INTERFACE_LIST interfaceList, out WITNESS_INTERFACE_INFO accessInterface) { accessInterface = new WITNESS_INTERFACE_INFO(); foreach (var info in interfaceList.InterfaceInfo) { if (info.NodeState == SwnNodeState.AVAILABLE && (info.Flags & (uint)SwnNodeFlagsValue.INTERFACE_WITNESS) == 0) { accessInterface = info; BaseTestSite.Log.Add(LogEntryKind.Debug, "Access interface:"); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tInterface group name: {0}", accessInterface.InterfaceGroupName); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tInterface IPV4 address: {0}", new IPAddress(accessInterface.IPV4).ToString()); BaseTestSite.Log.Add(LogEntryKind.Debug, "\tInterface IPV6 address: {0}", SWNTestUtility.ConvertIPV6(accessInterface.IPV6).ToString()); return; } } BaseTestSite.Assert.Fail("Cannot get register interface."); } /// <summary> /// Verify the interface list. /// </summary> /// <param name="interfaceList">The interface list from server.</param> /// <param name="platform">SUT platform.</param> /// <param name="failCaseIfProtocolVersionIsInvalid">Indicates if failing the case if the verification of protocol version fails</param> public static bool VerifyInterfaceList(WITNESS_INTERFACE_LIST interfaceList, Platform platform, bool failCaseIfProtocolVersionIsInvalid = false) { bool ret = false; PrintInterfaceList(interfaceList); BaseTestSite.Assert.AreNotEqual<uint>(0, interfaceList.NumberOfInterfaces, "WitnessrGetInterfaceList MUST return at least one available interface."); foreach (var info in interfaceList.InterfaceInfo) { if (info.InterfaceGroupName == "") { BaseTestSite.Assert.Fail("The InterfaceGroupName is empty."); } if (info.NodeState == SwnNodeState.AVAILABLE && (info.Flags & (uint)SwnNodeFlagsValue.INTERFACE_WITNESS) != 0) { ret = true; } #region Check Version switch ((SwnVersion)info.Version) { case SwnVersion.SWN_VERSION_1: BaseTestSite.Log.Add(LogEntryKind.Debug, "The Version of SWN service on {0} is 0x{1:X08}", info.InterfaceGroupName, (uint)SwnVersion.SWN_VERSION_1); break; case SwnVersion.SWN_VERSION_2: BaseTestSite.Log.Add(LogEntryKind.Debug, "The Version of SWN service on {0} is 0x{1:X08}", info.InterfaceGroupName, (uint)SwnVersion.SWN_VERSION_2); break; case SwnVersion.SWN_VERSION_UNKNOWN: if (platform >= Platform.WindowsServer2012R2) { // Windows Server 2012 R2, Windows Server 2016, Windows Server operating system, and Windows Server 2019 initialize the value of Version to 0xFFFFFFFF. BaseTestSite.Log.Add(LogEntryKind.Debug, "The Version of SWN service on {0} is 0x{1:X08}", info.InterfaceGroupName, (uint)SwnVersion.SWN_VERSION_UNKNOWN); } else { BaseTestSite.Assert.Fail( "The Version of SWN service on {0} is unknown 0x{1:X08}", info.InterfaceGroupName, info.Version); } break; default: BaseTestSite.Assert.Fail( "The Version of SWN service on {0} is unknown 0x{1:X08}", info.InterfaceGroupName, info.Version); break; } #endregion if ((info.Flags & (uint)SwnNodeFlagsValue.IPv4) != 0 && info.IPV4 == 0) { BaseTestSite.Assert.Fail("The IPV4 {0} of {1} is invalid.", new IPAddress(info.IPV4).ToString(), info.InterfaceGroupName); } else if ((info.Flags & (uint)SwnNodeFlagsValue.IPv6) != 0 && info.IPV6.All(ip => ip == 0)) { BaseTestSite.Assert.Fail("The IPV6 {0} of {1} is invalid.", ConvertIPV6(info.IPV6).ToString(), info.InterfaceGroupName); } } return ret; } /// <summary> /// Verify RESOURCE_CHANGE_NOTIFICATION in Asynchronous Notification /// </summary> /// <param name="respNotify">Asynchronous notification</param> /// <param name="changeType">State change of the resource</param> public static void VerifyResourceChange(RESP_ASYNC_NOTIFY respNotify, SwnResourceChangeType changeType) { BaseTestSite.Assert.AreEqual<uint>((uint)SwnMessageType.RESOURCE_CHANGE_NOTIFICATION, respNotify.MessageType, "Expect MessageType is set to RESOURCE_CHANGE_NOTIFICATION"); RESOURCE_CHANGE[] resourceChangeList; SwnUtility.ParseResourceChange(respNotify, out resourceChangeList); BaseTestSite.Assert.AreEqual<uint>(0x00000001, respNotify.NumberOfMessages, "Expect NumberOfMessages is set to 1."); BaseTestSite.Assert.AreEqual<uint>((uint)changeType, resourceChangeList[0].ChangeType, "Expect ChangeType is set to {0}.", changeType); } /// <summary> /// Verify CLIENT_MOVE_NOTIFICATION/SHARE_MOVE_NOTIFICATION/IP_CHANGE_NOTIFICATION in Asynchronous Notification /// </summary> /// <param name="respNotify">Asynchronous notification</param> /// <param name="expectedMessageType">Expected message type</param> /// <param name="expectedIPAddrInforFlag">Expected flag</param> /// <param name="platform">Platform of SUT</param> public static void VerifyClientMoveShareMoveAndIpChange(RESP_ASYNC_NOTIFY respNotify, SwnMessageType expectedMessageType, uint expectedIPAddrInforFlag, Platform platform) { BaseTestSite.Assert.AreEqual<uint>((uint)expectedMessageType, respNotify.MessageType, "Expect MessageType is set to " + expectedMessageType.ToString()); BaseTestSite.Assert.AreEqual<uint>(1, respNotify.NumberOfMessages, "NumberOfMessages MUST be set to 1."); IPADDR_INFO_LIST IPAddrInfoList; SwnUtility.ParseIPAddrInfoList(respNotify, out IPAddrInfoList); BaseTestSite.Assert.AreEqual<uint>(respNotify.Length, IPAddrInfoList.Length, "Expect Length is the size of the IPADDR_INFO_LIST structure."); BaseTestSite.Assert.AreEqual<uint>(0, IPAddrInfoList.Reserved, "Expect Reserved is 0."); BaseTestSite.Assert.IsTrue(IPAddrInfoList.IPAddrInstances >= 1, "Expect that there is at least one available IPAddress in the IPADDR_INFO structures."); BaseTestSite.Assert.AreEqual<uint>(IPAddrInfoList.IPAddrInstances, (uint)IPAddrInfoList.IPAddrList.Length, "Expect that the length of IPAddrList equals IPAddrInstances ."); for (int i = 0; i < IPAddrInfoList.IPAddrInstances; i++) { /// 2.2.2.1 IPADDR_INFO /// Flags (4 bytes): The Flags field SHOULD<1> be set to a combination of one or more of the following values. /// <1> Section 2.2.2.1: Windows Server 2012 and Windows Server 2012 R2 set the undefined Flags field bits to arbitrary values. if (platform == Platform.NonWindows) { BaseTestSite.Assert.AreEqual<uint>(expectedIPAddrInforFlag, IPAddrInfoList.IPAddrList[i].Flags, "Expect the Flags in IPADDR_INFO structures in the IPAddrList equals " + expectedIPAddrInforFlag.ToString()); } if ((IPAddrInfoList.IPAddrList[i].Flags & (uint)SwnNodeFlagsValue.IPv4) != 0 && IPAddrInfoList.IPAddrList[i].IPV4 == 0) { BaseTestSite.Assert.Fail("The IPV4 {0} in IPAddrInfoList.IPAddrList is invalid.", new IPAddress(IPAddrInfoList.IPAddrList[i].IPV4).ToString()); } else if ((IPAddrInfoList.IPAddrList[i].Flags & (uint)SwnNodeFlagsValue.IPv6) != 0 && IPAddrInfoList.IPAddrList[i].IPV6.All(ip => ip == 0)) { BaseTestSite.Assert.Fail("The IPV6 {0} in IPAddrInfoList.IPAddrList is invalid.", ConvertIPV6(IPAddrInfoList.IPAddrList[i].IPV6).ToString()); } } } /// <summary> /// Get the ip address of current accessed node. /// </summary> /// <param name="server"></param> /// <returns></returns> public static IPAddress GetCurrentAccessIP(string server) { IPAddress[] accessIpList = Dns.GetHostAddresses(server); IPAddress currentAccessIp = accessIpList[0]; BaseTestSite.Assume.AreNotEqual(null, currentAccessIp, "Access IP to the file server should NOT be empty."); BaseTestSite.Log.Add(LogEntryKind.Debug, "Got IP {0} to access the file server", currentAccessIp.ToString()); return currentAccessIp; } /// <summary> /// Get the list of InterfaceGroupName. /// </summary> /// <param name="interfaceList">The interface list from server.</param> /// <returns>InterfaceGroupName array. /// Index 0: InterfaceGroupName of the registered node. /// Index 1: InterfaceGroupName of the witnessed node.</returns> public static string[] GetInterfaceGroupName(WITNESS_INTERFACE_LIST interfaceList) { // TODO: string[] interfaceGroupName = new string[2]; foreach (var info in interfaceList.InterfaceInfo) { if ((info.Flags & (uint)SwnNodeFlagsValue.INTERFACE_WITNESS) != 0) { // InterfaceGroupName of the registered node. interfaceGroupName[0] = info.InterfaceGroupName; } if ((info.Flags & (uint)SwnNodeFlagsValue.INTERFACE_WITNESS) == 0) { // InterfaceGroupName of the witnessed node. interfaceGroupName[1] = info.InterfaceGroupName; } } return interfaceGroupName; } public static IPAddress ConvertIPV6(ushort[] ipv6) { byte[] buffer = new byte[16]; Buffer.BlockCopy(ipv6, 0, buffer, 0, 16); return new IPAddress(buffer); } /// <summary> /// Check SWN version /// </summary> /// <param name="expectedVersion">The expected SWN Version.</param> /// <param name="actualVersion">The actual SWN Version.</param> public static void CheckVersion(SwnVersion expectedVersion, SwnVersion actualVersion) { if ((uint)actualVersion < (uint)expectedVersion) { // If server's actual SWN version is less than the expected version to run this test case, set it as inconclusive. BaseTestSite.Assert.Inconclusive("Test case is not applicable to servers that support SWN Version 0x{0:X08}.", (uint)actualVersion); } } } }
51.390476
179
0.5596
[ "MIT" ]
G-arj/WindowsProtocolTestSuites
TestSuites/FileServer/src/ServerFailover/TestSuite/SWN/SWNTestUtility.cs
26,980
C#
using System; namespace CallTargetNativeTest { internal abstract class AbstractClass { public abstract void VoidMethod(string name); } internal class Impl01OfAbstract : AbstractClass { public override void VoidMethod(string name) { } public void OtherMethod() { Console.WriteLine("Hello from the other method"); } } internal class Impl02OfAbstract : AbstractClass { public override void VoidMethod(string name) { } } internal class NonAbstractClass { public virtual void VoidMethod(string name) { Console.WriteLine("Hello from NonAbstractClass"); } } internal class Impl01OfNonAbstract : NonAbstractClass { public override void VoidMethod(string name) { Console.WriteLine("Hello from Impl01OfNonAbstract "); } } internal class Impl02OfNonAbstract : NonAbstractClass { public override void VoidMethod(string name) { base.VoidMethod(name); } } }
21.188679
65
0.599288
[ "Apache-2.0" ]
DataDog/dd-trace-csharp
tracer/test/test-applications/instrumentation/CallTargetNativeTest/Derived.cs
1,123
C#
/* Copyright 2013 Microsoft Corporation Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ using System; using System.Configuration; using System.Data; using System.Data.Common; using System.Data.SqlClient; using System.Transactions; using Microsoft.Practices.EnterpriseLibrary.Data; using Microsoft.VisualStudio.TestTools.UnitTesting; namespace Microsoft.Practices.EnterpriseLibrary.Data.BVT.CommonDatabase { [TestClass] public class DTCFixture : EntLibFixtureBase { public DTCFixture() : base("ConfigFiles.OlderTestsConfiguration.config") { } [TestInitialize()] public override void Initialize() { ServiceHelper.Start("MSDTC"); System.Threading.Thread.Sleep(15000); ConnectionStringsSection section = (ConnectionStringsSection)base.ConfigurationSource.GetSection("connectionStrings"); connStr = section.ConnectionStrings["DataSQLTest"].ConnectionString; SqlConnection conn = new SqlConnection(); conn.ConnectionString = connStr; conn.Open(); SqlCommand cmd = new SqlCommand("Delete from DTCTable", conn); cmd.ExecuteNonQuery(); conn.Close(); ServiceHelper.Stop("MSDTC"); DatabaseFactory.SetDatabaseProviderFactory(new DatabaseProviderFactory(), false); } [TestCleanup] public override void Cleanup() { DatabaseFactory.ClearDatabaseProviderFactory(); base.Cleanup(); } [TestMethod] public void TransactionScopeTimesOutAndTransactionIsRolledBack() { ServiceHelper.Start("MSDTC"); System.Threading.Thread.Sleep(15000); using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = connStr; conn.Open(); SqlTransaction trans = conn.BeginTransaction(); SqlCommand cmRowCont = null; int numberOfRows = 0; try { SqlCommand cmd = new SqlCommand("insert into DTCTable Values(1,'Narayan')", conn, trans); cmd.ExecuteNonQuery(); cmRowCont = new SqlCommand("select count(eno) from DTCTable", conn, trans); numberOfRows = (int)cmRowCont.ExecuteScalar(); using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew)) { //generating an exception Database db = DatabaseFactory.CreateDatabase("DataSQLTest"); SqlConnection conn1 = new SqlConnection(); conn1.ConnectionString = connStr; //primary key violation SqlCommand cmd1 = new SqlCommand("insert into DTCTable values(1,'Narayan')", conn1); db.ExecuteNonQuery(cmd1); ts.Complete(); } trans.Commit(); Assert.Fail("Exception was not raised"); } catch (Exception) { trans.Rollback(); int numberOfRowsafter = (int)cmRowCont.ExecuteScalar(); Assert.AreEqual(numberOfRows - 1, numberOfRowsafter); } } } [TestMethod] public void TransactionSucceedsWithDTC() { ServiceHelper.Start("MSDTC"); System.Threading.Thread.Sleep(15000); using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew)) { using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = connStr; conn.Open(); SqlCommand cmd = new SqlCommand("insert into DTCTable Values(1,'Narayan')", conn); cmd.ExecuteNonQuery(); } // using DAAB with transaction Database db = DatabaseFactory.CreateDatabase("DataSQLTest"); using (DbConnection connection = db.CreateConnection()) { connection.Open(); DbTransaction transaction = connection.BeginTransaction(); db.ExecuteNonQuery(transaction, CommandType.Text, "insert into DTCTable Values(2,'Nandan')"); transaction.Commit(); } using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = connStr; conn.Open(); SqlCommand cmRowCont = new SqlCommand("select count(eno) from DTCTable", conn); int numberOfRows = (int)cmRowCont.ExecuteScalar(); Assert.AreEqual(numberOfRows, 2); } ts.Complete(); } ServiceHelper.Stop("MSDTC"); } [TestMethod] public void RowsAreInsertedWithoutTransactionWhenUsingDTC() { ServiceHelper.Start("MSDTC"); System.Threading.Thread.Sleep(15000); using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew)) { using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = connStr; conn.Open(); SqlCommand cmd = new SqlCommand("insert into DTCTable Values(1,'Narayan')", conn); cmd.ExecuteNonQuery(); } // using DAAB with transaction Database db = DatabaseFactory.CreateDatabase("DataSQLTest"); using (SqlConnection conn1 = new SqlConnection()) { conn1.ConnectionString = connStr; SqlCommand cmd = new SqlCommand("insert into DTCTable values(2,'Nandan')", conn1); db.ExecuteNonQuery(cmd); } using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = connStr; conn.Open(); SqlCommand cmRowCont = new SqlCommand("select count(eno) from DTCTable", conn); int numberOfRows = (int)cmRowCont.ExecuteScalar(); Assert.AreEqual(numberOfRows, 2); conn.Close(); } ts.Complete(); } ServiceHelper.Stop("MSDTC"); } [TestMethod] public void InnerTransactionFailsButOuterTransactionCommitsWhenSuppressingInner() { ServiceHelper.Start("MSDTC"); System.Threading.Thread.Sleep(15000); using (TransactionScope ts = new TransactionScope(TransactionScopeOption.RequiresNew)) { using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = connStr; conn.Open(); SqlCommand cmd = new SqlCommand("insert into DTCTable Values(1,'Narayan')", conn); cmd.ExecuteNonQuery(); } try { using (TransactionScope ts1 = new TransactionScope(TransactionScopeOption.Suppress)) { Database db = DatabaseFactory.CreateDatabase("DataSQLTest"); SqlConnection conn1 = new SqlConnection(); conn1.ConnectionString = connStr; SqlCommand cmd = new SqlCommand("insert into DTCTable values(1,'Nandan')", conn1); db.ExecuteNonQuery(cmd); ts1.Complete(); } } catch (Exception) { } using (SqlConnection conn = new SqlConnection()) { conn.ConnectionString = connStr; conn.Open(); SqlCommand cmRowCont = new SqlCommand("select count(eno) from DTCTable", conn); int numberOfRows = (int)cmRowCont.ExecuteScalar(); Assert.AreEqual(numberOfRows, 1); conn.Close(); } ts.Complete(); } ServiceHelper.Stop("MSDTC"); } } }
40.565022
130
0.54256
[ "Apache-2.0" ]
tsahi/data-access-application-block
BVT/Data.BVT/CommonDatabase/DTCFixture.cs
9,046
C#
// Copyright (c) 2007-2018 Thong Nguyen (tumtumtum@gmail.com) using System; using System.Collections.Generic; using System.IO; using System.Linq; using System.Reflection; using System.Text; using System.Threading; using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; namespace Shaolinq.AsyncRewriter { public class Rewriter { private static readonly string[] alwaysExcludedTypeNames = { "System.IO.TextWriter", "System.IO.StringWriter", "System.IO.MemoryStream" }; private CompilationLookup lookup; private readonly IAsyncRewriterLogger log; private HashSet<ITypeSymbol> excludedTypes; private ITypeSymbol methodAttributesSymbol; private ITypeSymbol cancellationTokenSymbol; private CSharpCompilation compilation; private readonly HashSet<string> typesAlreadyWarnedAbout = new HashSet<string>(); private static readonly UsingDirectiveSyntax[] extraUsingDirectives = { SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System")), SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Threading")), SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("System.Threading.Tasks")) }; public Rewriter(IAsyncRewriterLogger log = null) { this.log = log ?? TextAsyncRewriterLogger.ConsoleLogger; } private static IEnumerable<string> GetNamespacesAndParents(string nameSpace) { var parts = nameSpace.Split('.'); var current = new StringBuilder(); foreach (var part in parts) { current.Append(part); yield return current.ToString(); current.Append('.'); } } private CompilationUnitSyntax UpdateUsings(CompilationUnitSyntax compilationUnit) { var namespaces = compilationUnit.Members.OfType<NamespaceDeclarationSyntax>().ToList(); var usings = compilationUnit.Usings; usings = usings .AddRange(extraUsingDirectives) .AddRange(namespaces.SelectMany(c => GetNamespacesAndParents(c.Name.ToString()).Select(d => SyntaxFactory.UsingDirective(SyntaxFactory.ParseName(d))))) .Sort(); usings = usings.Replace(usings[0], usings[0].WithLeadingTrivia ( SyntaxFactory.EndOfLine(Environment.NewLine), SyntaxFactory.Trivia(SyntaxFactory.PragmaWarningDirectiveTrivia(SyntaxFactory.Token(SyntaxKind.DisableKeyword), true)), SyntaxFactory.EndOfLine(Environment.NewLine) )); return compilationUnit.WithUsings(usings); } public string RewriteAndMerge(string[] paths, string[] additionalAssemblyNames = null, string[] excludeTypes = null) { var syntaxTrees = paths .Select(p => SyntaxFactory.ParseSyntaxTree(File.ReadAllText(p)).WithFilePath(p)) .Select(c => c.WithRootAndOptions(UpdateUsings(c.GetCompilationUnitRoot()), c.Options)) .ToArray(); var references = new List<MetadataReference>() { MetadataReference.CreateFromFile(typeof(object).GetTypeInfo().Assembly.Location), MetadataReference.CreateFromFile(typeof(Queryable).GetTypeInfo().Assembly.Location) }; if (additionalAssemblyNames != null) { var assemblyPath = Path.GetDirectoryName(typeof(object).GetTypeInfo().Assembly.Location); this.log.LogMessage("FrameworkPath: " + assemblyPath); if (assemblyPath == null) { throw new InvalidOperationException(); } var facadesLoaded = new HashSet<string>(StringComparer.InvariantCultureIgnoreCase); var loadedAssemblies = new List<string>(); references.AddRange(additionalAssemblyNames.SelectMany(n => { var results = new List<MetadataReference>(); if (File.Exists(n)) { var facadesPath = Path.Combine(Path.GetDirectoryName(n) ?? "", "Facades"); results.Add(MetadataReference.CreateFromFile(n)); loadedAssemblies.Add(n); if (Directory.Exists(facadesPath) && !facadesLoaded.Contains(facadesPath)) { facadesLoaded.Add(facadesPath); results.AddRange(Directory.GetFiles(facadesPath).Select(facadeDll => MetadataReference.CreateFromFile(facadeDll))); } return results; } if (File.Exists(Path.Combine(assemblyPath, n))) { results.Add(MetadataReference.CreateFromFile(Path.Combine(assemblyPath, n))); return results; } this.log.LogError($"Could not find referenced assembly: {n}"); return results; }).Where(c => c != null)); } var options = new CSharpCompilationOptions(OutputKind.DynamicallyLinkedLibrary).WithAssemblyIdentityComparer(DesktopAssemblyIdentityComparer.Default); this.compilation = CSharpCompilation .Create("Temp", syntaxTrees, references, options); this.lookup = new CompilationLookup(this.compilation); var resultTree = RewriteAndMerge(syntaxTrees, this.compilation, excludeTypes); var retval = resultTree.ToString(); #if OUTPUT_COMPILER_ERRORS var correctedTrees = this.CorrectAsyncCalls(this.compilation, syntaxTrees, excludeTypes); var newCompilation = this.compilation = CSharpCompilation .Create("Temp", correctedTrees.Concat(new [] { resultTree }).ToArray(), references, options); var emitResult = newCompilation.Emit(Stream.Null); if (emitResult.Diagnostics.Any()) { log.LogMessage("Compiler errors:"); foreach (var diagnostic in emitResult.Diagnostics) { var message = diagnostic.GetMessage(); if (diagnostic.Severity == DiagnosticSeverity.Info) { log.LogMessage(message); } else { log.LogError(message); } } } #endif return retval; } private IEnumerable<SyntaxTree> CorrectAsyncCalls(Compilation compilationNode, SyntaxTree[] syntaxTrees, string[] excludeTypes) { this.methodAttributesSymbol = compilationNode.GetTypeByMetadataName(typeof(MethodAttributes).FullName); this.cancellationTokenSymbol = compilationNode.GetTypeByMetadataName(typeof(CancellationToken).FullName); this.excludedTypes = new HashSet<ITypeSymbol>(); if (excludeTypes != null) { var excludedTypeSymbols = excludeTypes.Select(compilationNode.GetTypeByMetadataName).ToList(); var notFound = excludedTypeSymbols.IndexOf(null); if (notFound != -1) { throw new ArgumentException($"Type {excludeTypes[notFound]} not found in compilation", nameof(excludeTypes)); } this.excludedTypes.UnionWith(excludedTypeSymbols); } this.excludedTypes.UnionWith(alwaysExcludedTypeNames.Select(compilationNode.GetTypeByMetadataName).Where(sym => sym != null)); foreach (var syntaxTree in syntaxTrees) { var semanticModel = compilationNode.GetSemanticModel(syntaxTree, true); if (semanticModel == null) { throw new ArgumentException("A provided syntax tree was compiled into the provided compilation"); } var newRoot = syntaxTree .GetRoot() .ReplaceNodes(syntaxTree.GetRoot().DescendantNodes(), (a, b) => { var method = b as MethodDeclarationSyntax; if (method == null) { return b; } return method.WithBody(GeneratedAsyncMethodSubstitutor.Rewrite(this.log, this.lookup, semanticModel, this.excludedTypes, this.cancellationTokenSymbol, method).Body); }); yield return syntaxTree.WithRootAndOptions(newRoot, syntaxTree.Options); } } private static NamespaceDeclarationSyntax AmendUsings(NamespaceDeclarationSyntax nameSpace, SyntaxList<UsingDirectiveSyntax> usings) { var last = nameSpace.Name.ToString().Right(c => c != '.'); foreach (var item in usings) { var name = item.Name.ToString(); var first = name.Left(c => c != '.'); if (first == last) { usings = usings.Remove(item); usings = usings.Add(SyntaxFactory.UsingDirective(SyntaxFactory.ParseName("global::" + name))); } } return nameSpace.WithUsings(usings); } private SyntaxTree RewriteAndMerge(SyntaxTree[] syntaxTrees, CSharpCompilation compilationNode, string[] excludeTypes = null) { var rewrittenTrees = Rewrite(syntaxTrees, compilationNode, excludeTypes).ToArray(); return SyntaxFactory.SyntaxTree ( InterpolatedFormatSpecifierFixer.Fix ( ParenthesizedExpressionStatementFixer.Fix ( SyntaxFactory.CompilationUnit() .WithMembers ( SyntaxFactory.List ( rewrittenTrees.SelectMany ( c => c.GetCompilationUnitRoot().Members ) ) ) ).NormalizeWhitespace("\t") ) ); } private bool AllMethodsInClassShouldBeAsync(ITypeSymbol type) { var initialType = type; while (type != null) { var attributeSyntax = (AttributeSyntax)type.GetAttributes().FirstOrDefault(c => ((AttributeSyntax)c.ApplicationSyntaxReference?.GetSyntax()) ?.Name.ToString() == "RewriteAsync")?.ApplicationSyntaxReference?.GetSyntax(); if (attributeSyntax?.ArgumentList?.Arguments.Any(c => c.NameEquals.Name.ToString() == "ApplyToDescendents") == true) { var x = attributeSyntax?.ArgumentList.Arguments.First(c => c.NameEquals.Name.ToString() == "ApplyToDescendents"); if (x.Expression.ToString().Equals("true", StringComparison.OrdinalIgnoreCase)) { return true; } if (x.Expression.ToString().Equals("false", StringComparison.OrdinalIgnoreCase)) { return type == initialType; } } if (attributeSyntax != null && type == initialType) { return true; } type = type.BaseType; } return false; } public IEnumerable<SyntaxTree> Rewrite(SyntaxTree[] syntaxTrees, CSharpCompilation compilationNode, string[] excludeTypes = null) { this.methodAttributesSymbol = compilationNode.GetTypeByMetadataName(typeof(MethodAttributes).FullName); this.cancellationTokenSymbol = compilationNode.GetTypeByMetadataName(typeof(CancellationToken).FullName); this.excludedTypes = new HashSet<ITypeSymbol>(); if (excludeTypes != null) { var excludedTypeSymbols = excludeTypes.Select(compilationNode.GetTypeByMetadataName).ToList(); var notFound = excludedTypeSymbols.IndexOf(null); if (notFound != -1) { throw new ArgumentException($"Type {excludeTypes[notFound]} not found in compilation", nameof(excludeTypes)); } this.excludedTypes.UnionWith(excludedTypeSymbols); } this.excludedTypes.UnionWith(alwaysExcludedTypeNames.Select(compilationNode.GetTypeByMetadataName).Where(sym => sym != null)); foreach (var syntaxTree in syntaxTrees) { var semanticModel = compilationNode.GetSemanticModel(syntaxTree, true); if (semanticModel == null) { throw new ArgumentException("A provided syntax tree was compiled into the provided compilation"); } var asyncMethods = syntaxTree .GetRoot() .DescendantNodes() .OfType<MethodDeclarationSyntax>() .Where(m => m.Modifiers.Any(c => c.Kind() == SyntaxKind.AsyncKeyword)); foreach (var asyncMethod in asyncMethods) { ValidateAsyncMethod(asyncMethod, semanticModel); } if (syntaxTree.GetRoot().DescendantNodes().All(m => ((m as MethodDeclarationSyntax)?.AttributeLists ?? (m as TypeDeclarationSyntax)?.AttributeLists)?.SelectMany(al => al.Attributes).Any(a => a.Name.ToString().StartsWith("RewriteAsync")) == null)) { if (syntaxTree.GetRoot().DescendantNodes().OfType<TypeDeclarationSyntax>().All(c => AllMethodsInClassShouldBeAsync(semanticModel.GetDeclaredSymbol(c)))) { continue; } } var namespaces = SyntaxFactory.List<MemberDeclarationSyntax> ( syntaxTree.GetRoot() .DescendantNodes() .OfType<MethodDeclarationSyntax>() .Where(m => AllMethodsInClassShouldBeAsync(semanticModel.GetDeclaredSymbol(m.Parent as TypeDeclarationSyntax)) || m.AttributeLists.SelectMany(al => al.Attributes).Any(a => a.Name.ToString().StartsWith("RewriteAsync"))) .Where(c => (c.FirstAncestorOrSelf<ClassDeclarationSyntax>() as TypeDeclarationSyntax ?? c.FirstAncestorOrSelf<InterfaceDeclarationSyntax>() as TypeDeclarationSyntax) != null) .GroupBy(m => m.FirstAncestorOrSelf<ClassDeclarationSyntax>() as TypeDeclarationSyntax ?? m.FirstAncestorOrSelf<InterfaceDeclarationSyntax>()) .GroupBy(g => g.Key.FirstAncestorOrSelf<NamespaceDeclarationSyntax>()) .Select(namespaceGrouping => SyntaxFactory.NamespaceDeclaration(namespaceGrouping.Key.Name) .WithMembers(SyntaxFactory.List<MemberDeclarationSyntax> ( namespaceGrouping.Select ( typeGrouping => typeGrouping.Key is ClassDeclarationSyntax ? (SyntaxFactory.ClassDeclaration(typeGrouping.Key.Identifier) .WithModifiers(typeGrouping.Key.Modifiers) .WithTypeParameterList(typeGrouping.Key.TypeParameterList) .WithMembers(SyntaxFactory.List<MemberDeclarationSyntax>(typeGrouping.SelectMany(m => RewriteMethods(m, semanticModel)))) as TypeDeclarationSyntax) .WithLeadingTrivia(new SyntaxTriviaList()) : (SyntaxFactory.InterfaceDeclaration(typeGrouping.Key.Identifier).WithModifiers(typeGrouping.Key.Modifiers) .WithTypeParameterList(typeGrouping.Key.TypeParameterList) .WithMembers(SyntaxFactory.List<MemberDeclarationSyntax>(typeGrouping.SelectMany(m => RewriteMethods(m, semanticModel)))) as TypeDeclarationSyntax) .WithLeadingTrivia(new SyntaxTriviaList()) ) )) ) ); yield return SyntaxFactory.SyntaxTree ( SyntaxFactory.CompilationUnit() .WithMembers(SyntaxFactory.List<MemberDeclarationSyntax>(namespaces.OfType<NamespaceDeclarationSyntax>().Select(c => AmendUsings(c, syntaxTree.GetCompilationUnitRoot().Usings)))) .WithEndOfFileToken(SyntaxFactory.Token(SyntaxKind.EndOfFileToken)) ); } } IEnumerable<MethodDeclarationSyntax> RewriteMethods(MethodDeclarationSyntax inMethodSyntax, SemanticModel semanticModel) { var result = RewriteMethodAsync(inMethodSyntax, semanticModel, false); if (result != null) { yield return result; } yield return RewriteMethodAsync(inMethodSyntax, semanticModel, true); } private IEnumerable<IMethodSymbol> GetMethods(SemanticModel semanticModel, ITypeSymbol symbol, string name, MethodDeclarationSyntax method, MethodDeclarationSyntax originalMethod) { var parameters = method.ParameterList.Parameters; var retval = GetAllMembers(symbol) .Where(c => c.Name == name) .OfType<IMethodSymbol>() .Where(c => c.Parameters.Select(d => GetParameterTypeComparisonKey(d.Type)).SequenceEqual(parameters.Select(d => GetParameterTypeComparisonKey(semanticModel.GetSpeculativeTypeInfo(originalMethod.ParameterList.SpanStart, d.Type, SpeculativeBindingOption.BindAsExpression).Type, method, d.Type)))); return retval; } private object GetParameterTypeComparisonKey(ITypeSymbol symbol, MethodDeclarationSyntax method = null, TypeSyntax typeSyntax = null) { if (symbol is ITypeParameterSymbol typedParameterSymbol) { return typedParameterSymbol.Ordinal; } if (symbol != null && symbol.TypeKind != TypeKind.Error) { return symbol; } return method?.TypeParameterList?.Parameters.IndexOf(c => c?.Identifier.Text == typeSyntax?.ToString()) ?? (object)symbol; } private IEnumerable<ISymbol> GetAllMembers(ITypeSymbol symbol, bool includeParents = true) { foreach (var member in symbol.GetMembers()) { yield return member; } if (symbol.BaseType != null && includeParents) { foreach (var member in symbol.BaseType.GetMembers()) { yield return member; } } } private void ValidateAsyncMethod(MethodDeclarationSyntax methodSyntax, SemanticModel semanticModel) { var methodSymbol = (IMethodSymbol)ModelExtensions.GetDeclaredSymbol(semanticModel, methodSyntax); var results = AsyncMethodValidator.Validate(methodSyntax, this.log, this.lookup, semanticModel, this.excludedTypes, this.cancellationTokenSymbol); if (results.Count > 0) { foreach (var result in results) { if (!result.ReplacementMethodSymbol.Equals(methodSymbol)) { this.log.LogWarning($"Async method call possible in {result.Position.GetLineSpan()}"); this.log.LogWarning($"Replace {result.MethodInvocationSyntax.NormalizeWhitespace()} with {result.ReplacementExpressionSyntax.NormalizeWhitespace()}"); } } } } private MethodDeclarationSyntax RewriteMethodAsync(MethodDeclarationSyntax methodSyntax, SemanticModel semanticModel, bool cancellationVersion) { var asyncMethodName = methodSyntax.Identifier.Text + "Async"; var methodSymbol = (IMethodSymbol)ModelExtensions.GetDeclaredSymbol(semanticModel, methodSyntax); var isInterfaceMethod = methodSymbol.ContainingType.TypeKind == TypeKind.Interface; if (((methodSyntax.Parent as TypeDeclarationSyntax)?.Modifiers)?.Any(c => c.Kind() == SyntaxKind.PartialKeyword) != true) { var name = ((TypeDeclarationSyntax)methodSyntax.Parent).Identifier.ToString(); if (!this.typesAlreadyWarnedAbout.Contains(name)) { this.typesAlreadyWarnedAbout.Add(name); this.log.LogError($"Type '{name}' needs to be marked as partial"); } } var returnTypeName = methodSyntax.ReturnType.ToString(); var newAsyncMethod = methodSyntax .WithIdentifier(SyntaxFactory.Identifier(asyncMethodName)) .WithAttributeLists(new SyntaxList<AttributeListSyntax>()) .WithReturnType(SyntaxFactory.ParseTypeName(returnTypeName == "void" ? "Task" : $"Task<{returnTypeName}>")); if (cancellationVersion) { newAsyncMethod = MethodInvocationAsyncRewriter.Rewrite(this.log, this.lookup, semanticModel, this.excludedTypes, this.cancellationTokenSymbol, methodSyntax); newAsyncMethod = newAsyncMethod .WithIdentifier(SyntaxFactory.Identifier(asyncMethodName)) .WithAttributeLists(new SyntaxList<AttributeListSyntax>()) .WithReturnType(SyntaxFactory.ParseTypeName(returnTypeName == "void" ? "Task" : $"Task<{returnTypeName}>")); newAsyncMethod = newAsyncMethod.WithParameterList(SyntaxFactory.ParameterList(methodSyntax.ParameterList.Parameters.Insert ( methodSyntax.ParameterList.Parameters.TakeWhile(p => p.Default == null && !p.Modifiers.Any(m => m.IsKind(SyntaxKind.ParamsKeyword))).Count(), SyntaxFactory.Parameter ( SyntaxFactory.List<AttributeListSyntax>(), SyntaxFactory.TokenList(), SyntaxFactory.ParseTypeName(this.cancellationTokenSymbol.ToMinimalDisplayString(semanticModel, newAsyncMethod.SpanStart)), SyntaxFactory.Identifier("cancellationToken"), null ) ))); if (!(isInterfaceMethod || methodSymbol.IsAbstract)) { newAsyncMethod = newAsyncMethod.WithModifiers(methodSyntax.Modifiers.Add(SyntaxFactory.Token(SyntaxKind.AsyncKeyword))); } } else { var thisExpression = (ExpressionSyntax)SyntaxFactory.ThisExpression(); if (methodSymbol.ExplicitInterfaceImplementations.Length > 0) { thisExpression = SyntaxFactory.ParenthesizedExpression(SyntaxFactory.CastExpression(SyntaxFactory.ParseTypeName(methodSymbol.ExplicitInterfaceImplementations[0].ContainingType.ToDisplayString(SymbolDisplayFormat.MinimallyQualifiedFormat)), thisExpression)); } SimpleNameSyntax methodName; if (methodSymbol.TypeParameters.Length == 0) { methodName = SyntaxFactory.IdentifierName(asyncMethodName); } else { methodName = SyntaxFactory.GenericName(SyntaxFactory.Identifier(asyncMethodName), SyntaxFactory.TypeArgumentList(SyntaxFactory.SeparatedList(methodSymbol.TypeParameters.Select(c => SyntaxFactory.ParseTypeName(c.Name))))); } var invocationTarget = (ExpressionSyntax)methodName; if (!methodSymbol.IsStatic) { invocationTarget = SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, thisExpression, methodName); } var callAsyncWithCancellationToken = SyntaxFactory.InvocationExpression ( invocationTarget, SyntaxFactory.ArgumentList ( new SeparatedSyntaxList<ArgumentSyntax>() .AddRange(methodSymbol.Parameters.TakeWhile(c => !(c.HasExplicitDefaultValue || c.IsParams)).Select(c => SyntaxFactory.Argument(SyntaxFactory.IdentifierName(c.Name)))) .Add(SyntaxFactory.Argument(SyntaxFactory.MemberAccessExpression(SyntaxKind.SimpleMemberAccessExpression, SyntaxFactory.ParseName("CancellationToken"), SyntaxFactory.IdentifierName("None")))) .AddRange(methodSymbol.Parameters.SkipWhile(c => !(c.HasExplicitDefaultValue || c.IsParams)).Select(c => SyntaxFactory.Argument(SyntaxFactory.IdentifierName(c.Name)))) ) ); if (!(isInterfaceMethod || methodSymbol.IsAbstract)) { if (newAsyncMethod.ExpressionBody != null) { newAsyncMethod = newAsyncMethod.WithExpressionBody(SyntaxFactory.ArrowExpressionClause(callAsyncWithCancellationToken)); } else { newAsyncMethod = newAsyncMethod.WithBody(SyntaxFactory.Block(SyntaxFactory.ReturnStatement(callAsyncWithCancellationToken))); } } } if (!(isInterfaceMethod || methodSymbol.IsAbstract)) { var baseAsyncMethod = GetMethods(semanticModel, methodSymbol.ReceiverType.BaseType, methodSymbol.Name + "Async", newAsyncMethod, methodSyntax) .FirstOrDefault(); var baseMethod = GetMethods(semanticModel, methodSymbol.ReceiverType.BaseType, methodSymbol.Name, methodSyntax, methodSyntax) .FirstOrDefault(); var parentContainsAsyncMethod = baseAsyncMethod != null; var parentContainsMethodWithRewriteAsync = baseMethod?.GetAttributes().Any(c => c.AttributeClass.Name.StartsWith("RewriteAsync")) == true || baseMethod?.ContainingType.GetAttributes().Any(c => c.AttributeClass.Name.StartsWith("RewriteAsync")) == true; var hadNew = newAsyncMethod.Modifiers.Any(c => c.Kind() == SyntaxKind.NewKeyword); var hadOverride = newAsyncMethod.Modifiers.Any(c => c.Kind() == SyntaxKind.OverrideKeyword); if (!parentContainsAsyncMethod && hadNew) { newAsyncMethod = newAsyncMethod.WithModifiers(new SyntaxTokenList().AddRange(newAsyncMethod.Modifiers.Where(c => c.Kind() != SyntaxKind.NewKeyword))); } if (parentContainsAsyncMethod && !(baseAsyncMethod.IsVirtual || baseAsyncMethod.IsAbstract || baseAsyncMethod.IsOverride)) { return null; } if (!(parentContainsAsyncMethod || parentContainsMethodWithRewriteAsync)) { newAsyncMethod = newAsyncMethod.WithModifiers(new SyntaxTokenList().AddRange(newAsyncMethod.Modifiers.Where(c => c.Kind() != SyntaxKind.OverrideKeyword))); if (hadOverride) { newAsyncMethod = newAsyncMethod.WithModifiers(newAsyncMethod.Modifiers.Add(SyntaxFactory.Token(SyntaxKind.VirtualKeyword))); } } var baseMatchedMethod = baseMethod ?? baseAsyncMethod; if (methodSyntax.ConstraintClauses.Any()) { newAsyncMethod = newAsyncMethod.WithConstraintClauses(methodSyntax.ConstraintClauses); } else if (!hadOverride && baseMatchedMethod != null) { var constraintClauses = new List<TypeParameterConstraintClauseSyntax>(); foreach (var typeParameter in baseMatchedMethod.TypeParameters) { var constraintClause = SyntaxFactory.TypeParameterConstraintClause(typeParameter.Name); var constraints = new List<TypeParameterConstraintSyntax>(); if (typeParameter.HasReferenceTypeConstraint) { constraints.Add(SyntaxFactory.ClassOrStructConstraint(SyntaxKind.ClassConstraint)); } if (typeParameter.HasValueTypeConstraint) { constraints.Add(SyntaxFactory.ClassOrStructConstraint(SyntaxKind.StructConstraint)); } if (typeParameter.HasConstructorConstraint) { constraints.Add(SyntaxFactory.ConstructorConstraint()); } constraints.AddRange(typeParameter.ConstraintTypes.Select(c => SyntaxFactory.TypeConstraint(SyntaxFactory.ParseName(c.ToMinimalDisplayString(semanticModel, methodSyntax.SpanStart))))); constraintClause = constraintClause.WithConstraints(SyntaxFactory.SeparatedList(constraints)); constraintClauses.Add(constraintClause); } newAsyncMethod = newAsyncMethod.WithConstraintClauses(SyntaxFactory.List(constraintClauses)); } } var attribute = methodSymbol.GetAttributes().SingleOrDefault(a => a.AttributeClass.Name.EndsWith("RewriteAsyncAttribute")) ?? methodSymbol.ContainingType.GetAttributes().SingleOrDefault(a => a.AttributeClass.Name.EndsWith("RewriteAsyncAttribute")); if (attribute?.ConstructorArguments.Length > 0) { var first = attribute.ConstructorArguments.First(); if (first.Type.Equals(this.methodAttributesSymbol)) { var methodAttributes = (MethodAttributes)Enum.ToObject(typeof(MethodAttributes), Convert.ToInt32(first.Value)); newAsyncMethod = newAsyncMethod.WithAccessModifiers(methodAttributes); } } newAsyncMethod = newAsyncMethod .WithLeadingTrivia(methodSyntax.GetLeadingTrivia().Where(c => c.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia || c.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia || c.Kind() == SyntaxKind.EndOfLineTrivia || c.Kind() == SyntaxKind.WhitespaceTrivia)) .WithTrailingTrivia(methodSyntax.GetTrailingTrivia().Where(c => c.Kind() == SyntaxKind.MultiLineDocumentationCommentTrivia || c.Kind() == SyntaxKind.SingleLineDocumentationCommentTrivia || c.Kind() == SyntaxKind.EndOfLineTrivia || c.Kind() == SyntaxKind.WhitespaceTrivia)); return newAsyncMethod; } private static bool Equal(TextReader left, TextReader right) { while (true) { var l = left.Read(); var r = right.Read(); if (l != r) { return false; } if (l == -1) { return true; } } } public static void Rewrite(string[] input, string[] assemblies, string[] output, bool dontWriteIfNoChanges) { var log = TextAsyncRewriterLogger.ConsoleLogger; var rewriter = new Rewriter(log); var code = rewriter.RewriteAndMerge(input, assemblies); foreach (var outputFile in output) { var changed = true; var filename = outputFile; try { using (TextReader left = File.OpenText(filename), right = new StringReader(code)) { if (Equal(left, right)) { log.LogMessage($"{filename} has not changed"); changed = false; } } } catch (Exception) { } if (!changed && dontWriteIfNoChanges) { log.LogMessage($"Skipping writing {filename}"); continue; } File.WriteAllText(filename, code); } } } }
36.784657
301
0.704914
[ "MIT" ]
asizikov/Shaolinq
src/Shaolinq.AsyncRewriter/Rewriter.cs
27,333
C#
// ---------------------------------------------------------------------------------- // // Copyright Microsoft Corporation // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // http://www.apache.org/licenses/LICENSE-2.0 // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // ---------------------------------------------------------------------------------- namespace Microsoft.Azure.PowerShell.Cmdlets.Elastic.Runtime { using Microsoft.Azure.PowerShell.Cmdlets.Elastic.generated.runtime.Properties; using System; using System.Collections.Generic; using System.Linq; using System.Management.Automation; using System.Reflection; using System.Text; using System.Threading.Tasks; public class MessageAttributeHelper { public const string BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK = "https://aka.ms/azps-changewarnings"; public const string SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME = "SuppressAzurePowerShellBreakingChangeWarnings"; /** * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) * And reads all the deprecation attributes attached to it * Prints a message on the cmdline For each of the attribute found * * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, * We only process the Parameter beaking change attributes attached only params listed in this list (if present) * */ public static void ProcessCustomAttributesAtRuntime(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet, System.Management.Automation.PSCmdlet psCmdlet) { bool supressWarningOrError = false; try { supressWarningOrError = bool.Parse(System.Environment.GetEnvironmentVariable(SUPPRESS_ERROR_OR_WARNING_MESSAGE_ENV_VARIABLE_NAME)); } catch (Exception) { //no action } if (supressWarningOrError) { //Do not process the attributes at runtime... The env variable to override the warning messages is set return; } List<GenericBreakingChangeAttribute> attributes = new List<GenericBreakingChangeAttribute>(GetAllBreakingChangeAttributesInType(commandInfo, invocationInfo, parameterSet)); StringBuilder sb = new StringBuilder(); Action<string> appendBreakingChangeInfo = (string s) => sb.Append(s); if (attributes != null && attributes.Count > 0) { appendBreakingChangeInfo(string.Format(Resources.BreakingChangesAttributesHeaderMessage, commandInfo.Name.Split('_')[0])); foreach (GenericBreakingChangeAttribute attribute in attributes) { attribute.PrintCustomAttributeInfo(appendBreakingChangeInfo); } appendBreakingChangeInfo(string.Format(Resources.BreakingChangesAttributesFooterMessage, BREAKING_CHANGE_ATTRIBUTE_INFORMATION_LINK)); psCmdlet.WriteWarning(sb.ToString()); } List<PreviewMessageAttribute> previewAttributes = new List<PreviewMessageAttribute>(GetAllPreviewAttributesInType(commandInfo, invocationInfo)); if (previewAttributes != null && previewAttributes.Count > 0) { foreach (PreviewMessageAttribute attribute in previewAttributes) { attribute.PrintCustomAttributeInfo(psCmdlet); } } } /** * This function takes in a CommandInfo (CmdletInfo or FunctionInfo) * And returns all the deprecation attributes attached to it * * the boundParameterNames is a list of parameters bound to the cmdlet at runtime, * We only process the Parameter beaking change attributes attached only params listed in this list (if present) **/ private static IEnumerable<GenericBreakingChangeAttribute> GetAllBreakingChangeAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo, String parameterSet) { List<GenericBreakingChangeAttribute> attributeList = new List<GenericBreakingChangeAttribute>(); if (commandInfo.GetType() == typeof(CmdletInfo)) { var type = ((CmdletInfo)commandInfo).ImplementingType; attributeList.AddRange(type.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast<GenericBreakingChangeAttribute>()); foreach (MethodInfo m in type.GetRuntimeMethods()) { attributeList.AddRange((m.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast<GenericBreakingChangeAttribute>())); } foreach (FieldInfo f in type.GetRuntimeFields()) { attributeList.AddRange(f.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast<GenericBreakingChangeAttribute>()); } foreach (PropertyInfo p in type.GetRuntimeProperties()) { attributeList.AddRange(p.GetCustomAttributes(typeof(GenericBreakingChangeAttribute), false).Cast<GenericBreakingChangeAttribute>()); } } else if (commandInfo.GetType() == typeof(FunctionInfo)) { attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast<GenericBreakingChangeAttribute>()); foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) { attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(GenericBreakingChangeAttribute).IsAssignableFrom(e.GetType())).Cast<GenericBreakingChangeAttribute>()); } } return invocationInfo == null ? attributeList : attributeList.Where(e => e.GetType() == typeof(ParameterSetBreakingChangeAttribute) ? ((ParameterSetBreakingChangeAttribute)e).IsApplicableToInvocation(invocationInfo, parameterSet) : e.IsApplicableToInvocation(invocationInfo)); } private static IEnumerable<PreviewMessageAttribute> GetAllPreviewAttributesInType(CommandInfo commandInfo, InvocationInfo invocationInfo) { List<PreviewMessageAttribute> attributeList = new List<PreviewMessageAttribute>(); if (commandInfo.GetType() == typeof(CmdletInfo)) { var type = ((CmdletInfo)commandInfo).ImplementingType; attributeList.AddRange(type.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast<PreviewMessageAttribute>()); foreach (MethodInfo m in type.GetRuntimeMethods()) { attributeList.AddRange((m.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast<PreviewMessageAttribute>())); } foreach (FieldInfo f in type.GetRuntimeFields()) { attributeList.AddRange(f.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast<PreviewMessageAttribute>()); } foreach (PropertyInfo p in type.GetRuntimeProperties()) { attributeList.AddRange(p.GetCustomAttributes(typeof(PreviewMessageAttribute), false).Cast<PreviewMessageAttribute>()); } } else if (commandInfo.GetType() == typeof(FunctionInfo)) { attributeList.AddRange(((FunctionInfo)commandInfo).ScriptBlock.Attributes.Where(e => typeof(PreviewMessageAttribute).IsAssignableFrom(e.GetType())).Cast<PreviewMessageAttribute>()); foreach (var parameter in ((FunctionInfo)commandInfo).Parameters) { attributeList.AddRange(parameter.Value.Attributes.Where(e => typeof(PreviewMessageAttribute).IsAssignableFrom(e.GetType())).Cast<PreviewMessageAttribute>()); } } return invocationInfo == null ? attributeList : attributeList.Where(e => e.IsApplicableToInvocation(invocationInfo)); } } }
54.901235
289
0.642793
[ "MIT" ]
Agazoth/azure-powershell
src/Elastic/generated/runtime/MessageAttributeHelper.cs
8,735
C#
using System; namespace YouGe.Core.Repositorys { public class EmptyClass { public EmptyClass() { } } }
12.727273
32
0.55
[ "MIT" ]
chenqiangdage/YouGe.Core
YouGe.Core.Repositorys/EmptyClass.cs
142
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.Migrate.Models.Api20210210 { using Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.PowerShell; /// <summary> /// A PowerShell PSTypeConverter to support converting to an instance of <see cref="ReplicationAgentDetails" /> /// </summary> public partial class ReplicationAgentDetailsTypeConverter : global::System.Management.Automation.PSTypeConverter { /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c>. /// </returns> public override bool CanConvertFrom(object sourceValue, global::System.Type destinationType) => CanConvertFrom(sourceValue); /// <summary> /// Determines if the converter can convert the <see cref="sourceValue"/> parameter to the <see cref="destinationType" /> /// parameter. /// </summary> /// <param name="sourceValue">the <see cref="System.Object" /> instance to check if it can be converted to the <see cref="ReplicationAgentDetails" /// /> type.</param> /// <returns> /// <c>true</c> if the instance could be converted to a <see cref="ReplicationAgentDetails" /> type, otherwise <c>false</c> /// </returns> public static bool CanConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return true; } global::System.Type type = sourceValue.GetType(); if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { // we say yest to PSObjects return true; } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { // we say yest to Hashtables/dictionaries return true; } try { if (null != sourceValue.ToJsonString()) { return true; } } catch { // Not one of our objects } try { string text = sourceValue.ToString()?.Trim(); return true == text?.StartsWith("{") && true == text?.EndsWith("}") && Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonNode.Parse(text).Type == Microsoft.Azure.PowerShell.Cmdlets.Migrate.Runtime.Json.JsonType.Object; } catch { // Doesn't look like it can be treated as JSON } return false; } /// <summary> /// Determines if the <see cref="sourceValue" /> parameter can be converted to the <see cref="destinationType" /> parameter /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <returns> /// <c>true</c> if the converter can convert the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> /// parameter, otherwise <c>false</c> /// </returns> public override bool CanConvertTo(object sourceValue, global::System.Type destinationType) => false; /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns> /// an instance of <see cref="ReplicationAgentDetails" />, or <c>null</c> if there is no suitable conversion. /// </returns> public override object ConvertFrom(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => ConvertFrom(sourceValue); /// <summary> /// Converts the <see cref="sourceValue" /> parameter to the <see cref="destinationType" /> parameter using <see cref="formatProvider" /// /> and <see cref="ignoreCase" /> /// </summary> /// <param name="sourceValue">the value to convert into an instance of <see cref="ReplicationAgentDetails" />.</param> /// <returns> /// an instance of <see cref="ReplicationAgentDetails" />, or <c>null</c> if there is no suitable conversion. /// </returns> public static Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IReplicationAgentDetails ConvertFrom(dynamic sourceValue) { if (null == sourceValue) { return null; } global::System.Type type = sourceValue.GetType(); if (typeof(Microsoft.Azure.PowerShell.Cmdlets.Migrate.Models.Api20210210.IReplicationAgentDetails).IsAssignableFrom(type)) { return sourceValue; } try { return ReplicationAgentDetails.FromJsonString(typeof(string) == sourceValue.GetType() ? sourceValue : sourceValue.ToJsonString());; } catch { // Unable to use JSON pattern } if (typeof(global::System.Management.Automation.PSObject).IsAssignableFrom(type)) { return ReplicationAgentDetails.DeserializeFromPSObject(sourceValue); } if (typeof(global::System.Collections.IDictionary).IsAssignableFrom(type)) { return ReplicationAgentDetails.DeserializeFromDictionary(sourceValue); } return null; } /// <summary>NotImplemented -- this will return <c>null</c></summary> /// <param name="sourceValue">the <see cref="System.Object"/> to convert from</param> /// <param name="destinationType">the <see cref="System.Type" /> to convert to</param> /// <param name="formatProvider">not used by this TypeConverter.</param> /// <param name="ignoreCase">when set to <c>true</c>, will ignore the case when converting.</param> /// <returns>will always return <c>null</c>.</returns> public override object ConvertTo(object sourceValue, global::System.Type destinationType, global::System.IFormatProvider formatProvider, bool ignoreCase) => null; } }
52.244898
245
0.59362
[ "MIT" ]
Agazoth/azure-powershell
src/Migrate/generated/api/Models/Api20210210/ReplicationAgentDetails.TypeConverter.cs
7,534
C#
// Copyright 2022 Google LLC // // Licensed under the Apache License, Version 2.0 (the "License"); // you may not use this file except in compliance with the License. // You may obtain a copy of the License at // // https://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. // See the License for the specific language governing permissions and // limitations under the License. // Generated code. DO NOT EDIT! namespace Google.Cloud.Tasks.V2Beta3.Snippets { // [START cloudtasks_v2beta3_generated_CloudTasks_SetIamPolicy_sync] using Google.Api.Gax; using Google.Cloud.Iam.V1; using Google.Cloud.Tasks.V2Beta3; using Google.Protobuf.WellKnownTypes; public sealed partial class GeneratedCloudTasksClientSnippets { /// <summary>Snippet for SetIamPolicy</summary> /// <remarks> /// This snippet has been automatically generated for illustrative purposes only. /// It may require modifications to work in your environment. /// </remarks> public void SetIamPolicyRequestObject() { // Create client CloudTasksClient cloudTasksClient = CloudTasksClient.Create(); // Initialize request argument(s) SetIamPolicyRequest request = new SetIamPolicyRequest { ResourceAsResourceName = new UnparsedResourceName("a/wildcard/resource"), Policy = new Policy(), UpdateMask = new FieldMask(), }; // Make the request Policy response = cloudTasksClient.SetIamPolicy(request); } } // [END cloudtasks_v2beta3_generated_CloudTasks_SetIamPolicy_sync] }
38.428571
89
0.680297
[ "Apache-2.0" ]
AlexandrTrf/google-cloud-dotnet
apis/Google.Cloud.Tasks.V2Beta3/Google.Cloud.Tasks.V2Beta3.GeneratedSnippets/CloudTasksClient.SetIamPolicyRequestObjectSnippet.g.cs
1,883
C#
#region Usings using System; using System.Linq.Expressions; using JetBrains.Annotations; #endregion namespace Extend { /// <summary> /// Class containing some extension methods for <see cref="object" />. /// </summary> public static partial class ObjectEx { /// <summary> /// Gets the name of the member to which the given expression points. /// </summary> /// <exception cref="ArgumentNullException">expression can not be null.</exception> /// <exception cref="NotSupportedException"> /// The given expression is of a not supported type (supported are: /// <see cref="ExpressionType.MemberAccess" />, <see cref="ExpressionType.Convert" />). /// </exception> /// <typeparam name="TObject">The type of the source object.</typeparam> /// <typeparam name="TMember">The type of the member to which the expression points.</typeparam> /// <param name="obj">The source object.</param> /// <param name="expression">An expression pointing to the member to get the name of.</param> /// <returns>Returns the name of the member to which the given expression points.</returns> [NotNull] [Pure] [PublicAPI] public static String GetName<TObject, TMember>( [CanBeNull] this TObject obj, [NotNull] Expression<Func<TObject, TMember>> expression ) { expression.ThrowIfNull( nameof(expression) ); return GetName( expression.Body ); } /// <summary> /// Gets the name of the member to which the given expression points. /// </summary> /// <exception cref="ArgumentNullException">expression can not be null.</exception> /// <exception cref="NotSupportedException"> /// The given expression is of a not supported type (supported are: /// <see cref="ExpressionType.MemberAccess" />, <see cref="ExpressionType.Convert" />). /// </exception> /// <typeparam name="TObject">The type of the member to which the expression points.</typeparam> /// <typeparam name="TMember">The type of the member to which the expression points.</typeparam> /// <param name="obj">The object to call the method on.</param> /// <param name="expression">An expression pointing to the member to get the name of.</param> /// <returns>Returns the name of the member to which the given expression points.</returns> [NotNull] [Pure] [PublicAPI] public static String GetName<TObject, TMember>( [CanBeNull] [NoEnumeration] this TObject obj, [NotNull] Expression<Func<TMember>> expression ) { expression.ThrowIfNull( nameof(expression) ); return GetName( expression.Body ); } /// <summary> /// Gets the name of the member to which the given expression points. /// </summary> /// <param name="expression">The expression pointing to the member.</param> /// <exception cref="NotSupportedException"> /// expression is not supported (expression is <see cref="ConstantExpression" /> or /// <see cref="LambdaExpression" /> with an invalid body). /// </exception> /// <returns>Returns the name of the member to which the given expression points.</returns> [NotNull] [Pure] [PublicAPI] private static String GetName( [NotNull] Expression expression ) { if ( !expression.TryGetMemberExpression( out var memberExpression ) ) throw new ArgumentException( "The given expression was not valid." ); return memberExpression.Member.Name; } } }
46.731707
151
0.609603
[ "MIT" ]
DaveSenn/Extend
.Src/Extend/System.Object/Generic/Object.Generic.GetName.cs
3,753
C#
using System; namespace Lucene.Net.Search.Spell { /* * Licensed to the Apache Software Foundation (ASF) under one or more * contributor license agreements. See the NOTICE file distributed with * this work for additional information regarding copyright ownership. * The ASF licenses this file to You under the Apache License, Version 2.0 * (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ /// <summary> /// N-Gram version of edit distance based on paper by Grzegorz Kondrak, /// "N-gram similarity and distance". Proceedings of the Twelfth International /// Conference on String Processing and Information Retrieval (SPIRE 2005), pp. 115-126, /// Buenos Aires, Argentina, November 2005. /// <a href="http://www.cs.ualberta.ca/~kondrak/papers/spire05.pdf">http://www.cs.ualberta.ca/~kondrak/papers/spire05.pdf</a> /// /// This implementation uses the position-based optimization to compute partial /// matches of n-gram sub-strings and adds a null-character prefix of size n-1 /// so that the first character is contained in the same number of n-grams as /// a middle character. Null-character prefix matches are discounted so that /// strings with no matching characters will return a distance of 0. /// </summary> public class NGramDistance : IStringDistance { private readonly int n; // LUCENENET: marked readonly /// <summary> /// Creates an N-Gram distance measure using n-grams of the specified size. </summary> /// <param name="size"> The size of the n-gram to be used to compute the string distance. </param> public NGramDistance(int size) { this.n = size; } /// <summary> /// Creates an N-Gram distance measure using n-grams of size 2. /// </summary> public NGramDistance() : this(2) { } public virtual float GetDistance(string source, string target) { int sl = source.Length; int tl = target.Length; if (sl == 0 || tl == 0) { if (sl == tl) { return 1; } else { return 0; } } int cost = 0; if (sl < n || tl < n) { for (int i2 = 0, ni = Math.Min(sl, tl); i2 < ni; i2++) { if (source[i2] == target[i2]) { cost++; } } return (float)cost / Math.Max(sl, tl); } char[] sa = new char[sl + n - 1]; float[] p; //'previous' cost array, horizontally float[] d; // cost array, horizontally float[] _d; //placeholder to assist in swapping p and d //construct sa with prefix for (int i2 = 0; i2 < sa.Length; i2++) { if (i2 < n - 1) { sa[i2] = (char)0; //add prefix } else { sa[i2] = source[i2 - n + 1]; } } p = new float[sl + 1]; d = new float[sl + 1]; // indexes into strings s and t int i; // iterates through source int j; // iterates through target char[] t_j = new char[n]; // jth n-gram of t for (i = 0; i <= sl; i++) { p[i] = i; } for (j = 1; j <= tl; j++) { //construct t_j n-gram if (j < n) { for (int ti = 0; ti < n - j; ti++) { t_j[ti] = (char)0; //add prefix } for (int ti = n - j; ti < n; ti++) { t_j[ti] = target[ti - (n - j)]; } } else { t_j = target.Substring(j - n, j - (j - n)).ToCharArray(); } d[0] = j; for (i = 1; i <= sl; i++) { cost = 0; int tn = n; //compare sa to t_j for (int ni = 0; ni < n; ni++) { if (sa[i - 1 + ni] != t_j[ni]) { cost++; } else if (sa[i - 1 + ni] == 0) //discount matches on prefix { tn--; } } float ec = (float)cost / tn; // minimum of cell to the left+1, to the top+1, diagonally left and up +cost d[i] = Math.Min(Math.Min(d[i - 1] + 1, p[i] + 1), p[i - 1] + ec); } // copy current distance counts to 'previous row' distance counts _d = p; p = d; d = _d; } // our last action in the above loop was to switch d and p, so p now // actually has the most recent cost counts return 1.0f - (p[sl] / Math.Max(tl, sl)); } public override int GetHashCode() { return 1427 * n * this.GetType().GetHashCode(); } public override bool Equals(object obj) { if (this == obj) { return true; } if (null == obj || this.GetType() != obj.GetType()) { return false; } var o = (NGramDistance)obj; return o.n == this.n; } public override string ToString() { return "ngram(" + n + ")"; } } }
34.198953
129
0.442437
[ "Apache-2.0" ]
10088/lucenenet
src/Lucene.Net.Suggest/Spell/NGramDistance.cs
6,534
C#
using System.Reflection; using System.Runtime.CompilerServices; using System.Runtime.InteropServices; // General Information about an assembly is controlled through the following // set of attributes. Change these attribute values to modify the information // associated with an assembly. [assembly: AssemblyTitle("09.ExchangeVariableValues")] [assembly: AssemblyDescription("")] [assembly: AssemblyConfiguration("")] [assembly: AssemblyCompany("")] [assembly: AssemblyProduct("09.ExchangeVariableValues")] [assembly: AssemblyCopyright("Copyright © 2015")] [assembly: AssemblyTrademark("")] [assembly: AssemblyCulture("")] // Setting ComVisible to false makes the types in this assembly not visible // to COM components. If you need to access a type in this assembly from // COM, set the ComVisible attribute to true on that type. [assembly: ComVisible(false)] // The following GUID is for the ID of the typelib if this project is exposed to COM [assembly: Guid("4232d23d-7216-4e06-acf0-943aafc61d45")] // Version information for an assembly consists of the following four values: // // Major Version // Minor Version // Build Number // Revision // // You can specify all the values or you can default the Build and Revision Numbers // by using the '*' as shown below: // [assembly: AssemblyVersion("1.0.*")] [assembly: AssemblyVersion("1.0.0.0")] [assembly: AssemblyFileVersion("1.0.0.0")]
38.459459
84
0.748419
[ "MIT" ]
SHAMMY1/Telerik-Academy
Homeworks/CSharpPartOne/02.PrimitiveDataTypes/Primitive-Data-Types-Homework/09.ExchangeVariableValues/Properties/AssemblyInfo.cs
1,426
C#
using System; using System.Collections.Generic; using System.Linq; using System.Text; using System.Threading.Tasks; using Windows.ApplicationModel; namespace uwpApplicationBase { class IdentityChecker { public static bool SampleIdentityConfigurationCorrect(String AzureClientId = "Not applicable") { string outputMessage = ""; bool isCorrect = true; if (AzureClientId == "") { outputMessage += "Azure AD Client ID not set; cannot sign in with Azure AD\n"; isCorrect = false; } if (Package.Current.Id.Publisher == "CN=Microsoft Corporation, O=Microsoft Corporation, L=Redmond, S=Washington, C=US") { outputMessage += "Application identity not set; cannot sign in with Microsoft account.\n"; isCorrect = false; } if (!isCorrect) { outputMessage += "See Readme.MD for details"; } return isCorrect; } } }
29.243243
131
0.565619
[ "MIT" ]
freistli/WinStoreSDKCPP
uwpApplicationBase/IdentityChecker.cs
1,084
C#
/* * Copyright 2010-2013 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. */ using System.Collections.Generic; using Amazon.ElasticBeanstalk.Model; using Amazon.Runtime.Internal.Transform; namespace Amazon.ElasticBeanstalk.Model.Internal.MarshallTransformations { /// <summary> /// DescribeApplicationsResult Unmarshaller /// </summary> internal class DescribeApplicationsResultUnmarshaller : IUnmarshaller<DescribeApplicationsResult, XmlUnmarshallerContext>, IUnmarshaller<DescribeApplicationsResult, JsonUnmarshallerContext> { public DescribeApplicationsResult Unmarshall(XmlUnmarshallerContext context) { DescribeApplicationsResult describeApplicationsResult = new DescribeApplicationsResult(); int originalDepth = context.CurrentDepth; int targetDepth = originalDepth + 1; if (context.IsStartOfDocument) targetDepth += 2; while (context.Read()) { if (context.IsStartElement || context.IsAttribute) { if (context.TestExpression("Applications/member", targetDepth)) { describeApplicationsResult.Applications.Add(ApplicationDescriptionUnmarshaller.GetInstance().Unmarshall(context)); continue; } } else if (context.IsEndElement && context.CurrentDepth < originalDepth) { return describeApplicationsResult; } } return describeApplicationsResult; } public DescribeApplicationsResult Unmarshall(JsonUnmarshallerContext context) { return null; } private static DescribeApplicationsResultUnmarshaller instance; public static DescribeApplicationsResultUnmarshaller GetInstance() { if (instance == null) instance = new DescribeApplicationsResultUnmarshaller(); return instance; } } }
35.786667
194
0.63003
[ "Apache-2.0" ]
jdluzen/aws-sdk-net-android
AWSSDK/Amazon.ElasticBeanstalk/Model/Internal/MarshallTransformations/DescribeApplicationsResultUnmarshaller.cs
2,684
C#
using System; using System.Collections.Generic; using System.Data; using System.DrawingCore; using System.DrawingCore.Imaging; using System.IO; using System.Runtime.Serialization.Json; using System.Security.Cryptography; using System.Text; namespace Common { public class CommonHelper { #region 加解密 public static string _KEY = "JIYUWU66"; //密钥 public static string _IV = "JIYUWU88"; //向量 /// <summary> /// des 加密 /// </summary> /// <param name="data"></param> /// <returns></returns> public static string DesEncypt(string data) { byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_KEY); byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(_IV); using (DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider()) using (MemoryStream ms = new MemoryStream()) using (CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateEncryptor(byKey, byIV), CryptoStreamMode.Write)) using (StreamWriter sw = new StreamWriter(cst)) { int i = cryptoProvider.KeySize; sw.Write(data); sw.Flush(); cst.FlushFinalBlock(); sw.Flush(); string strRet = Convert.ToBase64String(ms.GetBuffer(), 0, (int)ms.Length); return strRet; } } /// <summary> /// des解密 /// </summary> /// <param name="data"></param> /// <returns></returns> public static string DesDecrypt(string data) { byte[] byKey = System.Text.ASCIIEncoding.ASCII.GetBytes(_KEY); byte[] byIV = System.Text.ASCIIEncoding.ASCII.GetBytes(_IV); byte[] byEnc; try { data.Replace("_%_", "/"); data.Replace("-%-", "#"); byEnc = Convert.FromBase64String(data); } catch { return null; } using (DESCryptoServiceProvider cryptoProvider = new DESCryptoServiceProvider()) using (MemoryStream ms = new MemoryStream(byEnc)) using (CryptoStream cst = new CryptoStream(ms, cryptoProvider.CreateDecryptor(byKey, byIV), CryptoStreamMode.Read)) using (StreamReader sr = new StreamReader(cst)) { return sr.ReadToEnd(); } } public static string CalcMD5(string str) { byte[] bytes = System.Text.Encoding.UTF8.GetBytes(str); return CalcMD5(bytes); } public static string CalcMD5(byte[] bytes) { using (MD5 md5 = MD5.Create()) { byte[] computeBytes = md5.ComputeHash(bytes); string result = ""; for (int i = 0; i < computeBytes.Length; i++) { result += computeBytes[i].ToString("X").Length == 1 ? "0" + computeBytes[i].ToString("X") : computeBytes[i].ToString("X"); } return result; } } public static string CalcMD5(Stream stream) { using (MD5 md5 = MD5.Create()) { byte[] computeBytes = md5.ComputeHash(stream); string result = ""; for (int i = 0; i < computeBytes.Length; i++) { result += computeBytes[i].ToString("X").Length == 1 ? "0" + computeBytes[i].ToString("X") : computeBytes[i].ToString("X"); } return result; } } ///编码 public static string EncodeBase64(string code_type, string code) { string encode = ""; byte[] bytes = Encoding.GetEncoding(code_type).GetBytes(code); try { encode = Convert.ToBase64String(bytes); } catch { encode = code; } return encode; } ///解码 public static string DecodeBase64(string code_type, string code) { string decode = ""; byte[] bytes = Convert.FromBase64String(code); try { decode = Encoding.GetEncoding(code_type).GetString(bytes); } catch { decode = code; } return decode; } #endregion #region json序列化与反序列化 #region model<->json(对象和json互转) #region DataContractJsonSerializer public static string SerializeDataContractJson<T>(T obj) { DataContractJsonSerializer json = new DataContractJsonSerializer(obj.GetType()); using (MemoryStream stream = new MemoryStream()) { json.WriteObject(stream, obj); string szJson = Encoding.UTF8.GetString(stream.ToArray()); return szJson; } } public static T DeserializeDataContractJson<T>(string szJson) { T obj = Activator.CreateInstance<T>(); using (MemoryStream ms = new MemoryStream(Encoding.UTF8.GetBytes(szJson))) { DataContractJsonSerializer serializer = new DataContractJsonSerializer(obj.GetType()); return (T)serializer.ReadObject(ms); } } #endregion #region Newtonsoft static public string SerializeJSON<T>(T data) { return Newtonsoft.Json.JsonConvert.SerializeObject(data); } static public T DeserializeJSON<T>(string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject<T>(json); } #endregion #endregion #region datatable<->json(datatable和json互转) public static string SerializeDataTableToJSON(DataTable dt) { return Newtonsoft.Json.JsonConvert.SerializeObject(dt); } public static DataTable SerializeJSONToDataTable(string json) { return Newtonsoft.Json.JsonConvert.DeserializeObject<DataTable>(json); } #region 自己写datatable转json用于测试速度对比下 public static string MyDataTableToJson(DataTable dt) { StringBuilder JsonString = new StringBuilder(); if (dt != null && dt.Rows.Count > 0) { JsonString.Append("{ "); JsonString.Append("\"TableInfo\":[ "); for (int i = 0; i < dt.Rows.Count; i++) { JsonString.Append("{ "); for (int j = 0; j < dt.Columns.Count; j++) { if (j < dt.Columns.Count - 1) { JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\","); } else if (j == dt.Columns.Count - 1) { JsonString.Append("\"" + dt.Columns[j].ColumnName.ToString() + "\":" + "\"" + dt.Rows[i][j].ToString() + "\""); } } if (i == dt.Rows.Count - 1) { JsonString.Append("} "); } else { JsonString.Append("}, "); } } JsonString.Append("]}"); return JsonString.ToString(); } else { return null; } } #endregion #endregion #region 返回json /// <summary> /// 得到一个包含Json信息的JsonResult /// </summary> /// <param name="isOK">服务器处理是否成功 1.成功 -1.失败 0.没有数据</param> /// <param name="msg">报错消息</param> /// <param name="data">携带的额外信息</param> /// <returns></returns> public static string GetJsonResult(int code, string msg, object data = null) { var jsonObj = new { code = code, msg = msg, data = data }; return Newtonsoft.Json.JsonConvert.SerializeObject(jsonObj); } public static string GetJsonFormat(int code, string msg, string data = null) { if(data!=null) return "{"+string.Format("\"code\":{0},\"msg\":\"{1}\",\"data\":{2}", code, msg, data)+"}"; else return "{" + string.Format("\"code\":{0},\"msg\":\"{1}\"", code, msg) + "}"; } public static string CodeJson(string code, string msg) { return "{\"code\":\"" + code + "\",\"msg\":\"" + msg + "\"}"; } #endregion #endregion #region 验证码 public static byte[] Bitmap2Byte(Bitmap bitmap) { using (MemoryStream stream = new MemoryStream()) { bitmap.Save(stream, ImageFormat.Jpeg); byte[] data = new byte[stream.Length]; stream.Seek(0, SeekOrigin.Begin); stream.Read(data, 0, Convert.ToInt32(stream.Length)); return data; } } #endregion #region Log /// <summary> /// 常规日志 /// </summary> /// <param name="s"></param> public static void WriteLog(string s) { var path = Directory.GetCurrentDirectory()+"\\LogAll";//文件保存位置 JIYUWU.TXT.TXTHelper.WriteLog(s, path); } /// <summary> /// 错误日志保存 /// </summary> /// <param name="s"></param> public static void WriteErrorLog(string s) { var path = Directory.GetCurrentDirectory()+ "\\LogAll\\LogError"; JIYUWU.TXT.TXTHelper.WriteLog(s, path); } /// <summary> /// 警告日志保存 /// </summary> /// <param name="s"></param> public static void WriteWareLog(string s) { var path = Directory.GetCurrentDirectory() + "\\LogAll\\LogWare"; JIYUWU.TXT.TXTHelper.WriteLog(s, path); } #endregion } }
33.687296
142
0.491008
[ "Apache-2.0" ]
adminQQF/TemplateCore
Common/CommonHelper.cs
10,564
C#
[TaskCategoryAttribute] // RVA: 0x156940 Offset: 0x156A41 VA: 0x156940 [TaskDescriptionAttribute] // RVA: 0x156940 Offset: 0x156A41 VA: 0x156940 public class CrossFadeQueued : Action // TypeDefIndex: 11419 { // Fields [TooltipAttribute] // RVA: 0x194440 Offset: 0x194541 VA: 0x194440 public SharedGameObject targetGameObject; // 0x50 [TooltipAttribute] // RVA: 0x194480 Offset: 0x194581 VA: 0x194480 public SharedString animationName; // 0x58 [TooltipAttribute] // RVA: 0x1944C0 Offset: 0x1945C1 VA: 0x1944C0 public float fadeLength; // 0x60 [TooltipAttribute] // RVA: 0x194500 Offset: 0x194601 VA: 0x194500 public QueueMode queue; // 0x64 [TooltipAttribute] // RVA: 0x194540 Offset: 0x194641 VA: 0x194540 public PlayMode playMode; // 0x68 private Animation animation; // 0x70 private GameObject prevGameObject; // 0x78 // Methods // RVA: 0x278EB70 Offset: 0x278EC71 VA: 0x278EB70 Slot: 5 public override void OnStart() { } // RVA: 0x278EC70 Offset: 0x278ED71 VA: 0x278EC70 Slot: 6 public override TaskStatus OnUpdate() { } // RVA: 0x278ED70 Offset: 0x278EE71 VA: 0x278ED70 Slot: 16 public override void OnReset() { } // RVA: 0x278EE00 Offset: 0x278EF01 VA: 0x278EE00 public void .ctor() { } }
35.941176
73
0.746318
[ "MIT" ]
SinsofSloth/RF5-global-metadata
BehaviorDesigner/Runtime/Tasks/Unity/UnityAnimation/CrossFadeQueued.cs
1,222
C#
using EarTrumpet.DataModel; using EarTrumpet.Interop; using EarTrumpet.Interop.Helpers; using System; using System.Collections; using System.Diagnostics; using System.Runtime.InteropServices; using System.Windows; using System.Windows.Controls; using System.Windows.Controls.Primitives; using System.Windows.Input; using System.Windows.Interop; using System.Windows.Threading; namespace EarTrumpet.UI.Helpers { public class ShellNotifyIcon { public event EventHandler<InputType> PrimaryInvoke; public event EventHandler<InputType> SecondaryInvoke; public event EventHandler<InputType> TertiaryInvoke; public event EventHandler<int> Scrolled; public IShellNotifyIconSource IconSource { get; private set; } public bool IsMouseOver { get; private set; } public bool IsVisible { get => _isVisible; set { if (value != _isVisible) { _isVisible = value; Update(); Trace.WriteLine($"ShellNotifyIcon IsVisible {_isVisible}"); } } } private const int WM_CALLBACKMOUSEMSG = User32.WM_USER + 1024; private readonly Win32Window _window; private readonly DispatcherTimer _invalidationTimer; private bool _isCreated; private bool _isVisible; private bool _isListeningForInput; private string _text; private RECT _iconLocation; private System.Drawing.Point _cursorPosition; private int _remainingTicks; public ShellNotifyIcon(IShellNotifyIconSource icon) { IconSource = icon; IconSource.Changed += (_) => Update(); _window = new Win32Window(); _window.Initialize(WndProc); _invalidationTimer = new DispatcherTimer(TimeSpan.FromMilliseconds(500), DispatcherPriority.Normal, (_, __) => OnDelayedIconCheckForUpdate(), Dispatcher.CurrentDispatcher); Themes.Manager.Current.PropertyChanged += (_, __) => ScheduleDelayedIconInvalidation(); Microsoft.Win32.SystemEvents.DisplaySettingsChanged += (_, __) => ScheduleDelayedIconInvalidation(); } public void SetFocus() { Trace.WriteLine("ShellNotifyIcon SetFocus"); var data = MakeData(); if (!Shell32.Shell_NotifyIconW(Shell32.NotifyIconMessage.NIM_SETFOCUS, ref data)) { Trace.WriteLine($"ShellNotifyIcon NIM_SETFOCUS Failed: {(uint)Marshal.GetLastWin32Error()}"); } } public void SetTooltip(string text) { _text = text; Update(); } private NOTIFYICONDATAW MakeData() { return new NOTIFYICONDATAW { cbSize = Marshal.SizeOf(typeof(NOTIFYICONDATAW)), hWnd = _window.Handle, uFlags = NotifyIconFlags.NIF_MESSAGE | NotifyIconFlags.NIF_ICON | NotifyIconFlags.NIF_TIP, uCallbackMessage = WM_CALLBACKMOUSEMSG, hIcon = IconSource.Current.Handle, szTip = _text }; } private void Update() { var data = MakeData(); if (_isVisible) { if (_isCreated) { if (!Shell32.Shell_NotifyIconW(Shell32.NotifyIconMessage.NIM_MODIFY, ref data)) { // Modification will fail when the shell restarts, or if message processing times out Trace.WriteLine($"ShellNotifyIcon Update NIM_MODIFY Failed: {(uint)Marshal.GetLastWin32Error()}"); _isCreated = false; Update(); } } else { if (!Shell32.Shell_NotifyIconW(Shell32.NotifyIconMessage.NIM_ADD, ref data)) { Trace.WriteLine($"ShellNotifyIcon Update NIM_ADD Failed {(uint)Marshal.GetLastWin32Error()}"); } _isCreated = true; data.uTimeoutOrVersion = Shell32.NOTIFYICON_VERSION_4; if (!Shell32.Shell_NotifyIconW(Shell32.NotifyIconMessage.NIM_SETVERSION, ref data)) { Trace.WriteLine($"ShellNotifyIcon Update NIM_SETVERSION Failed: {(uint)Marshal.GetLastWin32Error()}"); } } } else if (_isCreated) { if (!Shell32.Shell_NotifyIconW(Shell32.NotifyIconMessage.NIM_DELETE, ref data)) { Trace.WriteLine($"ShellNotifyIcon Update NIM_DELETE Failed: {(uint)Marshal.GetLastWin32Error()}"); } _isCreated = false; } } private void WndProc(System.Windows.Forms.Message msg) { if (msg.Msg == WM_CALLBACKMOUSEMSG) { CallbackMsgWndProc(msg); } else if (msg.Msg == Shell32.WM_TASKBARCREATED || (msg.Msg == User32.WM_SETTINGCHANGE && (int)msg.WParam == User32.SPI_SETWORKAREA)) { ScheduleDelayedIconInvalidation(); } else if (msg.Msg == User32.WM_INPUT && InputHelper.ProcessMouseInputMessage(msg.LParam, ref _cursorPosition, out int wheelDelta) && IsCursorWithinNotifyIconBounds() && wheelDelta != 0) { Scrolled?.Invoke(this, wheelDelta); } } private void CallbackMsgWndProc(System.Windows.Forms.Message msg) { switch ((int)msg.LParam) { case (int)Shell32.NotifyIconNotification.NIN_SELECT: case User32.WM_LBUTTONUP: PrimaryInvoke?.Invoke(this, InputType.Mouse); break; case (int)Shell32.NotifyIconNotification.NIN_KEYSELECT: PrimaryInvoke?.Invoke(this, InputType.Keyboard); break; case User32.WM_MBUTTONUP: TertiaryInvoke?.Invoke(this, InputType.Mouse); break; case User32.WM_CONTEXTMENU: SecondaryInvoke?.Invoke(this, InputType.Keyboard); break; case User32.WM_RBUTTONUP: SecondaryInvoke?.Invoke(this, InputType.Mouse); break; case User32.WM_MOUSEMOVE: OnNotifyIconMouseMove(); IconSource.CheckForUpdate(); break; } } private void OnNotifyIconMouseMove() { var id = new NOTIFYICONIDENTIFIER { cbSize = Marshal.SizeOf(typeof(NOTIFYICONIDENTIFIER)), hWnd = _window.Handle }; if (Shell32.Shell_NotifyIconGetRect(ref id, out RECT location) == 0) { _iconLocation = location; _cursorPosition = System.Windows.Forms.Cursor.Position; IsCursorWithinNotifyIconBounds(); } else { _iconLocation = default(RECT); } } private bool IsCursorWithinNotifyIconBounds() { bool isInBounds = _iconLocation.Contains(_cursorPosition); if (isInBounds) { if (!_isListeningForInput) { _isListeningForInput = true; InputHelper.RegisterForMouseInput(_window.Handle); } } else { if (_isListeningForInput) { _isListeningForInput = false; InputHelper.UnregisterForMouseInput(); } } bool isChanged = (IsMouseOver != isInBounds); IsMouseOver = isInBounds; if (isChanged) { IconSource.OnMouseOverChanged(IsMouseOver); } return isInBounds; } private void ScheduleDelayedIconInvalidation() { _remainingTicks = 10; _invalidationTimer.Start(); IconSource.CheckForUpdate(); } private void OnDelayedIconCheckForUpdate() { _remainingTicks--; if (_remainingTicks <= 0) { _invalidationTimer.Stop(); // Force a final update to protect us from the shell doing implicit work Update(); } IconSource.CheckForUpdate(); } public void ShowContextMenu(IEnumerable itemsSource) { Trace.WriteLine("ShellNotifyIcon ShowContextMenu"); var contextMenu = new ContextMenu { FlowDirection = SystemSettings.IsRTL ? FlowDirection.RightToLeft : FlowDirection.LeftToRight, StaysOpen = true, ItemsSource = itemsSource, }; Themes.Options.SetSource(contextMenu, Themes.Options.SourceKind.System); contextMenu.PreviewKeyDown += (_, e) => { if (e.Key == Key.Escape) { SetFocus(); } }; contextMenu.Opened += (_, __) => { Trace.WriteLine("ShellNotifyIcon ContextMenu.Opened"); // Workaround: The framework expects there to already be a WPF window open and thus fails to take focus. User32.SetForegroundWindow(((HwndSource)HwndSource.FromVisual(contextMenu)).Handle); contextMenu.Focus(); contextMenu.StaysOpen = false; // Disable only the exit animation. ((Popup)contextMenu.Parent).PopupAnimation = PopupAnimation.None; }; contextMenu.Closed += (_, __) => Trace.WriteLine("ShellNotifyIcon ContextMenu.Closed"); ; contextMenu.IsOpen = true; } } }
37.464539
185
0.524941
[ "MIT" ]
ADeltaX/EarTrumpet
EarTrumpet/UI/Helpers/ShellNotifyIcon.cs
10,286
C#
using CocoStudio.Core; using CocoStudio.Model.DataModel; using CocoStudio.Projects; using MonoDevelop.Core.Serialization; using System; namespace CocoStudio.Model { [DataModelExtension, DataInclude(typeof(ResourceData))] public class ResourceItemData : ResourceData, IDataModel, IDataConvert { private ResourceItemData() { } public ResourceItemData(string path) : base(path) { } public ResourceItemData(EnumResourceType type, string path) : base(type, path) { } public ResourceItemData(EnumResourceType type, string path, string plistFile) : base(type, path, plistFile) { } public object CreateViewModel() { return Services.ProjectOperations.CurrentResourceGroup.FindResourceItem(this); } public void SetData(object viewObject) { if (!(viewObject is ResourceItem)) { throw new ArgumentException("Only support ResourceFile type."); } ResourceItem resourceItem = viewObject as ResourceItem; ResourceData resourceData = resourceItem.GetResourceData(); base.Path = resourceData.Path; base.Type = resourceData.Type; base.Plist = resourceData.Plist; } internal void Update(ResourceData data) { base.Type = data.Type; base.Path = data.Path; base.Plist = data.Plist; } } }
23.296296
109
0.737679
[ "MIT" ]
gdbobu/CocoStudio2.0.6
CocoStudio.Model/CocoStudio.Model/ResourceItemData.cs
1,258
C#
// <auto-generated /> using DemoShop.UI.Data; using Microsoft.EntityFrameworkCore; using Microsoft.EntityFrameworkCore.Infrastructure; using Microsoft.EntityFrameworkCore.Metadata; using Microsoft.EntityFrameworkCore.Migrations; using Microsoft.EntityFrameworkCore.Storage; using Microsoft.EntityFrameworkCore.Storage.Internal; using System; namespace DemoShop.UI.Migrations { [DbContext(typeof(ShopDbContext))] [Migration("20180629072417_toDecimal")] partial class toDecimal { protected override void BuildTargetModel(ModelBuilder modelBuilder) { #pragma warning disable 612, 618 modelBuilder .HasAnnotation("ProductVersion", "2.0.3-rtm-10026") .HasAnnotation("SqlServer:ValueGenerationStrategy", SqlServerValueGenerationStrategy.IdentityColumn); modelBuilder.Entity("DemoShop.Core.Domain.Product", b => { b.Property<Guid>("ID") .ValueGeneratedOnAdd(); b.Property<string>("Name") .IsRequired() .HasMaxLength(255); b.Property<Guid>("ProductsCategoryID"); b.Property<Guid>("UnitID"); b.HasKey("ID"); b.HasIndex("ProductsCategoryID"); b.HasIndex("UnitID"); b.ToTable("Products"); }); modelBuilder.Entity("DemoShop.Core.Domain.ProductsCategory", b => { b.Property<Guid>("ID") .ValueGeneratedOnAdd(); b.Property<string>("Name") .IsRequired() .HasMaxLength(255); b.HasKey("ID"); b.ToTable("ProductsCategories"); }); modelBuilder.Entity("DemoShop.Core.Domain.PurchaseInvoice", b => { b.Property<Guid>("ID") .ValueGeneratedOnAdd(); b.Property<int>("Count"); b.Property<decimal>("Price"); b.Property<Guid>("ProductID"); b.Property<DateTime>("PurchaseDate"); b.HasKey("ID"); b.HasIndex("ProductID"); b.ToTable("PurchaseInvoices"); }); modelBuilder.Entity("DemoShop.Core.Domain.SalesInvoice", b => { b.Property<Guid>("ID") .ValueGeneratedOnAdd(); b.Property<int>("Count"); b.Property<decimal>("Price"); b.Property<Guid>("ProductID"); b.Property<DateTime>("PurchaseDate"); b.HasKey("ID"); b.HasIndex("ProductID"); b.ToTable("SalesInvoices"); }); modelBuilder.Entity("DemoShop.Core.Domain.ShopModule", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<string>("Name") .IsRequired(); b.HasKey("Id"); b.ToTable("Modules"); }); modelBuilder.Entity("DemoShop.Core.Domain.ShopRole", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Description"); b.Property<Guid>("ModuleID"); b.Property<string>("Name") .HasMaxLength(256); b.Property<string>("NormalizedName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("ModuleID"); b.HasIndex("NormalizedName") .IsUnique() .HasName("RoleNameIndex") .HasFilter("[NormalizedName] IS NOT NULL"); b.ToTable("AspNetRoles"); }); modelBuilder.Entity("DemoShop.Core.Domain.ShopUser", b => { b.Property<Guid>("Id") .ValueGeneratedOnAdd(); b.Property<int>("AccessFailedCount"); b.Property<string>("ConcurrencyStamp") .IsConcurrencyToken(); b.Property<string>("Email") .HasMaxLength(256); b.Property<bool>("EmailConfirmed"); b.Property<string>("FullName"); b.Property<bool>("LockoutEnabled"); b.Property<DateTimeOffset?>("LockoutEnd"); b.Property<string>("NormalizedEmail") .HasMaxLength(256); b.Property<string>("NormalizedUserName") .HasMaxLength(256); b.Property<string>("PasswordHash"); b.Property<string>("PhoneNumber"); b.Property<bool>("PhoneNumberConfirmed"); b.Property<string>("SecurityStamp"); b.Property<bool>("TwoFactorEnabled"); b.Property<string>("UserName") .HasMaxLength(256); b.HasKey("Id"); b.HasIndex("NormalizedEmail") .HasName("EmailIndex"); b.HasIndex("NormalizedUserName") .IsUnique() .HasName("UserNameIndex") .HasFilter("[NormalizedUserName] IS NOT NULL"); b.ToTable("AspNetUsers"); }); modelBuilder.Entity("DemoShop.Core.Domain.Unit", b => { b.Property<Guid>("ID") .ValueGeneratedOnAdd(); b.Property<string>("Name") .IsRequired() .HasMaxLength(255); b.Property<string>("ShortName") .IsRequired() .HasMaxLength(20); b.HasKey("ID"); b.HasIndex("Name") .IsUnique(); b.ToTable("Units"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<Guid>("RoleId"); b.HasKey("Id"); b.HasIndex("RoleId"); b.ToTable("AspNetRoleClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b => { b.Property<int>("Id") .ValueGeneratedOnAdd(); b.Property<string>("ClaimType"); b.Property<string>("ClaimValue"); b.Property<Guid>("UserId"); b.HasKey("Id"); b.HasIndex("UserId"); b.ToTable("AspNetUserClaims"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b => { b.Property<string>("LoginProvider"); b.Property<string>("ProviderKey"); b.Property<string>("ProviderDisplayName"); b.Property<Guid>("UserId"); b.HasKey("LoginProvider", "ProviderKey"); b.HasIndex("UserId"); b.ToTable("AspNetUserLogins"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b => { b.Property<Guid>("UserId"); b.Property<Guid>("RoleId"); b.HasKey("UserId", "RoleId"); b.HasIndex("RoleId"); b.ToTable("AspNetUserRoles"); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b => { b.Property<Guid>("UserId"); b.Property<string>("LoginProvider"); b.Property<string>("Name"); b.Property<string>("Value"); b.HasKey("UserId", "LoginProvider", "Name"); b.ToTable("AspNetUserTokens"); }); modelBuilder.Entity("DemoShop.Core.Domain.Product", b => { b.HasOne("DemoShop.Core.Domain.ProductsCategory", "ProductsCategory") .WithMany("Products") .HasForeignKey("ProductsCategoryID") .OnDelete(DeleteBehavior.Cascade); b.HasOne("DemoShop.Core.Domain.Unit", "Unit") .WithMany("Products") .HasForeignKey("UnitID") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("DemoShop.Core.Domain.PurchaseInvoice", b => { b.HasOne("DemoShop.Core.Domain.Product", "Product") .WithMany() .HasForeignKey("ProductID") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("DemoShop.Core.Domain.SalesInvoice", b => { b.HasOne("DemoShop.Core.Domain.Product", "Product") .WithMany() .HasForeignKey("ProductID") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("DemoShop.Core.Domain.ShopRole", b => { b.HasOne("DemoShop.Core.Domain.ShopModule", "Module") .WithMany() .HasForeignKey("ModuleID") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityRoleClaim<System.Guid>", b => { b.HasOne("DemoShop.Core.Domain.ShopRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserClaim<System.Guid>", b => { b.HasOne("DemoShop.Core.Domain.ShopUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserLogin<System.Guid>", b => { b.HasOne("DemoShop.Core.Domain.ShopUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserRole<System.Guid>", b => { b.HasOne("DemoShop.Core.Domain.ShopRole") .WithMany() .HasForeignKey("RoleId") .OnDelete(DeleteBehavior.Cascade); b.HasOne("DemoShop.Core.Domain.ShopUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); modelBuilder.Entity("Microsoft.AspNetCore.Identity.IdentityUserToken<System.Guid>", b => { b.HasOne("DemoShop.Core.Domain.ShopUser") .WithMany() .HasForeignKey("UserId") .OnDelete(DeleteBehavior.Cascade); }); #pragma warning restore 612, 618 } } }
32.775457
117
0.450809
[ "Apache-2.0" ]
pprometey/DemoShop
DemoShop/Migrations/20180629072417_toDecimal.Designer.cs
12,555
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.Collections.Generic; using RuntimeTypeInfo = System.Reflection.TypeLoading.RoType; namespace System.Reflection.Runtime.BindingFlagSupport { /// <summary> /// Policies for fields. /// </summary> internal sealed class FieldPolicies : MemberPolicies<FieldInfo> { public sealed override IEnumerable<FieldInfo> GetDeclaredMembers(TypeInfo typeInfo) { return typeInfo.DeclaredFields; } public sealed override IEnumerable<FieldInfo> CoreGetDeclaredMembers(RuntimeTypeInfo type, NameFilter? filter, RuntimeTypeInfo reflectedType) { return type.GetFieldsCore(filter, reflectedType); } public sealed override bool AlwaysTreatAsDeclaredOnly => false; public sealed override void GetMemberAttributes(FieldInfo member, out MethodAttributes visibility, out bool isStatic, out bool isVirtual, out bool isNewSlot) { FieldAttributes fieldAttributes = member.Attributes; visibility = (MethodAttributes)(fieldAttributes & FieldAttributes.FieldAccessMask); isStatic = (0 != (fieldAttributes & FieldAttributes.Static)); isVirtual = false; isNewSlot = false; } public sealed override bool ImplicitlyOverrides(FieldInfo? baseMember, FieldInfo? derivedMember) => false; public sealed override bool IsSuppressedByMoreDerivedMember(FieldInfo member, FieldInfo[] priorMembers, int startIndex, int endIndex) { return false; } public sealed override bool OkToIgnoreAmbiguity(FieldInfo m1, FieldInfo m2) { return true; // Unlike most member types, Field ambiguities are tolerated as long as they're defined in different classes. } } }
40.229167
165
0.698084
[ "MIT" ]
2m0nd/runtime
src/libraries/System.Reflection.MetadataLoadContext/src/System/Reflection/Runtime/BindingFlagSupport/FieldPolicies.cs
1,931
C#
// Copyright (c) Microsoft Corporation. All rights reserved. // Licensed under the MIT License. // <auto-generated/> #nullable disable using System; using System.Collections.Generic; using Azure.AI.Language.Conversations.Models; using Azure.Core; namespace Azure.AI.Language.Conversations { /// <summary> The JobStateAutoGenerated. </summary> public partial class JobStateAutoGenerated { /// <summary> Initializes a new instance of JobStateAutoGenerated. </summary> /// <param name="createdDateTime"></param> /// <param name="jobId"></param> /// <param name="lastUpdateDateTime"></param> /// <param name="status"></param> internal JobStateAutoGenerated(DateTimeOffset createdDateTime, Guid jobId, DateTimeOffset lastUpdateDateTime, JobState status) { CreatedDateTime = createdDateTime; JobId = jobId; LastUpdateDateTime = lastUpdateDateTime; Status = status; Errors = new ChangeTrackingList<GeneratedError>(); } /// <summary> Initializes a new instance of JobStateAutoGenerated. </summary> /// <param name="displayName"></param> /// <param name="createdDateTime"></param> /// <param name="expirationDateTime"></param> /// <param name="jobId"></param> /// <param name="lastUpdateDateTime"></param> /// <param name="status"></param> /// <param name="errors"></param> /// <param name="nextLink"></param> internal JobStateAutoGenerated(string displayName, DateTimeOffset createdDateTime, DateTimeOffset? expirationDateTime, Guid jobId, DateTimeOffset lastUpdateDateTime, JobState status, IReadOnlyList<GeneratedError> errors, string nextLink) { DisplayName = displayName; CreatedDateTime = createdDateTime; ExpirationDateTime = expirationDateTime; JobId = jobId; LastUpdateDateTime = lastUpdateDateTime; Status = status; Errors = errors; NextLink = nextLink; } /// <summary> Gets the display name. </summary> public string DisplayName { get; } /// <summary> Gets the created date time. </summary> public DateTimeOffset CreatedDateTime { get; } /// <summary> Gets the expiration date time. </summary> public DateTimeOffset? ExpirationDateTime { get; } /// <summary> Gets the job id. </summary> public Guid JobId { get; } /// <summary> Gets the last update date time. </summary> public DateTimeOffset LastUpdateDateTime { get; } /// <summary> Gets the status. </summary> public JobState Status { get; } /// <summary> Gets the errors. </summary> public IReadOnlyList<GeneratedError> Errors { get; } /// <summary> Gets the next link. </summary> public string NextLink { get; } } }
41.394366
245
0.632528
[ "MIT" ]
damodaravadhani/azure-sdk-for-net
sdk/cognitivelanguage/Azure.AI.Language.Conversations/src/Models/GeneratedModels/JobStateAutoGenerated.cs
2,939
C#
#region MIT license // // MIT license // // Copyright (c) 2007-2008 Jiri Moudry, Pascal Craponne // // Permission is hereby granted, free of charge, to any person obtaining a copy // of this software and associated documentation files (the "Software"), to deal // in the Software without restriction, including without limitation the rights // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell // copies of the Software, and to permit persons to whom the Software is // furnished to do so, subject to the following conditions: // // The above copyright notice and this permission notice shall be included in // all copies or substantial portions of the Software. // // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN // THE SOFTWARE. // #endregion using System; using System.Collections.Generic; using System.Linq; using System.Linq.Expressions; using DbLinq.Data.Linq.Sugar.Expressions; namespace DbLinq.Data.Linq.Sugar.ExpressionMutator.Implementation { internal class BinaryExpressionMutator : IMutableExpression { protected BinaryExpression BinaryExpression { get; private set; } public Expression Mutate(IList<Expression> operands) { switch (BinaryExpression.NodeType) { case ExpressionType.Add: if (BinaryExpression.Method != null) return Expression.Add(operands[0], operands[1], BinaryExpression.Method); return Expression.Add(operands[0], operands[1]); case ExpressionType.AddChecked: if (BinaryExpression.Method != null) return Expression.AddChecked(operands[0], operands[1], BinaryExpression.Method); return Expression.AddChecked(operands[0], operands[1]); case ExpressionType.Divide: if (BinaryExpression.Method != null) return Expression.Divide(operands[0], operands[1], BinaryExpression.Method); return Expression.Divide(operands[0], operands[1]); case ExpressionType.Modulo: if (BinaryExpression.Method != null) return Expression.Modulo(operands[0], operands[1], BinaryExpression.Method); return Expression.Modulo(operands[0], operands[1]); case ExpressionType.Multiply: if (BinaryExpression.Method != null) return Expression.Multiply(operands[0], operands[1], BinaryExpression.Method); return Expression.Multiply(operands[0], operands[1]); case ExpressionType.MultiplyChecked: if (BinaryExpression.Method != null) return Expression.MultiplyChecked(operands[0], operands[1], BinaryExpression.Method); return Expression.MultiplyChecked(operands[0], operands[1]); case ExpressionType.Power: if (BinaryExpression.Method != null) return Expression.Power(operands[0], operands[1], BinaryExpression.Method); return Expression.Power(operands[0], operands[1]); case ExpressionType.Subtract: if (BinaryExpression.Method != null) return Expression.Subtract(operands[0], operands[1], BinaryExpression.Method); return Expression.Subtract(operands[0], operands[1]); case ExpressionType.SubtractChecked: if (BinaryExpression.Method != null) return Expression.SubtractChecked(operands[0], operands[1], BinaryExpression.Method); return Expression.SubtractChecked(operands[0], operands[1]); case ExpressionType.And: if (BinaryExpression.Method != null) return Expression.And(operands[0], operands[1], BinaryExpression.Method); return Expression.And(operands[0], operands[1]); case ExpressionType.Or: if (BinaryExpression.Method != null) return Expression.Or(operands[0], operands[1], BinaryExpression.Method); return Expression.Or(operands[0], operands[1]); case ExpressionType.ExclusiveOr: if (BinaryExpression.Method != null) return Expression.ExclusiveOr(operands[0], operands[1], BinaryExpression.Method); return Expression.ExclusiveOr(operands[0], operands[1]); case ExpressionType.LeftShift: if (BinaryExpression.Method != null) return Expression.LeftShift(operands[0], operands[1], BinaryExpression.Method); return Expression.LeftShift(operands[0], operands[1]); case ExpressionType.RightShift: if (BinaryExpression.Method != null) return Expression.RightShift(operands[0], operands[1], BinaryExpression.Method); return Expression.RightShift(operands[0], operands[1]); case ExpressionType.AndAlso: if (BinaryExpression.Method != null) return Expression.AndAlso(operands[0], operands[1], BinaryExpression.Method); return Expression.AndAlso(operands[0], operands[1]); case ExpressionType.OrElse: if (BinaryExpression.Method != null) return Expression.OrElse(operands[0], operands[1], BinaryExpression.Method); return Expression.OrElse(operands[0], operands[1]); case ExpressionType.Equal: if (BinaryExpression.Method != null) return Expression.Equal(operands[0], operands[1], BinaryExpression.IsLiftedToNull, BinaryExpression.Method); return Expression.Equal(operands[0], operands[1]); case ExpressionType.NotEqual: if (BinaryExpression.Method != null) return Expression.NotEqual(operands[0], operands[1], BinaryExpression.IsLiftedToNull, BinaryExpression.Method); return Expression.NotEqual(operands[0], operands[1]); case ExpressionType.GreaterThanOrEqual: if (BinaryExpression.Method != null) return Expression.GreaterThanOrEqual(operands[0], operands[1], BinaryExpression.IsLiftedToNull, BinaryExpression.Method); return Expression.GreaterThanOrEqual(operands[0], operands[1]); case ExpressionType.GreaterThan: if (BinaryExpression.Method != null) return Expression.GreaterThan(operands[0], operands[1], BinaryExpression.IsLiftedToNull, BinaryExpression.Method); return Expression.GreaterThan(operands[0], operands[1]); case ExpressionType.LessThan: if (BinaryExpression.Method != null) return Expression.LessThan(operands[0], operands[1], BinaryExpression.IsLiftedToNull, BinaryExpression.Method); return Expression.LessThan(operands[0], operands[1]); case ExpressionType.LessThanOrEqual: if (BinaryExpression.Method != null) return Expression.LessThanOrEqual(operands[0], operands[1], BinaryExpression.IsLiftedToNull, BinaryExpression.Method); return Expression.LessThanOrEqual(operands[0], operands[1]); case ExpressionType.Coalesce: if (BinaryExpression.Conversion != null) return Expression.Coalesce(operands[0], operands[1], BinaryExpression.Conversion); return Expression.Coalesce(operands[0], operands[1]); case ExpressionType.Assign: return Expression.Assign(operands[0], operands[1]); case ExpressionType.ArrayIndex: return Expression.ArrayIndex(operands[0], operands.Skip(1)); } throw new Exception(); } public IEnumerable<Expression> Operands { get { yield return BinaryExpression.Left; yield return BinaryExpression.Right; } } public BinaryExpressionMutator(BinaryExpression expression) { BinaryExpression = expression; } } }
49.935135
146
0.596125
[ "Apache-2.0" ]
antiufo/mono
mcs/class/System.Data.Linq/src/DbLinq/Data/Linq/Sugar/ExpressionMutator/Implementation/BinaryExpressionMutator.cs
9,240
C#
//------------------------------------------------------------ // Copyright (c) Microsoft Corporation. All rights reserved. //------------------------------------------------------------ namespace Microsoft.Azure.Cosmos { using System; using System.Collections.Generic; using System.Diagnostics; using System.Linq; using System.Reflection; using System.Text; using Microsoft.Azure.Documents; using Microsoft.VisualStudio.TestTools.UnitTesting; [TestClass] public class DirectContractTests { [TestMethod] public void TestInteropTest() { try { CosmosClient client = new CosmosClient(connectionString: null); Assert.Fail(); } catch(ArgumentNullException) { } Assert.IsTrue(ServiceInteropWrapper.AssembliesExist.Value); string configJson = "{}"; IntPtr provider; uint result = ServiceInteropWrapper.CreateServiceProvider(configJson, out provider); } [TestMethod] public void PublicDirectTypes() { Assembly directAssembly = typeof(IStoreClient).Assembly; Assert.IsTrue(directAssembly.FullName.StartsWith("Microsoft.Azure.Cosmos.Direct", System.StringComparison.Ordinal), directAssembly.FullName); Type[] exportedTypes = directAssembly.GetExportedTypes(); Assert.AreEqual(1, exportedTypes.Length, string.Join(",", exportedTypes.Select(e => e.Name).ToArray())); Assert.AreEqual("Microsoft.Azure.Cosmos.CosmosRegions", exportedTypes.Select(e => e.FullName).Single()); } [TestMethod] public void RMContractTest() { Trace.TraceInformation($"{Documents.RMResources.PartitionKeyAndEffectivePartitionKeyBothSpecified} " + $"{Documents.RMResources.UnexpectedPartitionKeyRangeId}"); } [TestMethod] public void CustomJsonReaderTest() { // Contract validation that JsonReaderFactory is present DocumentServiceResponse.JsonReaderFactory = (stream) => null; } } }
34.3125
153
0.595173
[ "MIT" ]
ElasticCoder/azure-cosmos-dotnet-v3
Microsoft.Azure.Cosmos/tests/Microsoft.Azure.Cosmos.Tests/DirectContractTests.cs
2,198
C#
using System; public enum AchievementTargetId { NONE, UNIT, WARBAND, PROFILE, MAX_VALUE }
8.818182
31
0.731959
[ "CC0-1.0" ]
FreyaFreed/mordheim
Assembly-CSharp/AchievementTargetId.cs
99
C#
using System; using System.Collections.Generic; using System.ComponentModel.DataAnnotations; using System.ComponentModel.DataAnnotations.Schema; using System.Linq; using System.Threading.Tasks; namespace Anf.ChannelModel.Entity { public class AnfBookshelf { [Key] public long Id { get; set; } [MaxLength(64)] public string Name { get; set; } [ForeignKey(nameof(User))] public long UserId { get; set; } public bool Like { get; set; } [ForeignKey(nameof(LinkBookshelf))] public long? LinkId { get; set; } [Required] public DateTime CreateTime { get; set; } public virtual AnfUser User { get; set; } public AnfBookshelf LinkBookshelf { get; set; } public virtual ICollection<AnfBookshelfItem> Items { get; set; } } }
23.555556
72
0.639151
[ "BSD-3-Clause" ]
Cricle/Anf
Platforms/Anf.ChannelModel/Entity/AnfBookshelf.cs
850
C#
/* * Copyright 2012-2020 The Pkcs11Interop Project * * 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. */ /* * Written for the Pkcs11Interop project by: * Jaroslav IMRICH <jimrich@jimrich.sk> */ using System; using Net.Pkcs11Interop.Common; using Net.Pkcs11Interop.HighLevelAPI.MechanismParams; using Net.Pkcs11Interop.LowLevelAPI40.MechanismParams; // Note: Code in this file is generated automatically. namespace Net.Pkcs11Interop.HighLevelAPI40.MechanismParams { /// <summary> /// Information about the random data of a client and a server in a WTLS context /// </summary> public class CkWtlsRandomData : ICkWtlsRandomData { /// <summary> /// Flag indicating whether instance has been disposed /// </summary> private bool _disposed = false; /// <summary> /// Low level mechanism parameters /// </summary> private CK_WTLS_RANDOM_DATA _lowLevelStruct = new CK_WTLS_RANDOM_DATA(); /// <summary> /// Initializes a new instance of the CkWtlsRandomData class. /// </summary> /// <param name='clientRandom'>Client's random data</param> /// <param name='serverRandom'>Server's random data</param> public CkWtlsRandomData(byte[] clientRandom, byte[] serverRandom) { _lowLevelStruct.ClientRandom = IntPtr.Zero; _lowLevelStruct.ClientRandomLen = 0; _lowLevelStruct.ServerRandom = IntPtr.Zero; _lowLevelStruct.ServerRandomLen = 0; if (clientRandom != null) { _lowLevelStruct.ClientRandom = UnmanagedMemory.Allocate(clientRandom.Length); UnmanagedMemory.Write(_lowLevelStruct.ClientRandom, clientRandom); _lowLevelStruct.ClientRandomLen = ConvertUtils.UInt32FromInt32(clientRandom.Length); } if (serverRandom != null) { _lowLevelStruct.ServerRandom = UnmanagedMemory.Allocate(serverRandom.Length); UnmanagedMemory.Write(_lowLevelStruct.ServerRandom, serverRandom); _lowLevelStruct.ServerRandomLen = ConvertUtils.UInt32FromInt32(serverRandom.Length); } } #region IMechanismParams /// <summary> /// Returns managed object that can be marshaled to an unmanaged block of memory /// </summary> /// <returns>A managed object holding the data to be marshaled. This object must be an instance of a formatted class.</returns> public object ToMarshalableStructure() { if (this._disposed) throw new ObjectDisposedException(this.GetType().FullName); return _lowLevelStruct; } #endregion #region IDisposable /// <summary> /// Disposes object /// </summary> public void Dispose() { Dispose(true); GC.SuppressFinalize(this); } /// <summary> /// Disposes object /// </summary> /// <param name="disposing">Flag indicating whether managed resources should be disposed</param> protected virtual void Dispose(bool disposing) { if (!this._disposed) { if (disposing) { // Dispose managed objects } // Dispose unmanaged objects UnmanagedMemory.Free(ref _lowLevelStruct.ClientRandom); _lowLevelStruct.ClientRandomLen = 0; UnmanagedMemory.Free(ref _lowLevelStruct.ServerRandom); _lowLevelStruct.ServerRandomLen = 0; _disposed = true; } } /// <summary> /// Class destructor that disposes object if caller forgot to do so /// </summary> ~CkWtlsRandomData() { Dispose(false); } #endregion } }
34.455224
135
0.595841
[ "Apache-2.0" ]
ConnectionMaster/Pkcs11Interop
src/Pkcs11Interop/HighLevelAPI40/MechanismParams/CkWtlsRandomData.cs
4,617
C#
 using Microsoft.CodeAnalysis; using Microsoft.CodeAnalysis.CSharp; using Microsoft.CodeAnalysis.CSharp.Syntax; using System.Collections.Generic; using System.Linq; namespace UdonSharp.Compiler { public class UdonSharpSyntaxWalker : CSharpSyntaxWalker { public enum UdonSharpSyntaxWalkerDepth { Class, ClassDefinitions, ClassMemberBodies, } public ASTVisitorContext visitorContext; protected Stack<string> namespaceStack = new Stack<string>(); UdonSharpSyntaxWalkerDepth syntaxWalkerDepth; public UdonSharpSyntaxWalker(ResolverContext resolver, SymbolTable rootTable, LabelTable labelTable, ClassDebugInfo classDebugInfo = null) : base(SyntaxWalkerDepth.Node) { syntaxWalkerDepth = UdonSharpSyntaxWalkerDepth.ClassMemberBodies; visitorContext = new ASTVisitorContext(resolver, rootTable, labelTable, classDebugInfo); } public UdonSharpSyntaxWalker(UdonSharpSyntaxWalkerDepth depth, ResolverContext resolver, SymbolTable rootTable, LabelTable labelTable, ClassDebugInfo classDebugInfo = null) : base(SyntaxWalkerDepth.Node) { syntaxWalkerDepth = depth; visitorContext = new ASTVisitorContext(resolver, rootTable, labelTable, classDebugInfo); } protected void UpdateSyntaxNode(SyntaxNode node) { visitorContext.currentNode = node; if (visitorContext.debugInfo != null && !visitorContext.pauseDebugInfoWrite) visitorContext.debugInfo.UpdateSyntaxNode(node); } public override void DefaultVisit(SyntaxNode node) { UpdateSyntaxNode(node); base.DefaultVisit(node); } public override void VisitNamespaceDeclaration(NamespaceDeclarationSyntax node) { UpdateSyntaxNode(node); List<string> namespaces = new List<string>(); SyntaxToken lastToken = node.Name.GetLastToken(); SyntaxToken currentToken = node.Name.GetFirstToken(); while (currentToken != null) { if (currentToken.Text != ".") namespaces.Add(currentToken.Text); if (currentToken == lastToken) break; currentToken = currentToken.GetNextToken(); } foreach (string currentNamespace in namespaces) namespaceStack.Push(currentNamespace); foreach (UsingDirectiveSyntax usingDirective in node.Usings) Visit(usingDirective); foreach (MemberDeclarationSyntax memberDeclaration in node.Members) Visit(memberDeclaration); for (int i = 0; i < namespaces.Count; ++i) namespaceStack.Pop(); } public override void VisitClassDeclaration(ClassDeclarationSyntax node) { UpdateSyntaxNode(node); using (ExpressionCaptureScope classTypeCapture = new ExpressionCaptureScope(visitorContext, null)) { foreach (string namespaceToken in namespaceStack.Reverse()) { classTypeCapture.ResolveAccessToken(namespaceToken); if (classTypeCapture.IsNamespace()) visitorContext.resolverContext.AddNamespace(classTypeCapture.captureNamespace); } classTypeCapture.ResolveAccessToken(node.Identifier.ValueText); if (!classTypeCapture.IsType()) throw new System.Exception($"User type {node.Identifier.ValueText} could not be found"); } if (syntaxWalkerDepth == UdonSharpSyntaxWalkerDepth.ClassDefinitions || syntaxWalkerDepth == UdonSharpSyntaxWalkerDepth.ClassMemberBodies) base.VisitClassDeclaration(node); } public override void VisitVariableDeclaration(VariableDeclarationSyntax node) { if (syntaxWalkerDepth == UdonSharpSyntaxWalkerDepth.ClassMemberBodies) base.VisitVariableDeclaration(node); } public override void VisitMethodDeclaration(MethodDeclarationSyntax node) { if (syntaxWalkerDepth == UdonSharpSyntaxWalkerDepth.ClassMemberBodies) base.VisitMethodDeclaration(node); } public override void VisitPropertyDeclaration(PropertyDeclarationSyntax node) { if (syntaxWalkerDepth == UdonSharpSyntaxWalkerDepth.ClassMemberBodies) base.VisitPropertyDeclaration(node); } public override void VisitArrayType(ArrayTypeSyntax node) { UpdateSyntaxNode(node); using (ExpressionCaptureScope arrayTypeCaptureScope = new ExpressionCaptureScope(visitorContext, visitorContext.topCaptureScope)) { Visit(node.ElementType); for (int i = 0; i < node.RankSpecifiers.Count; ++i) arrayTypeCaptureScope.MakeArrayType(); } } public override void VisitArrayRankSpecifier(ArrayRankSpecifierSyntax node) { UpdateSyntaxNode(node); foreach (ExpressionSyntax size in node.Sizes) Visit(size); } // Boilerplate to have resolution work correctly public override void VisitUsingDirective(UsingDirectiveSyntax node) { UpdateSyntaxNode(node); using (ExpressionCaptureScope namespaceCapture = new ExpressionCaptureScope(visitorContext, null)) { if (node.StaticKeyword.IsKind(SyntaxKind.StaticKeyword)) throw new System.NotSupportedException("UdonSharp does not yet support static using statements"); if (node.Alias.IsKind(SyntaxKind.AliasKeyword)) throw new System.NotSupportedException("UdonSharp does not yet support namespace aliases"); Visit(node.Name); if (!namespaceCapture.IsNamespace()) throw new System.Exception("Did not capture a valid namespace"); visitorContext.resolverContext.AddNamespace(namespaceCapture.captureNamespace); } } public override void VisitIdentifierName(IdentifierNameSyntax node) { UpdateSyntaxNode(node); if (visitorContext.topCaptureScope != null) visitorContext.topCaptureScope.ResolveAccessToken(node.Identifier.ValueText); } public override void VisitPredefinedType(PredefinedTypeSyntax node) { UpdateSyntaxNode(node); if (visitorContext.topCaptureScope != null) visitorContext.topCaptureScope.ResolveAccessToken(node.Keyword.ValueText); } } }
37.819672
180
0.636758
[ "MIT" ]
PhaxeNor/UdonSharp
Assets/UdonSharp/Editor/UdonSharpSyntaxWalker.cs
6,923
C#
/*<FILE_LICENSE> * Azos (A to Z Application Operating System) Framework * The A to Z Foundation (a.k.a. Azist) licenses this file to you under the MIT license. * See the LICENSE file in the project root for more information. </FILE_LICENSE>*/ using System; using System.Collections.Generic; using System.Runtime.Serialization; using Azos.IO; namespace Azos.Serialization.Slim { internal class _ISerializableFixup { public object Instance; public SerializationInfo Info; } internal class _OnDeserializedCallback { public object Instance; public TypeDescriptor Descriptor; } internal class RefPool { public const int POOL_CAPACITY = 1024; public const int LARGE_TRIM_THRESHOLD = 16 * 1024; public void Acquire(SerializationOperation mode) { m_Mode = mode; } public void Release() { if (m_Mode==SerializationOperation.Serializing) { m_List.Clear(); m_Dict.Clear(); } else//Deserialization { m_List.Clear(); m_Fixups.Clear(); m_OnDeserializedCallbacks.Clear(); } } private SerializationOperation m_Mode; private QuickRefList m_List = new QuickRefList(POOL_CAPACITY); private Dictionary<object, int> m_Dict = new Dictionary<object,int>(POOL_CAPACITY, Collections.ReferenceEqualityComparer<object>.Instance); private List<_ISerializableFixup> m_Fixups = new List<_ISerializableFixup>(); private List<_OnDeserializedCallback> m_OnDeserializedCallbacks = new List<_OnDeserializedCallback>(); public int Count { get { return m_List.Count;} } public List<_ISerializableFixup> Fixups { get { return m_Fixups; }} public List<_OnDeserializedCallback> OnDeserializedCallbacks { get { return m_OnDeserializedCallbacks; }} public object this[int i] { get { return m_List[i]; } } public bool Add(object reference) { if (m_Mode==SerializationOperation.Serializing) { bool added; getIndex(reference, out added); return added; } else { if (reference==null) return false; m_List.Add(reference); return true; } } public void AddISerializableFixup(object instance, SerializationInfo info) { Debug.Assert(m_Mode == SerializationOperation.Deserializing, "AddISerializableFixup() called while serializing", DebugAction.Throw); m_Fixups.Add( new _ISerializableFixup{ Instance = instance, Info = info } ); } public void AddOnDeserializedCallback(object instance, TypeDescriptor descriptor) { Debug.Assert(m_Mode == SerializationOperation.Deserializing, "AddOnDeserializedCallback() called while serializing", DebugAction.Throw); m_OnDeserializedCallbacks.Add( new _OnDeserializedCallback{ Instance = instance, Descriptor = descriptor } ); } /// <summary> /// Emits MetaHandle that contains type handle for reference handle only when this referenced is added to pool for the first time. /// Emits inlined string for strings and inlined value types for boxed objects. /// Emits additional array dimensions info for array refernces who's types are emitted for the first time /// </summary> public MetaHandle GetHandle(object reference, TypeRegistry treg, SlimFormat format, out Type type) { Debug.Assert(m_Mode == SerializationOperation.Serializing, "GetHandle() called while deserializing", DebugAction.Throw); if (reference==null) { type = null; return new MetaHandle(0); } type = reference.GetType(); if (type == typeof(string)) { return MetaHandle.InlineString(reference as string); } if (reference is Type) { var thandle = treg.GetTypeHandle(reference as Type); return MetaHandle.InlineTypeValue(thandle); } if (type.IsValueType) { var vth = treg.GetTypeHandle(type); return MetaHandle.InlineValueType(vth); } bool added; uint handle = (uint)getIndex(reference, out added); if (added) { var th = treg.GetTypeHandle(type); if (format.IsRefTypeSupported(type))//20150305 Refhandle inline return MetaHandle.InlineRefType(th); if (type.IsArray)//write array header like so: "System.int[,]|0~10,0~12" or "$3|0~10,0~12" { //DKh 20130712 Removed repetitive code that was refactored into Arrays class var arr = (Array)reference; th = new VarIntStr( Arrays.ArrayToDescriptor(arr, type, th) ); } return new MetaHandle(handle, th); } return new MetaHandle(handle); } /// <summary> /// Returns object reference for supplied metahandle /// </summary> public object HandleToReference(MetaHandle handle, TypeRegistry treg, SlimFormat format, SlimReader reader) { Debug.Assert(m_Mode == SerializationOperation.Deserializing, "HandleToReference() called while serializing", DebugAction.Throw); if (handle.IsInlinedString) return handle.Metadata.Value.StringValue; if (handle.IsInlinedTypeValue) { var tref = treg[ handle.Metadata.Value ];//adding this type to registry if it is not there yet return tref; } if (handle.IsInlinedRefType) { var tref = treg[ handle.Metadata.Value ];//adding this type to registry if it is not there yet var ra = format.GetReadActionForRefType(tref); if (ra!=null) { var inst = ra(reader); m_List.Add(inst); return inst; } else throw new SlimDeserializationException("Internal error HandleToReference: no read action for ref type, but ref mhandle is inlined"); } int idx = (int)handle.Handle; if (idx<m_List.Count) return m_List[idx]; if (!handle.Metadata.HasValue) throw new SlimDeserializationException(StringConsts.SLIM_HNDLTOREF_MISSING_TYPE_NAME_ERROR + handle.ToString()); Type type; var metadata = handle.Metadata.Value; if (metadata.StringValue!=null)//need to search for possible array descriptor { var ip = metadata.StringValue.IndexOf('|');//array descriptor start if (ip>0) { var tname = metadata.StringValue.Substring(0, ip); if (TypeRegistry.IsNullHandle(tname)) return null; type = treg[ tname ]; } else { if (TypeRegistry.IsNullHandle(metadata)) return null; type = treg[ metadata ]; } } else { if (TypeRegistry.IsNullHandle(metadata)) return null; type = treg[ metadata ]; } object instance = null; if (type.IsArray) //DKh 20130712 Removed repetitive code that was refactored into Arrays class instance = Arrays.DescriptorToArray(metadata.StringValue, type); else //20130715 DKh instance = SerializationUtils.MakeNewObjectInstance(type); m_List.Add(instance); return instance; } private int getIndex(object reference, out bool added) { const int MAX_LINEAR_SEARCH = 8;//linear search is faster than dict lookup added = false; if (reference==null) return 0; int idx = -1; var cnt = m_List.Count; if (cnt<MAX_LINEAR_SEARCH) { for(var i=1; i<cnt; i++)//start form 1, skip NULL[0] if (object.ReferenceEquals(m_List[i], reference)) return i; } else if (m_Dict.TryGetValue(reference, out idx)) return idx; added = true; m_List.Add(reference); cnt = m_List.Count; idx = cnt - 1; if (cnt<MAX_LINEAR_SEARCH) return idx; if (cnt==MAX_LINEAR_SEARCH) {//upgrade LIST->DICT for(var i=1; i<cnt; i++)//start form 1, skip NULL[0] m_Dict.Add( m_List[i], i); } else m_Dict.Add(reference, idx); return idx; } }//RefPool //this class works faster than List<object> as it skips un-needed bound checks and array clears internal struct QuickRefList { public QuickRefList(int capacity) { if (Ambient.MemoryModel < Ambient.MemoryUtilizationModel.Regular) capacity = capacity / 2; m_InitialCapacity = capacity; m_Data = new object[ capacity ]; m_Count = 1;//the "zeros" element is always NULL } private int m_InitialCapacity; private object[] m_Data; private int m_Count; public int Count{ get{ return m_Count;}} public object this[int i]{ get{ return m_Data[i];} } public void Clear() { var mm = Ambient.MemoryModel; var trimAt = mm < Ambient.MemoryUtilizationModel.Regular ? RefPool.POOL_CAPACITY : RefPool.LARGE_TRIM_THRESHOLD; if (m_Count>trimAt) //We want to get rid of excess data when too much { //otherwise the array will get stuck in pool cache for a long time m_Data = new object[ m_InitialCapacity ]; } else if (mm== Ambient.MemoryUtilizationModel.Tiny) { Array.Clear(m_Data, 0, m_Data.Length); } m_Count = 1;//[0]==null, dont clear //notice: no Array.Clear... for normal memory modes } public void Add(object reference) { var len = m_Data.Length; if (m_Count==len) { var newData = new object[2 * len]; Array.Copy(m_Data, 0, newData, 0, len); m_Data = newData; } m_Data[m_Count] = reference; m_Count++; } } }
31.588415
146
0.594537
[ "MIT" ]
JohnPKosh/azos
src/Azos/Serialization/Slim/RefPool.cs
10,361
C#
using ObserverPattern.Others; namespace ObserverPattern { partial class MainForm { /// <summary> /// Required designer variable. /// </summary> private System.ComponentModel.IContainer components = null; /// <summary> /// Clean up any resources being used. /// </summary> /// <param name="disposing">true if managed resources should be disposed; otherwise, false.</param> protected override void Dispose(bool disposing) { if (disposing && (components != null)) { components.Dispose(); } base.Dispose(disposing); } #region Windows Form Designer generated code /// <summary> /// Required method for Designer support - do not modify /// the contents of this method with the code editor. /// </summary> private void InitializeComponent() { System.ComponentModel.ComponentResourceManager resources = new System.ComponentModel.ComponentResourceManager(typeof(MainForm)); this.label1 = new System.Windows.Forms.Label(); this.ColorCombo = new ColorComboBoxApp.ColorComboBox(); this.SuspendLayout(); // // label1 // this.label1.AutoSize = true; this.label1.Location = new System.Drawing.Point(25, 53); this.label1.Name = "label1"; this.label1.Size = new System.Drawing.Size(71, 13); this.label1.TabIndex = 2; this.label1.Text = "Change Color"; // // ColorCombo // this.ColorCombo.DataSource = ((object)(resources.GetObject("ColorCombo.DataSource"))); this.ColorCombo.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed; this.ColorCombo.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList; this.ColorCombo.FormattingEnabled = true; this.ColorCombo.Location = new System.Drawing.Point(28, 69); this.ColorCombo.Name = "ColorCombo"; this.ColorCombo.SelectedColor = System.Drawing.Color.WhiteSmoke; this.ColorCombo.Size = new System.Drawing.Size(166, 21); this.ColorCombo.TabIndex = 3; this.ColorCombo.SelectedIndexChanged += new System.EventHandler(this.ColorCombo_SelectedIndexChanged); // // MainForm // this.AutoScaleDimensions = new System.Drawing.SizeF(6F, 13F); this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font; this.BackColor = System.Drawing.Color.WhiteSmoke; this.ClientSize = new System.Drawing.Size(222, 172); this.Controls.Add(this.ColorCombo); this.Controls.Add(this.label1); this.Name = "MainForm"; this.Text = "Observer Pattern"; this.ResumeLayout(false); this.PerformLayout(); } #endregion private System.Windows.Forms.Label label1; private ColorComboBoxApp.ColorComboBox ColorCombo; } }
38.925926
140
0.594037
[ "CC0-1.0" ]
Lenscorpx/GOF_DesignPatterns_Fun
ObserverPattern/MainForm.Designer.cs
3,155
C#
using System.Threading; namespace JBToolkit.Culture { /// <summary> /// Current culture helper /// </summary> public class CultureHelper { /// <summary> /// GB uses the date format: dd-MM-yyyy /// </summary> public static void GloballySetCultureToGB() { var culture = new System.Globalization.CultureInfo("en-GB"); Thread.CurrentThread.CurrentCulture = culture; Thread.CurrentThread.CurrentUICulture = culture; } } }
26.3
72
0.591255
[ "MIT" ]
fcrimins/YTMusicUploader
YTMusicUploader/Helpers/CultureHelper.cs
528
C#
// <auto-generated> // Generated by the protocol buffer compiler. DO NOT EDIT! // source: google/ads/googleads/v1/services/geographic_view_service.proto // </auto-generated> #pragma warning disable 1591, 0612, 3021 #region Designer generated code using pb = global::Google.Protobuf; using pbc = global::Google.Protobuf.Collections; using pbr = global::Google.Protobuf.Reflection; using scg = global::System.Collections.Generic; namespace Google.Ads.GoogleAds.V1.Services { /// <summary>Holder for reflection information generated from google/ads/googleads/v1/services/geographic_view_service.proto</summary> public static partial class GeographicViewServiceReflection { #region Descriptor /// <summary>File descriptor for google/ads/googleads/v1/services/geographic_view_service.proto</summary> public static pbr::FileDescriptor Descriptor { get { return descriptor; } } private static pbr::FileDescriptor descriptor; static GeographicViewServiceReflection() { byte[] descriptorData = global::System.Convert.FromBase64String( string.Concat( "Cj5nb29nbGUvYWRzL2dvb2dsZWFkcy92MS9zZXJ2aWNlcy9nZW9ncmFwaGlj", "X3ZpZXdfc2VydmljZS5wcm90bxIgZ29vZ2xlLmFkcy5nb29nbGVhZHMudjEu", "c2VydmljZXMaN2dvb2dsZS9hZHMvZ29vZ2xlYWRzL3YxL3Jlc291cmNlcy9n", "ZW9ncmFwaGljX3ZpZXcucHJvdG8aHGdvb2dsZS9hcGkvYW5ub3RhdGlvbnMu", "cHJvdG8iMQoYR2V0R2VvZ3JhcGhpY1ZpZXdSZXF1ZXN0EhUKDXJlc291cmNl", "X25hbWUYASABKAky1wEKFUdlb2dyYXBoaWNWaWV3U2VydmljZRK9AQoRR2V0", "R2VvZ3JhcGhpY1ZpZXcSOi5nb29nbGUuYWRzLmdvb2dsZWFkcy52MS5zZXJ2", "aWNlcy5HZXRHZW9ncmFwaGljVmlld1JlcXVlc3QaMS5nb29nbGUuYWRzLmdv", "b2dsZWFkcy52MS5yZXNvdXJjZXMuR2VvZ3JhcGhpY1ZpZXciOYLT5JMCMxIx", "L3YxL3tyZXNvdXJjZV9uYW1lPWN1c3RvbWVycy8qL2dlb2dyYXBoaWNWaWV3", "cy8qfUKBAgokY29tLmdvb2dsZS5hZHMuZ29vZ2xlYWRzLnYxLnNlcnZpY2Vz", "QhpHZW9ncmFwaGljVmlld1NlcnZpY2VQcm90b1ABWkhnb29nbGUuZ29sYW5n", "Lm9yZy9nZW5wcm90by9nb29nbGVhcGlzL2Fkcy9nb29nbGVhZHMvdjEvc2Vy", "dmljZXM7c2VydmljZXOiAgNHQUGqAiBHb29nbGUuQWRzLkdvb2dsZUFkcy5W", "MS5TZXJ2aWNlc8oCIEdvb2dsZVxBZHNcR29vZ2xlQWRzXFYxXFNlcnZpY2Vz", "6gIkR29vZ2xlOjpBZHM6Okdvb2dsZUFkczo6VjE6OlNlcnZpY2VzYgZwcm90", "bzM=")); descriptor = pbr::FileDescriptor.FromGeneratedCode(descriptorData, new pbr::FileDescriptor[] { global::Google.Ads.GoogleAds.V1.Resources.GeographicViewReflection.Descriptor, global::Google.Api.AnnotationsReflection.Descriptor, }, new pbr::GeneratedClrTypeInfo(null, new pbr::GeneratedClrTypeInfo[] { new pbr::GeneratedClrTypeInfo(typeof(global::Google.Ads.GoogleAds.V1.Services.GetGeographicViewRequest), global::Google.Ads.GoogleAds.V1.Services.GetGeographicViewRequest.Parser, new[]{ "ResourceName" }, null, null, null) })); } #endregion } #region Messages /// <summary> /// Request message for [GeographicViewService.GetGeographicView][google.ads.googleads.v1.services.GeographicViewService.GetGeographicView]. /// </summary> public sealed partial class GetGeographicViewRequest : pb::IMessage<GetGeographicViewRequest> { private static readonly pb::MessageParser<GetGeographicViewRequest> _parser = new pb::MessageParser<GetGeographicViewRequest>(() => new GetGeographicViewRequest()); private pb::UnknownFieldSet _unknownFields; [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pb::MessageParser<GetGeographicViewRequest> Parser { get { return _parser; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public static pbr::MessageDescriptor Descriptor { get { return global::Google.Ads.GoogleAds.V1.Services.GeographicViewServiceReflection.Descriptor.MessageTypes[0]; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] pbr::MessageDescriptor pb::IMessage.Descriptor { get { return Descriptor; } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetGeographicViewRequest() { OnConstruction(); } partial void OnConstruction(); [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetGeographicViewRequest(GetGeographicViewRequest other) : this() { resourceName_ = other.resourceName_; _unknownFields = pb::UnknownFieldSet.Clone(other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public GetGeographicViewRequest Clone() { return new GetGeographicViewRequest(this); } /// <summary>Field number for the "resource_name" field.</summary> public const int ResourceNameFieldNumber = 1; private string resourceName_ = ""; /// <summary> /// The resource name of the geographic view to fetch. /// </summary> [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public string ResourceName { get { return resourceName_; } set { resourceName_ = pb::ProtoPreconditions.CheckNotNull(value, "value"); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override bool Equals(object other) { return Equals(other as GetGeographicViewRequest); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public bool Equals(GetGeographicViewRequest other) { if (ReferenceEquals(other, null)) { return false; } if (ReferenceEquals(other, this)) { return true; } if (ResourceName != other.ResourceName) return false; return Equals(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override int GetHashCode() { int hash = 1; if (ResourceName.Length != 0) hash ^= ResourceName.GetHashCode(); if (_unknownFields != null) { hash ^= _unknownFields.GetHashCode(); } return hash; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public override string ToString() { return pb::JsonFormatter.ToDiagnosticString(this); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void WriteTo(pb::CodedOutputStream output) { if (ResourceName.Length != 0) { output.WriteRawTag(10); output.WriteString(ResourceName); } if (_unknownFields != null) { _unknownFields.WriteTo(output); } } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public int CalculateSize() { int size = 0; if (ResourceName.Length != 0) { size += 1 + pb::CodedOutputStream.ComputeStringSize(ResourceName); } if (_unknownFields != null) { size += _unknownFields.CalculateSize(); } return size; } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(GetGeographicViewRequest other) { if (other == null) { return; } if (other.ResourceName.Length != 0) { ResourceName = other.ResourceName; } _unknownFields = pb::UnknownFieldSet.MergeFrom(_unknownFields, other._unknownFields); } [global::System.Diagnostics.DebuggerNonUserCodeAttribute] public void MergeFrom(pb::CodedInputStream input) { uint tag; while ((tag = input.ReadTag()) != 0) { switch(tag) { default: _unknownFields = pb::UnknownFieldSet.MergeFieldFrom(_unknownFields, input); break; case 10: { ResourceName = input.ReadString(); break; } } } } } #endregion } #endregion Designer generated code
39.664948
233
0.71371
[ "Apache-2.0" ]
chrisdunelm/google-ads-dotnet
src/V1/Stubs/GeographicViewService.cs
7,695
C#
// borrowed shamelessly and enhanced from Bag of Tricks https://www.nexusmods.com/pathfinderkingmaker/mods/26, which is under the MIT License using HarmonyLib; using Kingmaker; //using Kingmaker.Controllers.GlobalMap; using Kingmaker.EntitySystem.Entities; using Kingmaker.EntitySystem.Stats; //using Kingmaker.UI._ConsoleUI.Models; //using Kingmaker.UI.RestCamp; using Kingmaker.UnitLogic; using Kingmaker.UnitLogic.Class.LevelUp; using System; //using Kingmaker.UI._ConsoleUI.GroupChanger; using UnityModManager = UnityModManagerNet.UnityModManager; namespace ToyBox.BagOfPatches { internal static class NewChar { public static Settings settings = Main.settings; public static Player player = Game.Instance.Player; // public LevelUpState([NotNull] UnitEntityData unit, LevelUpState.CharBuildMode mode, bool isPregen) [HarmonyPatch(typeof(LevelUpState), MethodType.Constructor)] [HarmonyPatch(new Type[] { typeof(UnitEntityData), typeof(LevelUpState.CharBuildMode), typeof(bool) })] public static class LevelUpState_Patch { [HarmonyPriority(Priority.Low)] public static void Postfix(UnitDescriptor unit, LevelUpState.CharBuildMode mode, ref LevelUpState __instance, bool isPregen) { if (__instance.IsFirstCharacterLevel) { if (!__instance.IsPregen) { // Kludge - there is some weirdness where the unit in the character generator does not return IsCustomCharacter() as true during character creation so I have to check the blueprint. The thing is if I actually try to get the blueprint name the game crashes so I do this kludge calling unit.Blueprint.ToString() var isCustom = unit.Blueprint.ToString() == "CustomCompanion"; //Logger.Log($"unit.Blueprint: {unit.Blueprint.ToString()}"); //Logger.Log($"not pregen - isCust: {isCustom}"); var pointCount = Math.Max(0, isCustom ? settings.characterCreationAbilityPointsMerc : settings.characterCreationAbilityPointsPlayer); //Logger.Log($"points: {pointCount}"); __instance.StatsDistribution.Start(pointCount); } } } } [HarmonyPatch(typeof(StatsDistribution), nameof(StatsDistribution.CanRemove))] public static class StatsDistribution_CanRemove_Patch { public static void Postfix(ref bool __result, StatType attribute, StatsDistribution __instance) { if (settings.characterCreationAbilityPointsMin != 7) { __result = __instance.Available && __instance.StatValues[attribute] > settings.characterCreationAbilityPointsMin; } } } [HarmonyPatch(typeof(StatsDistribution), nameof(StatsDistribution.CanAdd))] public static class StatsDistribution_CanAdd_Patch { public static void Prefix() { } public static void Postfix(ref bool __result, StatType attribute, StatsDistribution __instance) { var attributeMax = settings.characterCreationAbilityPointsMax; if (!__instance.Available) { __result = false; } else { if (attributeMax <= 18) { attributeMax = 18; } var attributeValue = __instance.StatValues[attribute]; __result = attributeValue < attributeMax && __instance.GetAddCost(attribute) <= __instance.Points; } } } [HarmonyPatch(typeof(StatsDistribution), nameof(StatsDistribution.GetAddCost))] public static class StatsDistribution_GetAddCost_Patch { public static bool Prefix(StatsDistribution __instance, StatType attribute) { var attributeValue = __instance.StatValues[attribute]; return attributeValue > 7 && attributeValue < 17; } public static void Postfix(StatsDistribution __instance, ref int __result, StatType attribute) { var attributeValue = __instance.StatValues[attribute]; if (attributeValue <= 7) { __result = 2; } if (attributeValue >= 17) { __result = 4; } } } [HarmonyPatch(typeof(StatsDistribution), nameof(StatsDistribution.GetRemoveCost))] public static class StatsDistribution_GetRemoveCost_Patch { public static bool Prefix(StatsDistribution __instance, StatType attribute) { var attributeValue = __instance.StatValues[attribute]; return attributeValue > 7 && attributeValue < 17; } public static void Postfix(StatsDistribution __instance, ref int __result, StatType attribute) { var attributeValue = __instance.StatValues[attribute]; if (attributeValue <= 7) { __result = -2; } else if (attributeValue >= 17) { __result = -4; } } } } }
50.788462
333
0.623249
[ "MIT" ]
Aephiex/ToyBox
ToyBox/classes/MonkeyPatchin/BagOfPatches/NewChar.cs
5,284
C#
using System; using System.Collections.Generic; using UnityEngine; using System.Collections; using Zenject; #pragma warning disable 649 #pragma warning disable 618 namespace Zenject.Asteroids { public class Ship : MonoBehaviour { [SerializeField] MeshRenderer _meshRenderer; #if !UNITY_2018 [SerializeField] ParticleEmitter _particleEmitter; #endif ShipStateFactory _stateFactory; ShipState _state = null; [Inject] public void Construct(ShipStateFactory stateFactory) { _stateFactory = stateFactory; } public MeshRenderer MeshRenderer { get { return _meshRenderer; } } #if !UNITY_2018 public ParticleEmitter ParticleEmitter { get { return _particleEmitter; } } #endif public Vector3 Position { get { return transform.position; } set { transform.position = value; } } public Quaternion Rotation { get { return transform.rotation; } set { transform.rotation = value; } } public void Start() { ChangeState(ShipStates.WaitingToStart); } public void Update() { _state.Update(); } public void OnTriggerEnter(Collider other) { _state.OnTriggerEnter(other); } public void ChangeState(ShipStates state) { if (_state != null) { _state.Dispose(); _state = null; } _state = _stateFactory.CreateState(state); _state.Start(); } } }
20.583333
60
0.549451
[ "MIT" ]
MizoTake/SuperPK
Assets/Plugins/Zenject/OptionalExtras/SampleGame1 (Beginner)/Scripts/Ship/Ship.cs
1,729
C#